Skip to content

Commit aa2e10d

Browse files
Updated to pubScribe and added hypothetical DAC example.
1 parent 6261053 commit aa2e10d

File tree

3 files changed

+108
-74
lines changed

3 files changed

+108
-74
lines changed

mcp4725.py

Lines changed: 38 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
4242
4343
RASPBERRY PI I2C PINS to DAC (2-wires plus power and ground):
44-
RPI 40-pin MCP4275 DAC in 6-pin SOT-23-6
44+
RPI 40-pin MCP4725 DAC in 6-pin SOT-23-6
4545
= Pin 1 Vout
4646
= Pin 2 Vss (ground reference)
4747
= Pin 3 Vdd (2.7V - 5.5V)
@@ -69,21 +69,17 @@
6969
import smbus # I2C support
7070

7171

72-
class mcp4275 :
72+
class mcp4725 :
7373
def __init__(self) :
7474
self.OUTPUT_MAX = 4095 # 2^12-1 counts
7575

7676
# I2C address is not 0x62 or 0x63 per the data sheet, but 0x60
7777
self.i2c_address = 0x60
7878
print("mcp4275 i2c address: " + hex(self.i2c_address))
7979

80-
# initialize bus
81-
i2c_ch = 1 # i2c channel
82-
self.bus=smbus.SMBus(i2c_ch) # Initialize I2C (SMBus)
83-
8480

8581
def __del__(self) :
86-
self.bus.close()
82+
return
8783

8884

8985
def writeDAC(self, value):
@@ -117,6 +113,34 @@ def writeDAC(self, value):
117113

118114
return
119115

116+
def alg(self, data):
117+
print("Alg data: ", data)
118+
119+
#
120+
# Insert algorithm here...
121+
# Hypothetical example. Not tested.
122+
#
123+
124+
fanMin = 0.5
125+
fanMax = 0.9
126+
radonMin = 40
127+
RadonMax = 150
128+
SF = (fanMax - fanMin) / (radonMax - radonMin)
129+
130+
fanValue = fanMin + (data[0] - radonMin) * SF
131+
132+
if fanValue > fanMax :
133+
fanValue = fanMax
134+
elif fanValue < fanMin :
135+
fanValue = fanMin
136+
137+
print("FanValue: ", fanValue)
138+
139+
self.writeDAC(fanValue)
140+
141+
return
142+
143+
120144
# end class
121145

122146

@@ -125,7 +149,11 @@ def writeDAC(self, value):
125149
print("Press CTRL+C to exit...")
126150

127151
try:
128-
dac = mcp4275()
152+
dac = mcp4725()
153+
154+
# initialize bus
155+
i2c_ch = 1 # i2c channel
156+
dac.bus=smbus.SMBus(i2c_ch) # Initialize I2C (SMBus)
129157

130158
while True:
131159
print("Enter value (0.0 - 1.0): ")
@@ -134,3 +162,5 @@ def writeDAC(self, value):
134162

135163
except KeyboardInterrupt:
136164
print(" Keyboard interrupt caught, exiting.")
165+
166+
dac.bus.close()

radonMasterPlot.py

Lines changed: 57 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
REVISION HISTORY
1010
DATE AUTHOR CHANGES
1111
yyyy/mm/dd --------------- -------------------------------------
12+
2021/03/01 BrucesHobbies Revised default log file names
13+
2021/03/05 BrucesHobbies Updated for pubScribe
1214
1315
1416
OVERVIEW:
@@ -53,107 +55,108 @@
5355
#
5456
# Read in a comma seperated variable file. Assumes a header row exists.
5557
# Time series with time in seconds in first column.
58+
# Ignore text string with date/time from second column
59+
# data is columns [2:]
5660
#
5761
def importCsv(filename) :
5862
print("Reading " + filename)
5963

6064
with open(filename, 'r') as csvfile :
61-
data = list(csv.reader(csvfile))
65+
csvData = list(csv.reader(csvfile))
6266

