pi.write(LED_GPIO, pigpio.LOW) # Voltage readings from ADS1115 when # LDR is in the Dark and in the Light LIGHT_VOLTS = calibration.MAX_VOLTS # (2) DARK_VOLTS = calibration.MIN_VOLTS # Votage reading (and buffer) where we set # global variable triggered = True or False TRIGGER_VOLTS = LIGHT_VOLTS - ((LIGHT_VOLTS - DARK_VOLTS) / 2) # (3) TRIGGER_BUFFER = 0.25 # (4) # Create the I2C bus & ADS object. i2c = busio.I2C(board.SCL, board.SDA) ads = ADS.ADS1115(i2c) analog_channel = AnalogIn(ads, ADS.P0) #ADS.P0 --> A0 # "triggered" is set to True or False as the voltage # read by the ADS1115 passes over it's # TRIGGER_VOLTS (+/- TRIGGER_BUFFER) thresholds. triggered = False # (5) def update_trigger(volts): """ Compare the volts parameter to trigger conditions TRIGGER_VOLTS +/- TRIGGER_BUFFER and update the global 'triggered' variable as appropiate. """ global triggered
import busio #import adafruit_ads1x15.ads1015 as ADS import adafruit_ads1x15.ads1115 as ADS from adafruit_ads1x15.analog_in import AnalogIn # Create the I2C bus i2c = busio.I2C(board.SCL, board.SDA) # Create the ADS object #ads = ADS.ADS1015(i2c) ads = ADS.ADS1115(i2c) # Create a sinlge ended channel on Pin 0 # Max counts for ADS1015 = 2047 # ADS1115 = 32767 chan = AnalogIn(ads, ADS.P0) # The ADS1015 and ADS1115 both have the same gain options. # # GAIN RANGE (V) # ---- --------- # 2/3 +/- 6.144 # 1 +/- 4.096 # 2 +/- 2.048 # 4 +/- 1.024 # 8 +/- 0.512 # 16 +/- 0.256 # gains = (2 / 3, 1, 2, 4, 8, 16) while True:
def run(self): global DAC, mode #---------------------------------Inicializacion----------------------------------------------------- # Create the I2C bus i2c = busio.I2C(board.SCL, board.SDA) # Create the ADC object using the I2C bus ads = ADS.ADS1115(i2c) # Create single-ended input on channel 0 ch0 = AnalogIn(ads, ADS.P0) ch3 = AnalogIn(ads, ADS.P3) ch2 = AnalogIn(ads, ADS.P2) # Create differential input between channel 0 and 1 dif01 = AnalogIn(ads, ADS.P0, ADS.P1) dif23 = AnalogIn(ads, ADS.P2, ADS.P3) ads.gain = 2 / 3 ads.data_rate = 860 # Create Current and Voltage Filters VolFilter = IIR2Filter(2, [5], 'lowpass', 'butter', fs=1000) CurFilter = IIR2Filter(2, [200], 'lowpass', 'butter', fs=1000) #-------------------------------------------------------------------------------------------------- start = time.time() #-----------------------------------------PID SETUP----------------------------------------------- #pid = PID(0.55,0.9,0.005) pid = PID(0.55, 1, 0.01) pid.SetPoint = 20 pid.setSampleTime(0.001) feedback = 0 feedback_list = [] time_list = [] pidmin = 0 pidmax = 5 # ----------------------------------------------------------------------------------------------- voltajedac = 0 DAC.set_voltage(voltajedac) #------------------------------------- MAIN LOOP-------------------------------------------------- while True: try: Current = ch0.voltage Voltage = ch3.voltage #-----------------------------------------IRR FILTER---------------------------------------------- DataVoltage.append(VolFilter.filter(Voltage)) DataCurrent.append(CurFilter.filter(Current)) #------------------------------------------------------------------------------------------------- timenow = (time.time() - start) t.append(timenow) if mode == 'Test': if (timenow > 0 and timenow < 15): pid.SetPoint = 20 elif (timenow > 15 and timenow < 30): pid.SetPoint = 30 elif (timenow > 30): pid.SetPoint = 10 consigna.append(pid.SetPoint) DataVoltage[self.i] = DataVoltage[self.i] * 9.5853 - 0.1082 DataCurrent[self.i] = DataCurrent[self.i] * 1.4089 + 0.1326 DataPower.append(DataVoltage[self.i] * DataCurrent[self.i]) # --------------------------------------- PID CONTROLLER------------------------------------------ pid.update(DataPower[self.i]) output = pid.output if pid.SetPoint > 0: voltajedac = voltajedac + (output - (1 / (self.i + 1))) if voltajedac < pidmin: voltajedac = pidmin elif voltajedac > pidmax: voltajedac = pidmax # ---------------------------------------------DAC------------------------------------------------ voltbits = int((4096 / 5) * voltajedac) DAC.set_voltage(voltbits) # ------------------------------------------------------------------------------------------------ #print("| {0:^5.3f} | {1:^5.3f} | {2:^5.3f} |".format(DataCurrent[i],DataVoltage[i],DataPower[i])) self.i = self.i + 1 except IOError: print('IOError')
def main(): global running i2c = busio.I2C(board.SCL, board.SDA) ads = ADS.ADS1115(i2c) chan = AnalogIn(ads, ADS.P0) sensor = ms5837.MS5837_30BA() sensor.init() try: server_socket = socket.socket() server_socket.bind(('192.168.137.2', 50000)) server_socket.listen(0) print('waiting a client ...') connection, address_ip = server_socket.accept() print('client accepted') stream = connection.makefile('wb') except: print("can't create a connection") t0 = time.perf_counter() t_last = 0 ## keyboard.add_hotkey('q', stop_running) i = 0 running = True while running: ADC0_value = chan.value ADC0_voltage = chan.voltage sensor.read() pressure = sensor.pressure() temperature = sensor.temperature() freshwaterDepth = sensor.depth() t = (time.perf_counter() - t0) * 1000 delta_t = t - t_last t_last = t data = str(temperature) + ',' + str(pressure) + ',' + str(freshwaterDepth) + ',' + str(ADC0_value) + ',' + str(ADC0_voltage) + '\n' i = i + 1 try: stream.write(data.encode('Utf8')) stream.flush() except: ## print("can't send data") pass time.sleep(1) try: stream.close() print('stream is closed') except: print("can't close stream") try: connection.close() print('connection socket is closed') except: print("can't close connection") try: server_socket.close() print('server socket is closed') except: print("can't close server socket") print('End of program')
def read(self): return AnalogIn(self.ads, self.pin).value
#Library for all testing/validation based functions, ADC and photodetector #standard imports import board import busio import csv import pandas import matplotlib.pyplot as plt import adafruit_ads1x15.ads1115 as ADS from adafruit_ads1x15.analog_in import AnalogIn import time i2c = busio.I2C(board.SCL, board.SDA) #allows RPI to communicate with adc ads = ADS.ADS1115(i2c) ads.gain = 2 / 3 #set gain to largest range (+- 6.144) chan = AnalogIn(ads, ADS.P0, ADS.P1) # Set up in differential mode between 0 and 1 link_threshold = .10 #threshold above which is considered "link establishment" delayP = .001 #delay for print-style functions #prints status of beam on photodiode def printAS(glbl): #access global parameters while glbl.esc == False: #if something changes, write to file if glbl.actionString_update != glbl.actionString: glbl.setAS(glbl.actionString_update) note = '(Time: ' + str(round(time.process_time(), 3)) + ' sec) ' + glbl.actionString print(note)
def run(self): global DAC, WPt, WPpw, mode, actpow, qsetpoint #---------------------------------Inicializacion----------------------------------------------------- # Create the I2C bus i2c = busio.I2C(board.SCL, board.SDA) # Create the ADC object using the I2C bus ads = ADS.ADS1115(i2c) # Create single-ended input on channel 0 ch0 = AnalogIn(ads, ADS.P0) ch3 = AnalogIn(ads, ADS.P3) ch2 = AnalogIn(ads, ADS.P2) # Create differential input between channel 0 and 1 dif01 = AnalogIn(ads, ADS.P0, ADS.P1) dif23 = AnalogIn(ads, ADS.P2, ADS.P3) ads.gain = 2 / 3 ads.data_rate = 860 # Create Current and Voltage Filters VolFilter = IIR2Filter(2, [5], 'lowpass', 'butter', fs=1000) CurFilter = IIR2Filter(2, [200], 'lowpass', 'butter', fs=1000) #-------------------------------------------------------------------------------------------------- start = time.time() #-----------------------------------------PID SETUP----------------------------------------------- #pid = PID(0.55,0.9,0.005) #pid = PID(0.55,1,0.01) if (qkp.empty() == False): kp = qkp.get() else: kp = 0.55 if (qki.empty() == False): ki = qki.get() else: ki = 1 if (qkd.empty() == False): kd = qkd.get() else: kd = 0.01 pid = PID(kp, ki, kd) print('PID = {0},{1},{2}'.format(pid.getKp(), pid.getKi(), pid.getKd())) time.sleep(1) #-------------------------------------------------------------------------------------------------- start = time.time() pid.SetPoint = 20 pid.setSampleTime(0.001) feedback = 0 feedback_list = [] time_list = [] pidmin = 0 pidmax = 5 # ----------------------------------------------------------------------------------------------- voltajedac = 0 DAC.set_voltage(voltajedac) i = 0 c1 = 0 c2 = 0 c3 = 0 c4 = 0 iniciando.set('') #------------------------------------- MAIN LOOP-------------------------------------------------- #for i in range(2000): while True: try: Current = ch0.voltage Voltage = ch3.voltage #-----------------------------------------IRR FILTER---------------------------------------------- DataVoltage.append(VolFilter.filter(Voltage)) DataCurrent.append(CurFilter.filter(Current)) #-------------------------------------------Tiempo------------------------------------------------ timenow = (time.time() - start) t.append(timenow) #------------------------------------------------------------------------------------------------- mode = q.get() if mode == 'Test': if (timenow > 0 and timenow < 15): pid.SetPoint = 20 elif (timenow > 15 and timenow < 30): pid.SetPoint = 30 elif (timenow > 30): pid.SetPoint = 10 q.put('Test') elif mode == 'Perfil': for j in range(len(WPt) - 1): if (timenow > WPt[j] and timenow < WPt[j + 1]): pid.SetPoint = WPpw[j] q.put('Perfil') elif mode == 'Manual': if (qsetpoint.empty() == False): pid.SetPoint = float(qsetpoint.get()) q.put('Manual') #------------------------------Prueba aleatoria--------------------------------------------------- # if (timenow > 0 and timenow < 10): # c1=c1+1 # if(c1 == 1): # rand = round(random.uniform(10,35),2) # pid.SetPoint = rand # elif (timenow > 10 and timenow < 20): # c2=c2+1 # if(c2 == 1): # rand = round(random.uniform(10,35),2) # pid.SetPoint = rand # elif (timenow > 20 and timenow < 30): # c3=c3+1 # if(c3 == 1): # rand = round(random.uniform(10,35),2) # pid.SetPoint = rand # elif (timenow > 30 and timenow < 40): # c4=c4+1 # if(c4 == 1): # rand = round(random.uniform(10,35),2) # pid.SetPoint = rand # elif (timenow > 40): # t.pop() # break #--------------------------------Para graficar la consigna----------------------------------------- consigna.append(pid.SetPoint) #------------------------------------------------------------------------------------------------- DataVoltage[i] = DataVoltage[i] * 9.5853 - 0.1082 DataCurrent[i] = DataCurrent[i] * 1.4089 + 0.1326 DataPower.append(DataVoltage[i] * DataCurrent[i]) # --------------------------------------- PID CONTROLLER------------------------------------------ pid.update(DataPower[i]) output = pid.output if pid.SetPoint > 0: voltajedac = voltajedac + (output - (1 / (i + 1))) if voltajedac < pidmin: voltajedac = pidmin elif voltajedac > pidmax: voltajedac = pidmax # ---------------------------------------------DAC------------------------------------------------ voltbits = int((4096 / 5) * voltajedac) DAC.set_voltage(voltbits) # ------------------------------------------------------------------------------------------------ i = i + 1 except IOError: print('IOError') self.writecsv("/media/pi/KELLY/PruebaAleatoria1_1.csv", t, DataPower, consigna)
GPIO.RISING, callback=shutdown_btn_callback, bouncetime=300) # Shutdown button # Create the I2C bus i2c = busio.I2C(board.SCL, board.SDA) # Create the ADC object using the I2C bus ads1 = ADS.ADS1015(i2c, address=0x48) ads2 = ADS.ADS1015(i2c, address=0x49) ads3 = ADS.ADS1015(i2c, address=0x4A) ads4 = ADS.ADS1015(i2c, address=0x4B) # Create input channels # ADC1 (operator side) chan01 = AnalogIn(ads1, ADS.P0) chan02 = AnalogIn(ads1, ADS.P1) chan03 = AnalogIn(ads1, ADS.P2) chan04 = AnalogIn(ads1, ADS.P3) # ADC2 chan05 = AnalogIn(ads2, ADS.P0) chan06 = AnalogIn(ads2, ADS.P1) chan07 = AnalogIn(ads2, ADS.P2) chan08 = AnalogIn(ads2, ADS.P3) # ADC3 chan09 = AnalogIn(ads3, ADS.P0) chan10 = AnalogIn(ads3, ADS.P1) chan11 = AnalogIn(ads3, ADS.P2) chan12 = AnalogIn(ads3, ADS.P3) # ACD4 (machine side) chan13 = AnalogIn(ads4, ADS.P0)
import board import busio i2c = busio.I2C(board.SCL, board.SDA) import sys import time import adafruit_ads1x15.ads1115 as ADS from adafruit_ads1x15.analog_in import AnalogIn ads = ADS.ADS1115(i2c) try: while 1: chan = AnalogIn(ads, ADS.P0) print("Channel 1:", chan.value, " ", chan.voltage, "V\n") chan = AnalogIn(ads, ADS.P1) voltage = chan.voltage print("Channel 2:", chan.value, " ", voltage, "V\n") chan = AnalogIn(ads, ADS.P2) print("Channel 3:", chan.value, " ", chan.voltage, "V\n") chan = AnalogIn(ads, ADS.P3) print("Channel 4:", chan.value, " ", chan.voltage, "V\n") time.sleep(2) except KeyboardInterrupt: print("Stopped.")
# Create the I2C bus i2c = busio.I2C(board.SCL, board.SDA) # Create the ADC object using the I2C bus ads = ADS.ADS1015(i2c) mcp = adafruit_mcp230xx.MCP23017(i2c, address=32) P_LED_pins = 3 LED = mcp.get_pin(P_LED_pins) LED.direction = digitalio.Direction.OUTPUT LED.value = True # Create single-ended input on channel 0 # photoreceptor_channel = 0 pd = AnalogIn(ads, ADS.P1) print("{:>5}\t{:>5}".format('raw', 'v')) try: while True: print("{:>5}\t{:>5.3f}".format(pd.value, pd.voltage)) time.sleep(0.5) except KeyboardInterrupt: LED.value = False # for x in range(0,3): # pdval = adc.read_adc(photoreceptor_channel) # time.sleep(.5)
def pulse_reading(): #adc = Adafruit_ADS1x15.ADS1015() i2c = busio.I2C(board.SCL, board.SDA) # initialization GAIN = 2 / 3 adc = ADS.ADS1015(i2c, GAIN) chan = AnalogIn(adc, ADS.P0) curState = 0 thresh = 525 # mid point in the waveform P = 512 T = 512 stateChanged = 0 sampleCounter = 0 lastBeatTime = 0 firstBeat = True secondBeat = False Pulse = False IBI = 600 rate = [0] * 10 amp = 100 BMP = 0 lat = 0 lon = 0 dtime = '' speed = 'nan' lastTime = int(time.time() * 1000) # Main loop. use Ctrl-c to stop the code while True: # read from the ADC #TODO: Select the correct ADC channel. I have selected A0 here Signal = chan.value curTime = int(time.time() * 1000) sampleCounter += curTime - lastTime # # keep track of the time in mS with this variable lastTime = curTime N = sampleCounter - lastBeatTime # # monitor the time since the last beat to avoid noise #print N, Signal, curTime, sampleCounter, lastBeatTime ## find the peak and trough of the pulse wave if Signal < thresh and N > ( IBI / 5.0 ) * 3.0: # # avoid dichrotic noise by waiting 3/5 of last IBI if Signal < T: # T is the trough T = Signal # keep track of lowest point in pulse wave if Signal > thresh and Signal > P: # thresh condition helps avoid noise P = Signal # P is the peak # keep track of highest point in pulse wave # NOW IT'S TIME TO LOOK FOR THE HEART BEAT # signal surges up in value every time there is a pulse if N > 250: # avoid high frequency noise if (Signal > thresh) and (Pulse == False) and (N > (IBI / 5.0) * 3.0): Pulse = True # set the Pulse flag when we think there is a pulse IBI = sampleCounter - lastBeatTime # measure time between beats in mS lastBeatTime = sampleCounter # keep track of time for next pulse if secondBeat: # if this is the second beat, if secondBeat == TRUE secondBeat = False # clear secondBeat flag for i in range( 0, 10 ): # seed the running total to get a realisitic BPM at startup rate[i] = IBI if firstBeat: # if it's the first time we found a beat, if firstBeat == TRUE firstBeat = False # clear firstBeat flag secondBeat = True # set the second beat flag continue # IBI value is unreliable so discard it # keep a running total of the last 10 IBI values runningTotal = 0 # clear the runningTotal variable for i in range(0, 9): # shift data in the rate array rate[i] = rate[i + 1] # and drop the oldest IBI value runningTotal += rate[i] # add up the 9 oldest IBI values rate[9] = IBI # add the latest IBI to the rate array runningTotal += rate[9] # add the latest IBI to runningTotal runningTotal /= 10 # average the last 10 IBI values BPM = 60000 / runningTotal # how many beats can fit into a minute? that's BPM! database_pulse(BPM) print('BPM: {}'.format(BPM)) if Signal < thresh and Pulse == True: # when the values are going down, the beat is over Pulse = False # reset the Pulse flag so we can do it again amp = P - T # get amplitude of the pulse wave thresh = amp / 2 + T # set thresh at 50% of the amplitude P = thresh # reset these for next time T = thresh if N > 2500: # if 2.5 seconds go by without a beat thresh = 512 # set thresh default P = 512 # set P default T = 512 # set T default lastBeatTime = sampleCounter # bring the lastBeatTime up to date firstBeat = True # set these to avoid noise secondBeat = False # when we get the heartbeat back print("no beats found") time.sleep(0.05)
#!/usr/bin/env python3 """ the code is designed for collecting and sending data of pizoelectric vibration sensor using RPi and thingspeak cloud, ADS1115 adc is used. Data is update in my channel """ import http.client as http import urllib import board import busio import adafruit_ads1x15.ads1115 as ADS from adafruit_ads1x15.analog_in import AnalogIn i2c = busio.I2C(board.SCL, board.SDA) ads = ADS.ADS1115(i2c) chan = AnalogIn(ads, ADS.P0) # sensor input connected in pin0 vibration = chan.value # reading the value of senosr key = "ABCD" # API Key here def pizo_sensor(): while True: params = urllib.parse.urlencode({'field1': vibration, 'key': key}) headers = { "Content-typZZe": "application/x-www-form-urlencoded", "Accept": "text/plain" } conn = http.HTTPConnection("api.thingspeak.com:80") try: conn.request("POST", "/update", params, headers) response = conn.getresponse() print(vibration)
def flowtrig(self): global waterTick waterTick += 1 GPIO.add_event_callback(24, flowtrig) while True: time.sleep(interval) #Pull Temperature from DS18B20 temperature = ds18b20.get_temperature() #Measure Analog Input 0 chan = AnalogIn(ads, ADS.P0) #ADS.P1 , P2, P3 for channels 1, 2, 3 val = chan.value #Pull the raw ADC data from Channel 0 waterFlow = waterTick * 2.25 waterTick = 0 #Test Solenoids by turning each on for a half second GPIO.output(s1, GPIO.HIGH) #turn solenoid 1 on time.sleep(0.5) #Wait for a half second GPIO.output(s1, GPIO.LOW) #turn solenoid 1 off time.sleep(0.5) GPIO.output(s2, GPIO.HIGH) #turn solenoid 2 on time.sleep(0.5) #Wait for a half second GPIO.output(s2, GPIO.LOW) #turn solenoid 2 off time.sleep(0.5)
import busio import adafruit_ads1x15.ads1115 as ADS1 from adafruit_ads1x15.ads1x15 import Mode from adafruit_ads1x15.analog_in import AnalogIn # Data collection setup RATE = 250 RATEB = 250 SAMPLES = 1000 # Create the I2C bus with a fast frequency i2c = busio.I2C(board.SCL, board.SDA, frequency=1000000) # Create the ADC object using the I2C bus ads1115 = ADS1.ADS1115(i2c, address=0x4a) chanB3 = AnalogIn(ads1115, ADS1.P3) # ADC Configuration ads1115.mode = Mode.SINGLE ads1115.data_rate = RATEB ads1115.gain = 16 O2_Baseline = chanB3.voltage def GetO2Voltage(): vv =chanB3.voltage O2 = 20.9*vv/O2_Baseline return O2, vv
def init_pH(self): self.pH_sensor = AnalogIn(self.ads, ADS.P1)
#!/usr/bin/python3 import board import busio i2c = busio.I2C(board.SCL, board.SDA) import adafruit_ads1x15.ads1015 as ADS from adafruit_ads1x15.analog_in import AnalogIn ads = ADS.ADS1015(i2c) #Single Ended Mode for port in [ADS.P1, ADS.P2]: chan = AnalogIn(ads, port) adj = float(chan.voltage) / 0.09 print("voltage" + str(port) + ": %.2f" % adj) # print("port: " + str(port)) # print("-------------") # print("value: " + str(chan.value)) # print("voltage: " + str(chan.voltage)) # # print(chan.value, chan.voltage) # print("adjusted value: " + str(adj) ) # print("\n") ################################### # Differential Mode # chan = AnalogIn(ads, ADS.P0, ADS.P1) # print(chan.value, chan.voltage)
def getData(): #import necessary modules and initialize I2C bus import board import busio i2c = busio.I2C(board.SCL, board.SDA) #import board module (ADS1115) import adafruit_ads1x15.ads1115 as ADS #import ADS1x15 library's version of AnalogIn from adafruit_ads1x15.analog_in import AnalogIn #import Adafruit DHT22 stuff (humidty) import Adafruit_DHT as dht DHT = 14 #set DHT's GPIO pin number #import the w1 water temp sensor module from w1thermsensor import W1ThermSensor wt_sensor = W1ThermSensor() #import libraries for distance sensor import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) #GPIO Mode (BOARD / BCM) #create ADS object ads = ADS.ADS1115(i2c) ads.gain = 2 / 3 #single ended mode read for pin 0 and 1 chan = AnalogIn(ads, ADS.P0) chan1 = AnalogIn(ads, ADS.P1) #define readings from ADC pH = -5.82 * chan.voltage + 22.1 #calibrated equation #pH = chan.voltage TDS = chan1.voltage #read air temp and air humidity hum, atemp = dht.read_retry(dht.DHT22, DHT) #read w1 water temp sensor wtemp = wt_sensor.get_temperature() #setup distance sensing stuff GPIO_TRIGGER = 6 #set GPIO Pins GPIO_ECHO = 18 GPIO.setup(GPIO_TRIGGER, GPIO.OUT) #set GPIO direction (IN / OUT) GPIO.setup(GPIO_ECHO, GPIO.IN) # set Trigger to HIGH GPIO.output(GPIO_TRIGGER, True) # set Trigger after 0.01ms to LOW time.sleep(0.00001) GPIO.output(GPIO_TRIGGER, False) StartTime = time.time() StopTime = time.time() # save StartTime while GPIO.input(GPIO_ECHO) == 0: StartTime = time.time() # save time of arrival while GPIO.input(GPIO_ECHO) == 1: StopTime = time.time() # time difference between start and arrival TimeElapsed = StopTime - StartTime # multiply with the sonic speed (34300 cm/s) # and divide by 2, because there and back distance = (TimeElapsed * 34300) / 2 return pH, TDS, hum, atemp, wtemp, distance #from time import sleep #while True: # print(getData()) # sleep(0.2)
from time import sleep import board import busio import adafruit_ads1x15.ads1115 as ADS from adafruit_ads1x15.analog_in import AnalogIn import sys import random import cloud4rpi import ds18b20 import rpi i2c = busio.I2C(board.SCL, board.SDA) ads = ADS.ADS1115(i2c) efficacy = 21.856 area = 3.2 * (10**-6) chan1 = AnalogIn(ads, ADS.P0) chan2 = AnalogIn(ads, ADS.P1) def sensor1(): voltage = chan1.voltage logLux = voltage * 5.0 / 3.0 lux = pow(10, logLux) return lux def senso2(): voltage = chan2.voltage logLux = voltage * 5.0 / 3.0 lux = pow(10, logLux) return lux
import board import busio import time import csv #stand 2 foot up i2c = busio.I2C(board.SCL, board.SDA) import adafruit_ads1x15.ads1015 as ADS from adafruit_ads1x15.analog_in import AnalogIn ads = ADS.ADS1015(i2c, address=0x48) heel = AnalogIn(ads, ADS.P0) toe = AnalogIn(ads, ADS.P1) i = 0 f = open("Stand_Data2[up].csv", "w", newline="") c = csv.writer(f) start_time = time.time() seconds = 25 heelPhase = 0 toePhase = 0 c.writerow(["Heel Value", "Heel Phase", "Toe Value", "Toe Phase", "Time"]) while True: current_time = time.time() elapsed_time = current_time - start_time print("heel:", heel.value, heel.voltage, heelPhase, " | toe:", toe.value, toe.voltage, toePhase)
#windSpeedS #WindDirectionS #Main loop # Finn starttid startTime = time.time() # Setup ADC unit i2c = busio.I2C(board.SCL, board.SDA) # Create the ADC object using the I2C bus try: #-- ADC 1 -- ads1 = ADS.ADS1015(i2c) # Windspeed: channel1 = AnalogIn(ads1, ADS.P3) # WindDirection channel2 = AnalogIn(ads1, ADS.P0) except Exception as e: ads1 = None try: ads2 = ADS.ADS1015(i2c, 1, None, ADS.Mode.SINGLE, 0x4a) #-- ADC 2 -- # Humidity channel3 = AnalogIn(ads2, ADS.P0) # Temperature channel4 = AnalogIn(ads2, ADS.P2) except Exception as e: ads2 = None
def read_temp(): lines = read_temp_raw() while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw() equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos + 2:] temp_c = float(temp_string) / 1000.0 return temp_c ads.gain = 1 chan = AnalogIn(ads, ADS.P2) #, ADS.P1) print(format(chan.voltage, '05.2f').replace(".", ",")) #chan.voltage) # Type of sensor, can be `adafruit_dht.DHT11` or `adafruit_dht.DHT22`. # For the AM2302, use the `adafruit_dht.DHT22` class. DHT_TYPE = adafruit_dht.DHT22 # Example of sensor connected to Raspberry Pi Pin 17 DHT_PIN = board.D17 # Initialize the dht device, with data pin connected to: dhtDevice = DHT_TYPE(DHT_PIN) ## Wachttijd om internet verbinding te laten opstarten. print('20 seconden geduld om wifi-verbinding op te starten.') time.sleep(20)
def __init__(self): """docstring for .""" self.i2c = busio.I2C(board.SCL, board.SDA) self.ads = ADS.ADS1115(self.i2c) self.chan = AnalogIn(self.ads, ADS.P0)
def read(self, parameter): if parameter == "temperatureCPU": value = (self.cpu.temperature,) unit = "c" return(value, unit) elif parameter == "temperature": value = (self.sht.temperature,) unit = "c" return(value, unit) elif parameter == "Humidity": value = (self.sht.relative_humidity,) unit = "%" return(value, unit) elif parameter == "temperature2": value = (self.lps.temperature,) unit = "c" return(value, unit) elif parameter == "pressure": value = (self.lps.pressure,) unit = "hPa" return(value, unit) elif parameter == "lux": value = (self.tcs.lux,) unit = "lux" return(value, unit) elif parameter == "color-temperature": value = (self.tcs.color_temperature,) unit = "K" return(value, unit) elif parameter == "color-rgb": value = (self.tcs.color_rgb_bytes) unit = "rgb" return(value, unit) elif parameter == "acceleration": value = (self.icm.acceleration) unit = "m/s²" return(value, unit) elif parameter == "gyro": value = (self.icm.gyro) unit = "Rads/s" return(value, unit) elif parameter == "magnetic": value = (self.icm.magnetic) unit = "uT" return(value, unit) elif parameter == "external1": chan = AnalogIn(self.ads, ADS.P0) value = (chan.voltage,) unit = "mV" return(value, unit) elif parameter == "external2": chan = AnalogIn(self.ads, ADS.P1) value = (chan.voltage,) unit = "mV" return(value, unit) elif parameter == "external3": chan = AnalogIn(self.ads, ADS.P2) value = (chan.voltage,) unit = "mV" return(value, unit) elif parameter == "external4": chan = AnalogIn(self.ads, ADS.P3) value = (chan.voltage,) unit = "mV" return(value, unit)
def __init__(self, sysnum): self.sysnum = sysnum self.sysstr = 'EVE' + str(self.sysnum) self.config = configparser.ConfigParser() self.config.read('eve-conf.ini') # Define Experiment Variables self.time_between_pumps = self.config[self.sysstr].getfloat('time_between_pumps') self.OD_thr = self.config[self.sysstr].getfloat('OD_thr') self.OD_min = self.config[self.sysstr].getfloat('OD_min') self.time_between_ODs = self.config[self.sysstr].getfloat('time_between_ODs') # how often to gather OD data, in seconds self.time_between_graphs = self.config[self.sysstr].getfloat('time_between_graphs') # how often to graph, in minutes # OD_thr is the threshold above which to activate drug pump [vish bench tests: empty: 3.5V, Clear Vial: 0.265V, Very Cloudy Vial: 2.15V] #time_between_writes = 1 # how often to write out OD data, in minutes #loops_between_writes = (time_between_writes*60)/time_between_ODs # time bewteen writes in loops self.time_between_saves = self.config[self.sysstr].getfloat('time_between_saves') # Set Up I2C to Read OD Data # Create the I2C bus self.P_drug_times = self.config[self.sysstr].getfloat('P_drug_times') self.P_nut_times = self.config[self.sysstr].getfloat('P_nut_times') self.P_waste_times = self.config[self.sysstr].getfloat('P_waste_times') self.running_data = [] # the list which will hold our 2-tuples of time and OD self.pump_data = [] self.OD_tmplist = [] self.pump_tmplist = [] # self.currOD = np.zeros(num_cham) self.currOD = 0 # averaged OD value # self.avOD = np.zeros(num_cham) self.avOD = 0 self.OD_av_length = self.config[self.sysstr].getint('OD_av_length') # OD averaging buffer self.avOD_buffer = np.zeros(self.OD_av_length)#need to change for multiplexing self.elapsed_loop_time = 0 self.loops = 0 self.last_dilutionOD = 0 self.nut = 0 self.drug = 1 self.waste = 2 self.drug_mass = 0 self.total_time = self.config[self.sysstr].getfloat('Exp_time_hours')*3600 #in seconds self.loops_between_ODs = 1 self.loops_between_pumps = (self.time_between_pumps*60)/self.time_between_ODs # time between pumps in loops # num_cham = 1 # number of morbidostat vials being used self.i2c = busio.I2C(board.SCL, board.SDA) # # Create the ADC object using the I2C bus self.ads = ADS.ADS1015(self.i2c) # # Create single-ended input on channel 0 # # photoreceptor_channel = 0 self.photod = AnalogIn(self.ads, getattr(ADS,'P'+ str(self.config[self.sysstr].getint('Analogin')))) # Setup the GPIO Pins to Control the Pumps self.pipins = self.config[self.sysstr].getboolean('Pi_pins') self.P_drug_pins = self.config[self.sysstr].getint('P_drug_pins') self.P_nut_pins = self.config[self.sysstr].getint('P_nut_pins') self.P_waste_pins = self.config[self.sysstr].getint('P_waste_pins') self.P_LED_pins = self.config[self.sysstr].getint('P_LED_pins') # P_fan_pins = self.config[self.sysstr].getint('P_fan_pins') self.pin_list = [self.P_drug_pins, self.P_nut_pins, self.P_waste_pins, self.P_LED_pins] if self.pipins: GPIO.setmode(GPIO.BCM) for pin in self.pin_list: GPIO.setup(pin, GPIO.OUT) else: self.pins = [None]*(max(self.pin_list)+1) self.mcp = adafruit_mcp230xx.MCP23017(self.i2c, address=self.config[self.sysstr].getint('m_address')) for pin in self.pin_list: self.pins[pin] = self.mcp.get_pin(pin) self.pins[pin].direction = digitalio.Direction.OUTPUT self.pins[pin].value = False self.writer = 0 self.init_time = datetime.now() self.slack_client = SlackClient(self.config['MAIN']['slack_key']) # self.chanid = self.config['MAIN']['slack_chanid'] self.slack_usericon = self.config[self.sysstr]['slack_icon'] self.chan = self.config['MAIN']['slack_channel'] self.slack_client.api_call( "chat.postMessage", channel = self.chan, username=self.sysstr, icon_url = self.slack_usericon, text = self.init_time.strftime('Initialized at %H:%M:%S') )
def get_wind_dir(self): # Calculate wind direction based on ADC reading self.chan = AnalogIn(self.ads, ADS.P0) self.val = self.chan.value self.windDir = "Not Connected" self.windDeg = 999 if 20000 <= self.val <= 20500: self.windDir = "N" self.windDeg = 0 if 10000 <= self.val <= 10500: self.windDir = "NNE" self.windDeg = 22.5 if 11500 <= self.val <= 12000: self.windDir = "NE" self.windDeg = 45 if 2000 <= self.val <= 2250: self.windDir = "ENE" self.windDeg = 67.5 if 2300 <= self.val <= 2500: self.windDir = "E" self.windDeg = 90 if 1500 <= self.val <= 1950: self.windDir = "ESE" self.windDeg = 112.5 if 4500 <= self.val <= 4900: self.windDir = "SE" self.windDeg = 135 if 3000 <= self.val <= 3500: self.windDir = "SSE" self.windDeg = 157.5 if 7000 <= self.val <= 7500: self.windDir = "S" self.windDeg = 180 if 6000 <= self.val <= 6500: self.windDir = "SSW" self.windDeg = 202.5 if 16000 <= self.val <= 16500: self.windDir = "SW" self.windDeg = 225 if 15000 <= self.val <= 15500: self.windDir = "WSW" self.windDeg = 247.5 if 24000 <= self.val <= 24500: self.windDir = "W" self.windDeg = 270 if 21000 <= self.val <= 21500: self.windDir = "WNW" self.windDeg = 292.5 if 22500 <= self.val <= 23000: self.windDir = "NW" self.windDeg = 315 if 17500 <= self.val <= 18500: self.windDir = "NNW" self.windDeg = 337.5 return self.windDir, self.windDeg
#Setup import board import busio from time import sleep i2c = busio.I2C(board.SCL, board.SDA) import adafruit_ads1x15.ads1115 as ADS from adafruit_ads1x15.analog_in import AnalogIn ads = ADS.ADS1115(i2c) chan0 = AnalogIn(ads, ADS.P0) chan1 = AnalogIn(ads, ADS.P1) chan2 = AnalogIn(ads, ADS.P2) chan3 = AnalogIn(ads, ADS.P3) while True: a = chan0.voltage b = chan1.voltage c = chan2.voltage d = chan3.voltage print("{0:2.2f} - {1:2.2f} - {2:2.2f} - {3:2.2f}".format(a, b, c, d))
running = True samples = 1000 def cleanup(s=None): if s: s.close() try: i2c = I2C(SCL, SDA) sensor = LSM9DS1_I2C(i2c) sensor1 = MPL3115A2(i2c) ads = ADS.ADS1115(i2c) battery = AnalogIn(ads, ADS.P0) sensor.gyro_scale = GYROSCALE_2000DPS sensor.accel_range = ACCELRANGE_2G # this is here to 'zero' out the altitude sensor1.sealevel_pressure = int(sensor1.pressure) #sensor1.sealevel_pressure = 101325 # average except: print("Failed to setup Sensor(s)...") cleanup() sys.exit(1) try: s = socket(AF_INET, SOCK_STREAM)
def init_leak(self): self.leak_sensor = AnalogIn(self.ads, ADS.P0)
import board import busio i2c = busio.I2C(board.SCL, board.SDA) import adafruit_ads1x15.ads1015 as ADS from adafruit_ads1x15.analog_in import AnalogIn from time import sleep ads = ADS.ADS1015(i2c) in0 = AnalogIn(ads, ADS.P0) in1 = AnalogIn(ads, ADS.P1) in2 = AnalogIn(ads, ADS.P2) in3 = AnalogIn(ads, ADS.P3) inArr = [in0, in1, in2, in3] while True: for x, i in enumerate(inArr): print("Pin", x, ": ", i.value, i.voltage) sleep(1)
def read(self): ads = ADS.ADS1115(self.i2c) chan1 = AnalogIn(ads, ADS.P1) print(chan1.value, chan1.voltage)