def calc_vswr(ant, f, r): """Calculates the Voltage Standing Wave Ratio (VSWR) for a given antenna. Arguments: ant -- The antenna height (aquired from the config file) f -- Analog I/O pin on the DAQCplate board to read r -- Analog I/O pin on the DAQCplate board to read """ # fwdcalfac = get_calfac(f) # revcalfac = get_calfac(r) f = abs(DAQC.getADC(0, f)) r = abs(DAQC.getADC(0, r)) # TODO For normalizing elements when true test rig is ready # f=f-fwdcalfac # r=r-revcalfac # Need to divide voltage by 50 ohm to get current, multiply current times voltage to get watts x = abs(1 + math.sqrt(rm_utils.safe_div(r, f))) y = abs(1 - math.sqrt(rm_utils.safe_div(r, f))) swr = round(rm_utils.safe_div(x, y), 3) if swr > 3.0: logger.warning( "calc_vswr: Ant Height: {} SWR: \033[91m {} \033[0m".format( ant, swr)) if DEBUG: print("Ant Height: {} SWR: \033[91m {} \033[0m".format(ant, swr)) else: if DEBUG: print("Ant Height: {} SWR: \033[92m {} \033[0m".format(ant, swr)) return swr
def logData(self): global data if (self.logstate.get() == "Logging"): print "Logging..." sampleSet = np.zeros(shape=[10, 1]) for x in range(10): sampleSet[x] = DAQC.getADC(0, self.sumChannel) averageSum = np.mean(sampleSet) data = np.append( data, [[DAQC.getADC(0, self.tempChannel), averageSum, fb_bias]], axis=0) root.after(self.subInterval.get(), self.logData)
def sample(channel): """ Callback function for button interrupt that causes a sample to be taken from both sensors. """ time.sleep(0.1) print("Button pushed!") DAQC.getINTflags(0) # clear the interrupt # use light strobes to indicate measurement DAQC.setDOUTall(0, 0) for j in range(7): DAQC.setDOUTbit(0, j) time.sleep(0.1) DAQC.clrDOUTbit(0, j) time.sleep(0.1) # measure from the BME280 (ORDER MATTERS!) temp = sensor.read_temperature() pressure = sensor.read_pressure() / 100. # convert to hectopascals humidity = sensor.read_humidity() t = sensor.t_fine # measure from the (analog) photo-sensor light = DAQC.getADC(0, 0) global data data.append([t, temp, pressure, humidity, light]) # turn off LEDs DAQC.setDOUTall(0, 0)
def __init__(self, master, channel, r, c): self.master = master self.channel = channel self.tm = Frame(self.master, padx=4, pady=4, bd=2, relief='sunken') self.tm.grid(row=r, column=c, sticky=N + S + W + E) ##Font self.heading = tkFont.Font(family='Helvetica', size=18, weight='bold') ##Title self.labelt = Label(self.tm, text="Temperature (C):", padx=4, pady=4, font=self.heading) self.labelt.grid(row=0, sticky=W + E) ##display self.temp = DoubleVar() self.temp.set(18.14 * DAQC.getADC(0, channel) - 20.32) self.tempLabel = Label(self.tm, textvariable=self.temp, font=self.heading, fg='green') self.tempLabel.grid(row=1, sticky=W + E) ##update button, until better solution found self.buttonu = Button(self.tm, text="Update", command=self.update, padx=4, pady=4) self.buttonu.grid(row=2, sticky=W + E)
def task(): global lastT global lastR global lastSW global swMode global GC adata = DAQC.getADCall(3) val = round(DAQC.getADC(0, 8), 1) Power5Text.set(val) val = round((adata[1] - 2.73) * 100, 2) val = 0.2 * val + 0.8 * lastT lastT = val TempText.set(str("{:>3.1f}".format(val)) + 'C') val = round(adata[2] * 12.21 / 1.636, 1) Power12Text.set(val) val = round(adata[0] / 4.096 * 100, 1) FanText.set(str(val) + '%') DAQC.setPWM(0, 0, int(val * 1024 / 100)) val = DAQC.getRANGE(0, 6, 'c') if isinstance(val, float): if val > 100: val = 99.9 else: val = 0 val = round(val, 1) val = 0.8 * lastR + 0.2 * val lastR = val RangeText.set(str("{:>2.1f}".format(val)) + 'cm') lamp = 0 if (DAQC.getDINbit(0, 2) == 1): lamp = 32 sw = DAQC.getSWstate(0) if (sw == 1) and (lastSW == 0): lastSW = 1 swMode = not swMode if swMode: GCmode.set('Binary Code :') else: GCmode.set('Grey Code :') if (sw == 0) and (lastSW == 1): lastSW = 0 val = (int(adata[7] * 32 / 4.096)) if swMode == 0: GCText.set(GC[val]) num = GC[val] else: GCText.set(val) num = val DAQC.setDOUTall(0, (num + lamp)) root.after(100, task)
def Curr(addr, bit): Vmax = 0.0 for x in range (0,128): Vin = daqc.getADC(addr, bit) Vin = (Vin - V_OFFSET) if Vin > Vmax: Vmax = Vin return (Vmax * 30)
def update(self): if (self.var.get() == 1): self.val.set(DAQC.getADC(self.addr, self.chan)) self.valstring.set(str("{:5.3f}".format(self.val.get()))) self.log[self.nextPtr] = self.val.get() self.nextPtr = (self.nextPtr + 1) % self.maxrange self.plot() return self.val.get() else: return ''
def Vrms(plate, addr): Vmax = 0 Vmin = 1000 for x in range(0,200): Vin = (daqc.getADC(plate ,addr) - V_OFFSET) if Vin > Vmax: Vmax = Vin if Vin < Vmin: Vmin = Vin Veff = Vmax * V_RATIO return Veff
def main(): signal.signal(signal.SIGINT, signal_handler) while True: value = round(DAQC.getADC(0, DACport), 2) if (value < 3.20) or (value > 3.7) : print "Value " + str(value) + ", Activated!" DAQC.setDOUTbit(0,0) playAudio() DAQC.clrDOUTbit(0,0) else: print "Value " + str(value) + ", Waiting..." time.sleep(0.1) GPIO.cleanup()
def __init__(self, root, addr, channel): self.addr = addr self.root = root self.chan = channel self.var = IntVar() #This is the select button for each channel self.var.set(1) self.val = DoubleVar() self.val.set(DAQC.getADC(self.addr, self.chan)) self.valstring = StringVar() self.valstring.set(str(self.val.get())) off = H - 2 - 17 * SLICE + self.chan * SLICE BG = '#888FFFFFF' self.CWidth = int(.75 * W + 20) self.a2df = Frame(self.root, bg=BG, bd=0, relief="ridge") self.a2df.place(x=0, y=off, width=W, height=SLICE) self.a2dc = Checkbutton(self.a2df, fg="Black", bg=BG, variable=self.var, onvalue=1, offvalue=0, command=self.cb) self.a2dc.grid(row=0, column=0, sticky="w") self.var.set(1) self.a2dl = StringVar(root, value="A2D Channel " + str(self.chan) + ":") self.a2dt = Label(self.a2df, textvariable=self.valstring, fg="Black", bg=BG, width=5).grid(row=0, column=2, sticky="w") self.a2dtxt = Entry(self.a2df, textvariable=self.a2dl, fg="Black", bg=BG, bd=0, relief="flat", width=12) self.a2dtxt.grid(row=0, column=1, sticky="w") self.a2dcanvas = Canvas(self.a2df, bg=BG, width=self.CWidth, height=SLICE, bd=0, relief="flat") self.a2dcanvas.grid(row=0, column=3, sticky="e") self.maxrange = self.CWidth self.log = range(self.maxrange) for i in range(self.maxrange): self.log[i] = 0.0 self.nextPtr = 0
def plot_update(): global voltages global currents x.append(len(x)) voltage1 = DAQC.getADC(0, 0) voltage2 = DAQC.getADC(0, 1) voltage3 = DAQC.getADC(0, 2) voltage4 = DAQC.getADC(0, 3) voltage5 = DAQC.getADC(0, 4) voltage6 = DAQC.getADC(0, 5) voltage7 = DAQC.getADC(0, 6) voltage8 = DAQC.getADC(0, 7) voltages1.append(voltage1) voltages2.append(voltage2) voltages3.append(voltage3) voltages4.append(voltage4) voltages5.append(voltage5) voltages6.append(voltage6) voltages7.append(voltage7) voltages8.append(voltage8) length = len(x) source.data = dict(x=x, voltages1=voltages1, voltages2=voltages2, voltages3=voltages3, voltages4=voltages4, voltages5=voltages5, voltages6=voltages6, voltages7=voltages7, voltages8=voltages8) change = str(length).strip() + "," + str(datetime.datetime.now( )) + "," + str(time.time() - t0) + "," + str(voltage1).strip( ) + "," + str(voltage2).strip() + "," + str(voltage3).strip() + "," + str( voltage4).strip() + str(voltage5).strip() + "," + str(voltage6).strip( ) + "," + str(voltage7).strip() + "," + str(voltage8).strip() + "," with open(os.path.join(directory_control.value, file_control.value), 'a') as f: # writer = csv.writer(f) f.write(change) f.write("\n") f.close()
def __init__(self, master, title, channel, r, c): self.master = master self.channel = channel self.tm = Frame(self.master, padx=4, pady=4, bd=2, relief='sunken') self.tm.grid(row=r, column=c, sticky=N + S + W + E) ##Fonts self.title = tkFont.Font(family='Helvetica', size=24, weight='bold') self.heading = tkFont.Font(family='Helvetica', size=16, weight='bold') self.normal = tkFont.Font(family='Helvetica', size=14) ##Title self.labelt = Label(self.tm, text=title, padx=4, pady=4, font=self.title) self.labelt.grid(row=0, column=0, columnspan=2, sticky=W + E) ##display self.labelv1 = Label(self.tm, text="Voltage:", font=self.heading, anchor=E) self.labelv1.grid(row=1, column=0, sticky=W + E) self.tvoltage = DoubleVar() self.tvoltage.set(DAQC.getADC(0, channel)) self.labelv2 = Label(self.tm, textvariable=self.tvoltage, font=self.heading, fg='green', anchor=W) self.labelv2.grid(row=1, column=1, sticky=W + E) ##update button, until better solution found self.buttonu = Button(self.tm, text="Update", command=self.update, padx=4, pady=4) self.buttonu.grid(row=2, column=0, columnspan=2, sticky=W + E)
import time ppADDR = 1 adADDR = 1 cooler_rly = 7 ADCchan = 6 temp_slope = 108.43 temp_inter = -135 temp_setpoint = 67.0 temp_hyster = 4.0 try: while True: adcread = DAQC.getADC(adADDR, ADCchan) print('Temp voltage: ', adcread) temp_val = adcread * temp_slope + temp_inter print('Temp: ', temp_val) if temp_val > temp_setpoint + temp_hyster: RELAY.relayON(ppADDR, cooler_rly) print('Cooling') if temp_val <= temp_setpoint: RELAY.relayOFF(ppADDR, cooler_rly) print('Optimal Temperature Achieved') time.sleep(10) except KeyboardInterrupt:
def readPress(): v = DAQC.getADC(0, 0) vs = DAQC.getADC(0, 8) return (v/vs+0.095)/0.009
from __future__ import print_function import piplates.RELAYplate as RELAY import piplates.DAQCplate as DAQC import time ppADDR = 1 ADCchan = 0 print('reading adc channel', ADCchan) while True: adcread = DAQC.getADC(ppADDR, ADCchan) print("ADC reading #, val: ", ADCchan, adcread) time.sleep(1.0) ADCchan = ADCchan + 1 if ADCchan > 7: ADCchan = 0
import numpy as np import piplates.DAQCplate as DAQC parser = argparse.ArgumentParser(description='Acquire Data from Pi Plate') parser.add_argument('-f', '--fsample', dest='sample_frequency', metavar='fs', type=float, default=1, help='ADC sample frequency [Hz]') args = parser.parse_args() fs = args.sample_frequency if __debug__: print("Sample Frequency is " + str(fs) + " Hz") if fs < 1e-5: parser.error("Error: sample rate must be > 1e-5 Hz") # this is the main loop j = 0 while j < 10: x = DAQC.getADC(0, 1) if __debug__: print x j += 1 time.sleep(1 / fs) # this is the output when its done running # should also catch the CTRL-C
def getValues(self, address, count=1): caddress = self.corrected_address(address) value = dp.getADC(self._board_address, caddress) self.log('read {} from board {} input {}'.format( value, self._board_address, caddress)) return self._pack_float(value)
return tempc def log(fp, data): print(*data, sep=',', file=fp) fp.flush() fp = open("/var/tmp/heatpump.csv", "w+") start_http_server(8000) running_g = Gauge('heatpump_running', 'Is the compressor running?') top_g = Gauge('heatpump_toptemp', 'Temperature at top of tank.') return_g = Gauge('heatpump_returntemp', 'Temperature at inlet sensor.') gas_g = Gauge('heatpump_hottemp', 'Temperature at Hot Gas side sensor.') while (True): vv_retur = temp_get(DAQC.getADC(0, 0), DAQC.getADC(0, 8)) vv_top = temp_get(DAQC.getADC(0, 2), DAQC.getADC(0, 8)) hetgas = temp_get(DAQC.getADC(0, 1), DAQC.getADC(0, 8)) print("VV retur:", vv_retur) print("VV top:", vv_top) print("Hetgas:", hetgas) print("Kompressor:", compressor()) log(fp, [vv_retur, vv_top, hetgas, str(compressor()[0])]) broker_address = "monitor.tranquillity.se" client = mqtt.Client("P1") #create new instance client.connect(broker_address) #connect to broker client.publish("heatpump/running", str(compressor()[0]), retain=True) #publish client.publish("heatpump/toptemp", str(vv_top), retain=True) #publish client.publish("heatpump/returntemp", str(vv_retur), retain=True) #publish client.publish("heatpump/hottemp", str(hetgas), retain=True) #publish
def update(self): self.tvoltage.set(DAQC.getADC(0, self.channel)) root.after(500, self.update)
from Tkinter import * import time import piplates.DAQCplate as DAQC import tkFont import string import numpy as np data = np.empty(shape=[0, 3]) fb_initialBias = -275 fb_slope = -9.57 fb_percent = .25 fb_nominalTemp = 3.0752 fb_bias = fb_initialBias + fb_slope * fb_percent * (DAQC.getADC(0, 0) - fb_nominalTemp) class titleBLOCK: def __init__(self, master, r, c): self.master = master self.tit = Frame(self.master, padx=4, pady=4, bd=2, bg='white', relief='sunken') self.tit.grid(row=r, column=c, columnspan=2, sticky=N + S + E + W) ##Fonts self.title = tkFont.Font(family='Helvetica', size=30, weight='bold') self.heading = tkFont.Font(family='Helvetica', size=18, weight='bold')
def get_adc(self, idx): return DAQC.getADC(self.pid, idx)
def db_analog(): """Reads the Analog I/O pins, adjusts for the calibration factor and preps a SQL statement for insertion into the database. """ # calfac = get_calfac(100) calfac = 0 for aio in ANALOGIO: if aio == 0: aio_0 = DAQC.getADC(0, 0) aio_0 = aio_0 - calfac aio_0 = rm_utils.eval_analog(aio_0) if DEBUG: print("Analog In {}: {}vDC".format(aio, aio_0)) elif aio == 1: aio_1 = DAQC.getADC(0, 1) aio_1 = aio_1 - calfac aio_1 = rm_utils.eval_analog(aio_1) if DEBUG: print("Analog In {}: {}vDC".format(aio, aio_1)) elif aio == 2: aio_2 = DAQC.getADC(0, 2) aio_2 = aio_2 - calfac aio_2 = rm_utils.eval_analog(aio_2) if DEBUG: print("Analog In {}: {}vDC".format(aio, aio_2)) elif aio == 3: aio_3 = DAQC.getADC(0, 3) aio_3 = aio_3 - calfac aio_3 = rm_utils.eval_analog(aio_3) if DEBUG: print("Analog In {}: {}vDC".format(aio, aio_3)) elif aio == 4: aio_4 = DAQC.getADC(0, 4) aio_4 = aio_4 - calfac aio_4 = rm_utils.eval_analog(aio_4) if DEBUG: print("Analog In {}: {}vDC".format(aio, aio_4)) elif aio == 5: aio_5 = DAQC.getADC(0, 5) aio_5 = aio_5 - calfac aio_5 = rm_utils.eval_analog(aio_5) if DEBUG: print("Analog In {}: {}vDC".format(aio, aio_5)) elif aio == 6: aio_6 = DAQC.getADC(0, 6) aio_6 = aio_6 - calfac aio_6 = rm_utils.eval_analog(aio_6) if DEBUG: print("Analog In {}: {}vDC".format(aio, aio_6)) elif aio == 7: aio_7 = DAQC.getADC(0, 7) aio_7 = aio_7 - calfac aio_7 = rm_utils.eval_analog(aio_7) if DEBUG: print("Analog In {}: {}vDC".format(aio, aio_7)) elif aio == 8: aio_8 = DAQC.getADC(0, 8) aio_8 = aio_8 - calfac aio_8 = rm_utils.eval_analog(aio_8) if DEBUG: print("Analog In {}: {}vDC adcRef".format(aio, aio_8)) query = """INSERT INTO `analogInput` (`id`, `unix_time`, `analog0`, `analog1`, `analog2`, `analog3`, `analog4`, `analog5`, `analog6`, `analog7`, `analog8`) VALUES (NULL, CURRENT_TIMESTAMP, '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')""" try: cursor.execute( query.format(aio_0, aio_1, aio_2, aio_3, aio_4, aio_5, aio_6, aio_7, aio_8)) mariadb_connection.commit() except mariadb.Error as err: logger.error("DB: db_analog FAILED: {}".format(err)) mariadb_connection.rollback() if DEBUG: print("\033[91m Error analogInput db \033[0m".format(err))
# Define constants B = 3892 # From data sheet of NTCs R0 = 10000 # (Ohms) addHV = 1 # GPIB address, set on device inst = Gpib.Gpib(0, addHV) # Starting string inst.write(":DISP:WIND:TEXT:STAT ON") inst.write(":DISP:WIND2:TEXT:STAT ON") # Main temp checking loop while True: # Get the temperature from the NTC thermistor Vs = DAQC.getADC(0, 8) # Supply voltage (V) # This get the potential from channel 0 on the analog input (V) pot = DAQC.getADC(0, 0) Rn = R0 * (Vs / pot - 1) # Derive from KVL, (Ohms) # Steinhart equation steinhart = Rn / R0 # (R/Ro) steinhart = math.log(steinhart) # ln(R/R0) steinhart /= B steinhart += 1.0 / (25 + 273.15) # + (1/T0) steinhart = 1.0 / steinhart # Invert steinhart -= 273.15 # Convert to C temp = steinhart
myTime = time.localtime(time.time()) myMin = myTime.tm_min mySec = myTime.tm_sec if mySec % modSec == 0 or doorOverride == True: loopLine += door.getDoorCmnd(loopLine, url, doorOverride) doorOverride = False else: loopLine += 11 stdscr.addstr( loopLine, 0, "in else no call to getDoorCmd() - mySec: " + str(mySec) + " ") loopLine += 1 tmp1 = 100 * DAQC.getADC(0, 0) - 50 tmp1 = round(tmp1, 1) tmp2 = 100 * DAQC.getADC(0, 1) - 50 tmp2 = round(tmp2, 1) tmp3 = 100 * DAQC.getADC(0, 2) - 50 tmp3 = round(tmp3, 1) volts = DAQC.getADC(0, 3) fTemp1 = (1 - alpha) * tmp1 + alpha * fTemp1 fTemp1 = round(fTemp1, 1) fTemp2 = (1 - alpha) * tmp2 + alpha * fTemp2 fTemp2 = round(fTemp2, 1) fTemp3 = (1 - alpha) * tmp3 + alpha * fTemp3
def update(self): x = (18.14 * DAQC.getADC(0, self.channel) - 20.32) self.temp.set('%.3f' % x) root.after(500, self.update)
Parameters: empty : float - coltage the sensor gives for empty full : float - voltage the sensor gives for full channel : int - the daqc channel the sensor is on Return: checkValue : int - returns the percentage of the voltage ''' voltageInput = 0 #initialize sensorInput percent = 200 #initialize percUsed #while input is zero - zero means it didn't get a reading while voltageInput == 0: #try to get a reading try: #gets the voltage inut from the daqc board voltageInput = DAQC.getADC(0, channel) #if the voltage is greater than 0 it got a reading. if voltageInput > 0: #calculates the percentage for water if typeSensor == 'W': percent = round(((empty - voltageInput)/(empty-full))*100) #calculates the percentage for the battery elif typeSensor == 'B': percent = round((voltageInput/5)*100) #time.sleep(1) #If not voltage was read or it errored except: print("") #checkValue of the percentage bounds and than return it return checkValueBounds(percent)
def read(self, channel=0): #adc = self.spi.xfer2([1, (8 + channel) << 4, 0]) #data = ((adc[1] & 3) << 8) + adc[2] data = DAQC.getADC(4, 0) #print "measured: ", data return data
theSense = isense[isens] file = datetime.datetime.utcnow().strftime('/home/jbf/data/%Y/%m/' + tt[isens]) i = file.rindex('/') ff = file[0:i] if not os.path.exists(ff): os.makedirs(ff) max = 0. secondMax = 0. i = 0 while i < 1000: try: a = DAQC.getADC(0, theSense) if a > secondMax: if a > max: secondMax = max max = a else: secondMax = a except: out = open(file + '.except', 'w') import traceback traceback.print_exc(file=out) out.close() i = i + 1 rms = 0.707 * secondMax
except AssertionError: DP2.clrDOUTbit(addr, bit) resp['bit'] = bit resp['state'] = 0 elif (cmd == "toggleDOUTbit"): bit = args['bit'] try: DP.toggleDOUTbit(addr, bit) except AssertionError: DP2.toggleDOUTbit(addr, bit) resp['bit'] = bit resp['state'] = 'UNKNOWN' elif (cmd == "getADC"): channel = args['channel'] try: voltage = DP.getADC(addr, channel) except AssertionError: voltage = DP2.getADC(addr, channel) resp['channel'] = channel resp['voltage'] = voltage elif (cmd == "getTEMP"): bit = args['bit'] scale = args['scale'] try: temp = DP.getTEMP(addr, bit, scale) except AssertionError: temp = DP2.getTEMP(addr, bit, scale) resp['temp'] = temp resp['bit'] = bit else: sys.stderr.write("unknown daqc cmd: " + cmd)
HC-SR04 Aansluitschema: 5V: Digital-Output socket 10 Ground: Digital-Input socket 10 Trigger: Digital-Output socket 0 Echo: Digital Input socket 0 Zie voor details: https://pi-plates.com/daqc-users-guide/#Distance_Measurement_with_the_HC-SR04 ''' #### werkt alleen als de hardware is aangesloten # distance = DAQC.getRANGE(0,0,'c') # geeft afstand in cm # print(distance) ####### Lees data van Analoge Input val = DAQC.getADC(0, 1) # DAQC 0, adres Analog-Input 1 print(val) val8 = DAQC.getADCall(0) # lees alle 8 Analog-Inputs print(val8) ######## Lees meerdere data punten data = get_data.readPiPlate(DAQC, [0, 1, 2]) # kanaal [0,1,2], 1000 punten, ADC 0 # maak een (unieke) filenaam aan filename = 'meting_test1_%s.txt' % (int(time.time())) write_data.saveArray(data, filename)
os.mkdir(out_subdir) except Exception: pass output_file_single = 'ntc_single.out' output_file = 'ntc_%d-%d-%d_%d-%d.out' % (year, month, day, hour, min) # Connect to DB, us admin, pw '', db 'temps' client = InfluxDBClient('localhost', 8086, 'admin', '', 'readings') # DHT22 for 22, GPIO17 for 17 humidity_old, dht_temp_old = Adafruit_DHT.read(Adafruit_DHT.DHT22, 17) # Start main loop while True: Vs = DAQC.getADC(0, 8) # Supply voltage (V) pot1 = DAQC.getADC( 0, 0) # This get the potential from channel 0 on the analog input (V) pot2 = DAQC.getADC(0, 1) pot3 = DAQC.getADC(0, 2) pot4 = DAQC.getADC(0, 3) pot5 = DAQC.getADC(0, 4) pots = [pot1, pot2, pot3, pot4, pot5] temps = [] for pot in pots: Rn = R0 * (Vs / pot - 1) # Derive from KVL, (Ohms) # Steinhart equation steinhart = Rn / R0 # (R/Ro)