63-
header = data[0]
64-
print(header)
67+
hdr = csvData[0]
68+
print(hdr)
6569

66-
a = np.array(data[1:], dtype=np.float)
70+
tStamp = []
71+
for row in csvData[1:] :
72+
tStamp.append(float(row[0]))
6773

68-
print("Elements: ", a.size)
69-
print("Rows : ", len(a[:,0]))
70-
print("Cols : ", len(a[0,:]))
74+
data = {name : [] for name in hdr[2:]}
75+
# print(data)
76+
77+
for row in csvData[1:] :
78+
for idx in range(2,len(hdr)) :
79+
n = float(row[idx])
80+
if n == -99 :
81+
n = np.nan
82+
data[hdr[idx]].append(n)
83+
84+
return hdr[2:], tStamp, data
7185

72-
return header, a
7386

7487
#
75-
# Plot Short-Term and Long-Term radon levels
76-
# thresholds(y_value,"label")
88+
# Plot single or multiple variables {"key":[]} on common subplot
7789
#
78-
def plotRadon(thresholds) :
90+
def plotMultiVar(tStamp, data, title) :
91+
92+
t = [datetime.datetime.fromtimestamp(ts) for ts in tStamp]
93+
7994
fig = plt.figure()
8095
ax1 = fig.add_subplot(1, 1, 1)
8196

82-
ax1.plot(t, a[:,1], 'b', label='ST')
83-
ax1.plot(t, a[:,2], 'r', label='LT')
84-
# ax1.plot(t, a[:,1], 'b', marker='d', label='ST')
85-
# ax1.plot(t, a[:,2], 'r', marker='d', label='LT')
97+
for item in data :
98+
# print(item)
99+
ax1.plot(t, data[item], label=item)
100+
# ax1.plot(t, data[item], marker='d', label=item)
86101

87-
for item in thresholds :
88-
ax1.plot([t[0], t[len(t)-1]], [item[0], item[0]], item[1])
102+
ax1.set_title(title)
89103

90-
ax1.set_title("Radon")
91-
ax1.set_xlabel('Time')
92-
ax1.set_ylabel(header[1][9:])
93-
ax1.legend(loc='upper right', shadow=True)
104+
if len(data) > 1 :
105+
ax1.legend(loc='upper right', shadow=True)
106+
else :
107+
ax1.set_ylabel(item)
94108

95109
ax1.grid(which='both')
110+
96111
plt.gcf().autofmt_xdate() # slant labels
97112
dateFmt = mdates.DateFormatter('%Y-%m-%d %H:%M')
98113
plt.gca().xaxis.set_major_formatter(dateFmt)
99114

100-
plt.show(block=False)
101115

102116
#
103-
# Plot VOC, CO2, Temperature, Relative, Humidity, and air pressure
117+
# Plot single variable {"item":[]}
104118
#
105-
def plotSingle(var, ylabel, title) :
119+
def plotSingleVar(tStamp, data, title, item) :
120+
121+
t = [datetime.datetime.fromtimestamp(ts) for ts in tStamp]
122+
106123
fig = plt.figure()
107124
ax1 = fig.add_subplot(1, 1, 1)
108125

109-
ax1.plot(t, var)
110-
# ax1.plot(t, var, marker='d')
126+
ax1.plot(t, data[item], label=item)
127+
# ax1.plot(t, data[item], marker='d', label=item)
111128

112129
ax1.set_title(title)
113-
ax1.set_xlabel('Time')
114-
ax1.set_ylabel(ylabel)
115-
130+
ax1.set_ylabel(item)
131+
116132
ax1.grid(which='both')
133+
117134
plt.gcf().autofmt_xdate() # slant labels
118135
dateFmt = mdates.DateFormatter('%Y-%m-%d %H:%M')
119136
plt.gca().xaxis.set_major_formatter(dateFmt)
120137

121-
plt.show(block=False)
122138

123139
#
124140
# Plot two files
125141
#
126142
if __name__ == "__main__" :
127143

