def V_sampchan(self, chan, gain, data_rate=RATE): ''' This routine returns a single reading of the voltage for the channel. Returns a tuple of the following 5 objects: V -- float, the measured voltage time_stamp -- float, the time of the measurement in seconds since the beginning of the epoch (OS dependent begin time) ref -- float, the reference voltage (Vdd) collected simultaneously. :param int chan: the channel number (0, 1, 2, 3, 4, 5, 6, 7, 8). NOTE: channel 8 returns a measurement of Vdd. :param gain: ignored by board. Defaults to 1. :param int data_rate: ignored by board. :returns: V_avg, stdev, stdev_avg, time_stamp, Vdd_avg :return float V: :return float time_stamp: :return float ref: ''' start = time.time() value = DAQC2plate.getADC(self.addr, chan) ref = DAQC2plate.getADC(self.addr, 8) end = time.time() time_stamp = (start + end) / 2 return value, time_stamp, ref
def V_oversampchan_stats(self, chan, gain, avg_sec, data_rate=RATE): ''' This routine returns the average voltage for the channel averaged at the maximum rate for the board. The standard deviation and the estimated deviation of the mean are also returned. Returns a tuple of the following 5 objects: V_avg -- float, the averaged voltage stdev -- float, the standard deviation of the measured values during the averaging interval stdev_avg -- float, the estimated standard deviation of the returned average time_stamp -- float, the time at halfway through the averaging interval in seconds since the beginning of the epoch (OS dependent begin time) Vdd_avg -- float, the reference voltage (Vdd) collected simultaneously. :param int chan: the channel number (0, 1, 2, 3, 4, 5, 6, 7, 8). NOTE: channel 8 returns a measurement of Vdd. :param gain: ignored by board. Defaults to 1. :param int data_rate: ignored by board. :param float avg_sec: seconds to average for, actual averaging interval will be as close as possible for an integer number of samples :returns: V_avg, stdev, stdev_avg, time_stamp, Vdd_avg :return float V_avg: description :return float stdev: :return float stdev_avg: :return float time_stamp: :return float Vdd_avg: ''' value = [] ref = [] starttime = time.time() endtime = starttime + avg_sec while time.time() < endtime: value.append(DAQC2plate.getADC(self.addr, chan)) ref.append(DAQC2plate.getADC(self.addr, 8)) time_stamp = (starttime + endtime) / 2 ndata = len(value) logging.debug('channel:' + str(chan) + ', starttime:' + str(starttime) + ', ' 'endtime:' + str(endtime) + ', ndata:' + str(ndata) + '.') V_avg = sum(value) / ndata Vdd_avg = sum(ref) / ndata stdev = np.std(value, ddof=1, dtype=np.float64) stdev_avg = stdev / np.sqrt(float(ndata)) return V_avg, stdev, stdev_avg, time_stamp, Vdd_avg
def __init__(self, sim7600, filemanager, args): self.sim7600 = sim7600 self.filemanager = filemanager self.args = args # Is this the first time the script is running after power cycle self.initial_startup = True # There will be a cron.log file which needs to be deleted IF the cron ran successfully self.delete_cron_log = True # Should data be uploaded self.upload_data = False # Should we get a GPS postion self.get_gps_position = True # How many samples should be taken before the sample upload is done self.sample_size = 120 # Check if required local directories exist, and if they don't creat them self.filemanager.check_directory_requirements() # Save the current time self.current_time = time.time() self.previous_time = self.current_time # Save today's date to check for 24-hour intervals self.today = datetime.now(timezone.utc).strftime('%Y%m%d') # Turn SIM7600 module on self.sim7600.power_on() # Get GPS Coordinates if self.get_gps_position: self.args['coordinates'] = self.sim7600.get_position() # Add variables for wind and rain meter self.args['anemometer'] = 0 self.args['rainGauge'] = 0 # Create an instance of the WeatherSensors object # This is a threaded object that measures wind speed and rain self.weather_sensors = WeatherSensors(self.args) # Turn off Pi-Plates status LED on each plate for i in range(0, 2): DAQC2.setLED(i, 'off') # Counter to send initial upload for connectivity test self.test_counter = 0 # Run program loop while True: self.program_loop()
def DAQC2Interrupt(args): global AD global DINInterrupt global DINByte # get DIN digital inputs values DINByte = DAQC2.getDINall(AD) # debounce button before clearing interrupt (! software deboucining slow down OSC send rate, including CANs) # sleep(0.01) DINInterrupt = DAQC2.getINTflags(AD) pass
def OSCDOut(address, args): global AD # convert output number in address String to Integer range (0-7) pinOut = int(address[len(address) - 1]) % 8 # set or clear corresponding DAQC2 plate output if (args == 1): DAQC2.setDOUTbit(AD, pinOut) else: DAQC2.clrDOUTbit(AD, pinOut) pass
def V_oversampchan(self, chan, gain, avg_sec, data_rate=RATE): """ This routine returns the average voltage for the channel averaged at the default rate for the board and returns an average and observed range. Returns a tuple of the following 5 objects: V_avg -- float, the averaged voltage V_min -- float, the minimum voltage read during the interval V_max -- float, the maximum voltage read during the interval time_stamp -- float, the time at halfway through the averaging interval in seconds since the beginning of the epoch (OS dependent begin time) Vdd_avg -- float, the reference voltage (Vdd) collected simultaneously. :param int chan: the channel number (0, 1, 2, 3, 4, 5, 6, 7, 8). NOTE: channel 8 returns a measurement of Vdd. :param gain: ignored by board. Defaults to 1. :param int data_rate: ignored by board. :param float avg_sec: seconds to average for, actual averaging interval will be as close as possible for an integer number of samples :returns: V_avg, V_min, V_max, time_stamp, Vdd_avg :return float V_avg: description :return float V_min: :return float V_max: :return float time_stamp: :return float Vdd_avg: """ value = [] ref = [] starttime = time.time() endtime = starttime + avg_sec while time.time() < endtime: value.append(DAQC2plate.getADC(self.addr, chan)) ref.append(DAQC2plate.getADC(self.addr, 8)) time_stamp = (endtime + endtime) / 2 ndata = len(value) V_avg = sum(value) / ndata Vdd_avg = sum(ref) / ndata V_min = min(value) V_max = max(value) return V_avg, V_min, V_max, time_stamp, Vdd_avg
def exposeAndCollectData(): GPIO.output(methane_valve, GPIO.LOW) GPIO.output(ethane_valve, GPIO.LOW) GPIO.output(compressed_air_valve, GPIO.LOW) GPIO.output(chamber_venting_valve, GPIO.LOW) GPIO.output(mfc1_output_to_chamber_valve, GPIO.LOW) GPIO.output(mfc2_output_to_chamber_valve, GPIO.LOW) GPIO.output(mfc1_venting_valve, GPIO.LOW) GPIO.output(mfc2_venting_valve, GPIO.LOW) start_time = time.time() # capture the time at which the test began. All time values can use start_time as a reference dataVector1 = [] # data values to be returned from sensor 1 dataVector2 = [] # data values to be returned from sensor 2 tempDataVector = [] humidityDataVector = [] timeVector = [] # time values associated with data values sampling_time_index = 1 #sampling_time_index is used to ensure that sampling takes place every interval of sampling_time, without drifting. data_date_and_time = time.asctime( time.localtime(time.time()) ) print("Starting data capture") while (time.time() < (start_time + duration_of_signal)): # While time is less than duration of logged file if (time.time() > (start_time + (sampling_time * sampling_time_index))): # if time since last sample is more than the sampling time, take another sample dataVector1.append( DAQC.getADC(daqc_address, sensor_input_channel_1) ) # Perform analog to digital function, reading voltage from first sensor channel dataVector2.append( DAQC.getADC(daqc_address, sensor_input_channel_2) ) # Perform analog to digital function, reading voltage from second sensor channel timeVector.append( time.time() - start_time ) sampling_time_index += 1 # increment sampling_time_index to set awaited time for next data sample if ((sampling_time_index - 1) % 10 == 0): print(int(time.time() - start_time)) print(DAQC.getADC(daqc_address, linear_actuator_position_channel)) # If time is between 10-50 seconds and the Linear Actuator position sensor signal from DAQCplate indicates a retracted state, extend the sensor ## elif (time.time() >= (start_time + sensing_delay_time) and time.time() <= (sensing_retract_time + start_time) and DAQC.getADC(daqc_address, linear_actuator_position_channel) < extended_state ): elif (time.time() >= (start_time + sensing_delay_time) and time.time() <= (start_time + sensing_delay_time + 10) ): GPIO.output(linear_actuator_extend, GPIO.HIGH) # Actuate linear actuator to extended position GPIO.output(linear_actuator_unlock_retract, GPIO.LOW)# Energizing both control wires causes linear actuator to extend # If time is less than 10 seconds or greater than 50 seconds and linear actuator position sensor signal from DAQCplate indicates an extended state, retract the sensor elif ( ((time.time() < (sensing_delay_time + start_time)) or (time.time() > (sensing_retract_time + start_time)) ) and DAQC.getADC(daqc_address, linear_actuator_position_channel) > retracted_state): ## elif ( ((time.time() < (sensing_retract_time + start_time + 10)) and (time.time() > (sensing_retract_time + start_time)) )): GPIO.output(linear_actuator_unlock_retract, GPIO.HIGH) # Retract linear actuator to initial position. Energizing only the linear_actuator_unlock_retract wire causes the lineaer actuator to retract GPIO.output(linear_actuator_extend, GPIO.LOW) # Otherwise, keep outputs off else: GPIO.output(linear_actuator_unlock_retract, GPIO.LOW) GPIO.output(linear_actuator_extend, GPIO.LOW) ## print("blep") return dataVector1, dataVector2, timeVector
def button(): if DAQC2.getDINbit(0,0) == 0: global button_pressed button_pressed = 1 #print button_pressed print "Button Pressed" DAQC2.setDOUTbit(0,0) sleep(0.02) DAQC2.clrDOUTbit(0,0) sleep(0.2) return()
def __init__(self, addr): super().__init__() self.name = 'DAQC2' self.vendor = 'Pi-Plates' # Note: channel 8 is wired to Vdd so cannot be used for measurements. self.channels = (0, 1, 2, 3, 4, 5, 6, 7, 8) self.addr = addr # Flash light green and then off to indicated found and set up. DAQC2plate.setLED(self.addr, 'green') Vddcheck = float(self.V_oversampchan(8, 1, 5)[0]) self.Vdd = Vddcheck DAQC2plate.setLED(self.addr, 'off')
def button(): if DAQC2.getDINbit(0,0) == 0: global button_pressed button_pressed = 1 print ("Button Pressed") global insert_num insert_num = input("Enter insert #: ") DAQC2.setDOUTbit(0,0) sleep(0.02) DAQC2.clrDOUTbit(0,0) sleep(0.015) return
def button(): global flag if flag == 2: global button_pressed button_pressed = 1 DAQC2.setDOUTbit(0,0) time.sleep(0.02) DAQC2.clrDOUTbit(0,0) time.sleep(0.015) relay() time.sleep(0.01) get_audio() button_pressed = 0
def button(): if DAQC2.getDINbit(0,0) == 0: global button_pressed button_pressed = 1 DAQC2.setDOUTbit(0,0) sleep(0.02) DAQC2.clrDOUTbit(0,0) sleep(0.015) relay() time.sleep(0.01) get_audio() button_pressed = 0 return
def sample_data(self): heading_indices = self.args['preferences']['headingString'].split(",") data_string = "" for idx in heading_indices: if idx[:2] == "ch": # Read the normal input pins if self.args['preferences']['headerIndices'][ idx] == "Anemometer(km/h)": # 1 tick per second = 2.4km/h data_string += "{:.1f},".format(self.args['anemometer']) elif self.args['preferences']['headerIndices'][ idx] == "RainGauge(mm)": # 1 tick = 0.2794mm rain data_string += "{:.4f},".format(self.args['rainGauge']) # Relative humidity is calculated using the formula: # RH = 0.0375 * Vout - 37.7 # Vout needs to be in mV and RH in % elif self.args['preferences']['headerIndices'][ idx] == "RelativeHumidity(%)": Vout = DAQC2.getADC( int(idx[2]), int(idx[3]) ) * 1000 # We have to convert voltage to mV as it is read in V RH = 0.0375 * Vout - 37.7 data_string += "{:.4f},".format(RH) elif self.args['preferences']['headerIndices'][ idx] == "RainGauge(mm)": # 1 tick = 0.2794mm rain data_string += "{:.4f},".format(self.args['rainGauge']) else: data_string += "{:.5f},".format( DAQC2.getADC(int(idx[2]), int(idx[3]))) data_string += "{},".format(datetime.now(timezone.utc).strftime('%Y')) data_string += "{},".format(datetime.now(timezone.utc).strftime('%m')) data_string += "{},".format(datetime.now(timezone.utc).strftime('%d')) data_string += "{},".format(datetime.now(timezone.utc).strftime('%H')) data_string += "{},".format(datetime.now(timezone.utc).strftime('%M')) data_string += "{}\n".format(datetime.now(timezone.utc).strftime('%S')) print(data_string, end='') self.filemanager.save_to_file(self.args['preferences']['savePath'], self.args['filename'], data_string) self.previous_time = self.current_time
def getDAQC2DIN(): global AD global DINInterrupt global DINByte # get DIN digital inputs values DINByte = DAQC2.getDINall(AD) DINInterrupt = 255 pass
def animate(i): # Left shift data data[0:-1] = data[1:] # Record current time data[-1] = v_to_dbm(DAQC2.getADC(0, 0), laser_cw * 1e-3) line.set_ydata(data) return [line]
def probeUpdater(self): if self.record and self.enabled: #piplate holds all pins high #pinReading = (0 if DAQC2.getDINbit(0,self.pin) else 1) pinReading = DAQC2.getDINbit(0,self.pin) self.pdata.append(pinReading) self.pcurve.setData(self.pdata) #Testing threading (requires data to be added to func parameters) '''if self.record and self.enabled:
def readOD(): DAQC2.setDOUTbit(0, 7) time.sleep(1) rowVolts = [] j = 0 k = 0 num = 1 while (k <= 5): tempVolt = [] tEnd = time.time() + .5 while (time.time() < tEnd): tempVolt.append(DAQC2.getADC(j, k)) currAvgVolt = sum(tempVolt) / len(tempVolt) rowVolts.append(currAvgVolt) print("Avg voltage for ", num, ": ", currAvgVolt) k = k + 1 num = num + 1 if (k == 6 and j == 0): j = 1 k = 0 elif (k == 2 and j == 1): k = 10 DAQC2.clrDOUTbit(0, 7)
def read_rain_gauge(self): current_time = time.time() elapsed_time = current_time - self.gauges['rainGauge']['previousTime'] if elapsed_time >= 1: self.args['rainGauge'] = (self.gauges['rainGauge']['numberTicks'] * self.args['preferences']['rainConstant']) self.gauges['rainGauge']['numberTicks'] = 0 self.gauges['rainGauge']['previousTime'] = current_time temp_val = DAQC2.getADC(int(self.gauges['rainGauge']['channel'][2]), int(self.gauges['rainGauge']['channel'][3])) if temp_val > 4: if not self.gauges['rainGauge']['recordedTick']: self.gauges['rainGauge']['numberTicks'] += 1 self.gauges['rainGauge']['recordedTick'] = True else: self.gauges['rainGauge']['recordedTick'] = False
def photoTest(): elapsedTime = 0 tMax = 25 startReadTime = time.time() onVolt = [] offVolt = [] ## tRead = 0 while (tMax >= elapsedTime): DAQC2.setDOUTbit(0, 7) #turn laser on time.sleep(1) tempVolt1 = [] tEnd1 = time.time() + 1 while (time.time() < tEnd1): tempVolt1.append(DAQC2.getADC(0, 0)) DAQC2.clrDOUTbit(0, 7) anaVolt = sum(tempVolt1) / len(tempVolt1) print("number of reads: ", len(tempVolt1)) print("Voltage('ON'): ", anaVolt) onVolt.append(anaVolt) tempVolt2 = [] tEnd2 = time.time() + 1 while (time.time() < tEnd2): tempVolt2.append(DAQC2.getADC(0, 0)) anaVolt = sum(tempVolt2) / len(tempVolt2) print("number of reads: ", len(tempVolt2)) print("Voltage('OFF'): ", anaVolt) offVolt.append(anaVolt) elapsedTime = time.time() - startReadTime print() avgON = sum(onVolt) / len(onVolt) avgOFF = sum(offVolt) / len(offVolt) print("average ON volt: ", avgON) print("avgerage OFF volt: ", avgOFF) print()
resp['value'] = value elif (cmd == "getPWM"): channel = args['channel'] value = PP.getPWM(addr, channel) resp['channel'] = channel resp['value'] = value elif (cmd == "setPWM"): channel = args['channel'] value = args['value'] PP.setPWM(addr, channel, value) resp['channel'] = channel resp['value'] = value elif (cmd == "calDAC"): PP.calDAC(addr) elif (cmd == "getFREQ" and plate_type == "DAQC2"): value = DP2.getFREQ(addr) resp['value'] = value elif (cmd == "setLED" and plate_type == "DAQC"): color = args['color'] if color == 'off': DP.clrLED(addr, 0) DP.clrLED(addr, 1) elif color == 'red': DP.setLED(addr, 0) DP.clrLED(addr, 1) elif color == 'green': DP.clrLED(addr, 0) DP.setLED(addr, 1) elif color == 'yellow': DP.setLED(addr, 0)
import piplates.DAQC2plate as DP2 for i in range(8): resp = DP2.getADDR(i) if (resp < 8): print("found DAQC2 at address: {}".format(resp))
def set_value(self, value): DQ.setDAC(self.piid, self.tid, value)
steps = 3310 parser.read(CONF) if (parser['inserttest_config']['insert_section'] == 'middle'): if (parser['inserttest_config']['size'] == '5'): steps = 5241 if (parser['inserttest_config']['size'] == '5.5'): steps = 4689 if (parser['inserttest_config']['size'] == '7'): flag == 1 steps = 4413 x=1 speed=.001 slowpoint = (steps) *0.75 #1000ms = 14.5/16ths of an inch on input resolution of 200 DAQC2.toggleDOUTbit(7,0) if flag == 1: for x in range(steps): print(x) DAQC2.toggleDOUTbit(7,2) x=x+1 if x==(int(slowpoint)): speed=.005 time.sleep(speed) if flag == steps: flag == 0 DAQC2.toggleDOUTbit(7,1) speed=.001 for x in range(steps):
def run(self): while True: data = DAQC2.getDINbit(0, self.pin) self.newData.emit(data) time.sleep(0.05)
def get_value(self): return DQ.getADC(self.piid, self.tid)
import piplates.DAQC2plate as DAQC2 import time DAQC2.setDAC(0, 0, 2.5) time.sleep(0.25) AIN = DAQC2.getADC(0, 0) time.sleep(0.25) DAQC2.setDAC(0, 0, 0) print("AIN =", AIN, "volts")
import piplates.DAQC2plate as DAQC2 import numpy as np import time voltages = np.arange(2, 4, 0.1) for v in voltages: DAQC2.setDAC(0, 0, v) time.sleep(0.25) DAQC2.setDAC(0, 0, 0) time.sleep(0.25) print("Vout = ", v)
resp['state'] = this_state elif (cmd == "RESET"): RP.RESET(addr) resp['RESET'] = "OK" else: sys.stderr.write("unknown relay cmd: " + cmd) break print(json.dumps(resp)) elif (plate_type == "DAQC"): with simpleflock.SimpleFlock("/tmp/daqc.lock", timeout=3): if (cmd == "getDINbit"): bit = args['bit'] try: state = DP.getDINbit(addr, bit) except AssertionError: state = DP2.getDINbit(addr, bit) resp['bit'] = bit resp['state'] = state elif (cmd == "setDOUTbit"): bit = args['bit'] try: DP.setDOUTbit(addr, bit) except AssertionError: DP2.setDOUTbit(addr, bit) resp['bit'] = bit resp['state'] = 1 elif (cmd == "clrDOUTbit"): bit = args['bit'] try: DP.clrDOUTbit(addr, bit) except AssertionError:
import numpy as np import time import get_data import write_data try: import piplates.DAQC2plate as DAQC except ImportError: print("Failed to import piplates-DAQCplate from python system path") raise ImportError( "Failed to import library from parent folder") ####### zet de LED uit DAQC.setLED(0, 'off') ####### stuur de analoge output aan DAQC.setDAC(0, 1, 2.64) # DAQ 0, adres analog-output 1, voltage 2.64 V ###### stuur 0, 1, 2, 3 volt naar analog-output 1 for i in range(10): volt = i % 4 # i modulo 4 DAQC.setDAC(0, 1, volt) time.sleep(0.1) ####### 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
def set_value(self, value): DQ.setPWM(self.piid, self.tid, value)