128-
# --- Radon Short-term and Long-term ---
129-
# (time in column 0, data in columns 1 - 2)
130-
# filename = "radonLogFile.csv"
131-
filename = "waveLogFile.csv"
132-
header, a = importCsv(filename)
133-
134-
tstamp = []
135-
for item in a[:,0] :
136-
tstamp.append(item)
137-
t = [datetime.datetime.fromtimestamp(ts) for ts in tstamp]
138-
139-
plotRadon([(1.3, 'g--'),(2.7, 'y--'),(4.0, 'r--')])
140-
141-
# Plot remaining data from WavePlus (columns 4 - 8)
142-
for col in range(3, len(header)-1) :
143-
plotSingle(a[:,col],header[col],header[col])
144+
# --- WavePlus data ---
145+
# (time in column 0, data in columns 2:)
146+
filename = "RadonMaster_WavePlus.csv"
147+
header, tStamp, data = importCsv(filename)
144148

149+
for item in data :
150+
plotSingleVar(tStamp, data, filename[:-4], item)
145151

146152
# --- Mitigation fan pressure ---
147-
filename = "radonMaster.csv"
148-
header, a = importCsv(filename)
149-
150-
tstamp = []
151-
for item in a[:,0] :
152-
tstamp.append(item)
153-
t = [datetime.datetime.fromtimestamp(ts) for ts in tstamp]
153+
filename = "RadonMaster_PresSensor.csv"
154+
header, tStamp, data = importCsv(filename)
154155

155-
plotSingle(a[:,1],'Inches W.C.','Mitigation Fan Vacuum')
156+
plotMultiVar(tStamp, data, 'Mitigation Fan Vacuum')
156157

157158
# Pause to close plots
159+
plt.show(False) # Blocks, user must close plot window
160+
print("")
158161
input("Press [enter] key to close plots...")
159162
print("Done...")

wave.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,15 @@
5858

5959
import pubScribe
6060

61+
MCP4725_ENABLED = 0
62+
63+
if MCP4725_ENABLED :
64+
import mcp4725
65+
dac = mcp4725.mcp4725()
66+
# initialize bus
67+
# i2c_ch = 1 # i2c channel
68+
# dac.bus=smbus.SMBus(i2c_ch) # Initialize I2C (SMBus)
69+
6170

6271
SerialNumber = 0
6372

@@ -66,7 +75,6 @@
6675
MODE='terminal'
6776

6877
LOGGING_ENABLED = 1
69-
# wpLogFilename = "waveLogFile.csv"
7078

7179
#
7280
# find_wave and read_waveplus both require bluepy, SerialNumber==0 indicates bluepy lib or wave not found
@@ -285,11 +293,6 @@ def writeHeaders() :
285293
# print(hdrRow[5:])
286294
print(hdrRow)
287295

288-
"""
289-
if LOGGING_ENABLED and not os.path.isfile(wpLogFilename) :
290-
# If csv log file does not exist, write header
291-
write2Csv(hdrRow)
292-
"""
293296

294297

295298
#
@@ -327,19 +330,17 @@ def readAirthings() :
327330

328331
if LOGGING_ENABLED :
329332
data = [radon_st_avg, radon_lt_avg, VOC_lvl, CO2_lvl, temperature, humidity, pressure]
330-
"""
331-
rowStr = str(round(time.time())) + ","
332-
for item in data :
333-
rowStr = rowStr + str(item) + ","
334-
write2Csv(rowStr[:-1])
335-
"""
336333
topic = "RadonMaster/WavePlus"
337334
pubScribe.pubRecord(pubScribe.CSV_FILE, topic, data, hdrRow)
338335

339336
results = formatLocalTime() + " " + str(sensor2StringUnits(sensors))
340337

341338
alert, s = checkAlerts(radon_st_avg, VOC_lvl, CO2_lvl, temperature, humidity)
342339

340+
if MCP4725_ENABLED :
341+
dac.alg(data)
342+
343+
343344
except :
344345
print("Exception!!!")
345346
waveplus.disconnect()

0 commit comments

Comments
 (0)