lcd_en = digitalio.DigitalInOut(board.D19) lcd_d7 = digitalio.DigitalInOut(board.D27) lcd_d6 = digitalio.DigitalInOut(board.D22) lcd_d5 = digitalio.DigitalInOut(board.D24) lcd_d4 = digitalio.DigitalInOut(board.D25) lcd_columns = 20 lcd_rows = 4 lcd = characterlcd.Character_LCD_Mono(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows) # initialize multiplexer board tca_multi = TCA.TCA9548A(i2c) # initialize saffron_grow_sensors # tca_multi[1] = ADS1115, bme680, ccs811 ads1115 = ADS.ADS1115(tca_multi[1]) bme680_1 = BME.Adafruit_BME680_I2C(tca_multi[1]) ccs811 = CCS.CCS811(tca_multi[1]) # chan0 = AnalogIn(ads1115, ADS.P0) chan1 = AnalogIn(ads1115, ADS.P1) chan2 = AnalogIn(ads1115, ADS.P2) while True: try: lcd.clear() temp_c_room = round(bme680_1.temperature, 1) temp_f_room = round(((9 / 5) * temp_c_room + 32), 1) rh_room = round(bme680_1.humidity, 1) # coir_vwc = round(get_soil_moisture(chan0.voltage), 1) coir50_vwc = round(get_soil_moisture(chan1.voltage), 1) rockwool_vwc = round(get_soil_moisture(chan2.voltage), 1)
from adafruit_ads1x15.analog_in import AnalogIn import time import os import glob from mqtt_client.publisher import Publisher import json from threading import Thread try: # Setup Current Sensors i2c = busio.I2C(board.SCL, board.SDA) ads = ADS.ADS1115(i2c, address=0x48) ads.gain = 1 chan = AnalogIn(ads, ADS.P0) chan2 = AnalogIn(ads,ADS.P1) chan3 = AnalogIn(ads, ADS.P2) # Setup Temperature Sensors ads_temp = ADS.ADS1115(i2c, address=0x49) ads_temp.gain = 1 jet1_in = AnalogIn(ads_temp, ADS.P0) jet2_in = AnalogIn(ads_temp, ADS.P1) compartment_in = AnalogIn(ads_temp, ADS.P2) except Exception: pass
import time # Import the ADS1x15 module. import adafruit_ads1x15.ads1115 as ads import adafruit_ads1x15.analog_in as analog_in import board import busio import requests adc = ads.ADS1115(busio.I2C(board.SCL, board.SDA)) # initialization GAIN = 2 / 3 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 lastTime = int(time.time() * 1000)
# OTHERWISE, leave gains at 1 to allow the ADC to digitize voltages from 0 to 4.096VDC (K-Thermocouple reading up to 1056F) # This should be enough temperature range for the top of a wood stove or the surface of a double wall chimney pipe. # Using other gain values (e.g. 2,4,8,16) will likely overdrive the ADC when digitizing a K-Thermocouple amp. adcgain = 2 / 3 num_channels = 1 reportInterval = 30 # seconds max_trend_samples = 10 # trend analysis will be over this many report intervals bias_voltage = 1.3 # Adafruit says 1.25 mv_per_c = 0.0025 # Adafruit says 0.005 #################################### # Initialize objects #################################### i2c = busio.I2C(board.SCL, board.SDA) ads = ADS.ADS1115(i2c, gain=adcgain) channels = [AnalogIn(ads, x) for x in range(num_channels)] #################################### #################################### # MAIN LOOP #################################### #################################### print('Starting Main Loop, press Ctrl-C to quit...') def voltage_to_c(voltage): celsius = (voltage - bias_voltage) / mv_per_c return celsius
import board import busio import adafruit_ads1x15.ads1115 as ADC from adafruit_ads1x15.analog_in import AnalogIn i2c = busio.I2C(board.SCL, board.SDA) ads = ADC.ADS1115(i2c) ads.gain = 2 / 3 # should be 0, 1, 2, 3 (ADC.P0) def read(pin): result = AnalogIn(ads, pin) return [result.value, result.voltage] if __name__ == "__main__": print(read(ADC.P1))
def temps(): import board import time import busio import adafruit_ads1x15.ads1115 as ADS from adafruit_ads1x15.analog_in import AnalogIn from sympy import Symbol from sympy.solvers import solve i2c=busio.I2C(board.SCL,board.SDA) ads1=ADS.ADS1115(i2c) ads2=ADS.ADS1115(i2c,address=0x49) ads3=ADS.ADS1115(i2c,address=0x4A) ads4=ADS.ADS1115(i2c,address=0x4B) chan01=AnalogIn(ads1,ADS.P0) chan11=AnalogIn(ads1,ADS.P1) chan02=AnalogIn(ads2,ADS.P0) chan12=AnalogIn(ads2,ADS.P1) chan03=AnalogIn(ads3,ADS.P0) chan13=AnalogIn(ads3,ADS.P1) chan04=AnalogIn(ads4,ADS.P0) chan14=AnalogIn(ads4,ADS.P1) #constants of pt100 a=3.9083*10**(-3) b=-5.775*10**(-7) c=-4.183*10**(-12) #vi=voltage pt100 / vcc=voltage source(3.3V) / R= rtc resistance vi1=chan01.voltage vcc1=chan11.voltage vi2=chan02.voltage vcc2=chan12.voltage vi3=chan03.voltage vcc3=chan13.voltage vi4=chan04.voltage vcc4=chan14.voltage R1=3300/(vcc1/vi1-1) R2=3300/(vcc2/vi2-1) R3=3300/(vcc3/vi3-1) R4=3300/(vcc4/vi4-1) #Finding temperature through resistance (rtc curve) x=Symbol("x") if R1>100: T1=solve(R1-100*(1+a*x+b*x**2),x) else: T1=solve(R1-100*(1+a*x+b*x**2+c*(x-100)*x**3),x) if R2>100: T2=solve(R2-100*(1+a*x+b*x**2),x) else: T2=solve(R2-100*(1+a*x+b*x**2+c*(x-100)*x**3),x) if R3>100: T3=solve(R3-100*(1+a*x+b*x**2),x) else: T3=solve(R3-100*(1+a*x+b*x**2+c*(x-100)*x**3),x) if R4>100: T4=solve(R4-100*(1+a*x+b*x**2),x) else: T4=solve(R4-100*(1+a*x+b*x**2+c*(x-100)*x**3),x) #keeping only the value within the reasonable range of temperatures temp=[] for z in range(0,len(T1)): if T1[z]>=-200 and T1[z]<=300: T1[z]=float("{:.2f}".format(T1[z])) temp.append(T1[z]) for z in range(0,len(T2)): if T2[z]>=-200 and T2[z]<=300: T2[z]=float("{:.2f}".format(T2[z])) temp.append(T2[z]) for z in range(0,len(T3)): if T3[z]>=-200 and T3[z]<=300: T3[z]=float("{:.2f}".format(T3[z])) temp.append(T3[z]) for z in range(0,len(T4)): if T4[z]>=-200 and T4[z]<=300: T4[z]=float("{:.2f}".format(T4[z])) temp.append(T4[z]) return temp
def StartEmulator(self): #---------------------------------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 a DAC instance. DAC = Adafruit_MCP4725.MCP4725(address=0x60, busnum=1) # Create Current and Voltage Filters VolFilter = IIR2Filter(2, [5], 'lowpass', 'butter', fs=1000) CurFilter = IIR2Filter(2, [200], 'lowpass', 'butter', fs=1000) #PIDFilter = IIR2Filter(1,[20],'lowpass','butter',fs=1000) #-------------------------------------------------------------------------------------------------- start = time.time() #-----------------------------------------PID SETUP----------------------------------------------- #pid = PID(0.55,0.9,0.005) pid = PID(0.55, 1, 0.005) 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 #------------------------------------- MAIN LOOP-------------------------------------------------- while True: 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 (timenow > 0 and timenow < 15): pid.SetPoint = 20 elif (timenow > 15 and timenow < 30): pid.SetPoint = 30 elif (timenow > 30): pid.SetPoint = 10 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) # ------------------------------------------------------------------------------------------------ #print("| {0:^5.3f} | {1:^5.3f} | {2:^5.3f} |".format(DataCurrent[i],DataVoltage[i],DataPower[i])) i = i + 1
def collect_Data(): # collecting air data for x in range(0, 6): init_gpio() print('*******************************') if x == 0: # measuring temperature mux_control(x) ads = ADS.ADS1115(i2c) chan = AnalogIn(ads, ADS.P0) temp_value = chan.voltage * 1000 temp_result = ( float(temp_value) - 500) * 0.1 # 500 is offset & 0.1 is Output Voltage Scaling if temp_result <= -30: temp_result = -30 elif temp_result > 50: temp_result = 50 print('Temperature : ' + str(round(temp_result, 2)) + 'degree celcius') # choice temperature each sensor data[1] = round(temp_result, 2) elif 1 <= x <= 4: # Measuring Working Electrode mux_control(x * 2 - 1) ads = ADS.ADS1115(i2c) chan = AnalogIn(ads, ADS.P0) we_value = chan.voltage * 1000 print(air_list[x - 1] + ' WE : ' + str(round(we_value, 2)) + 'mV') # Measuring Auxiliary Electrode mux_control(x * 2) ads = ADS.ADS1115(i2c) chan = AnalogIn(ads, ADS.P0) ae_value = chan.voltage * 1000 print(air_list[x - 1] + ' AE : ' + str(round(ae_value, 2)) + 'mV') if x == 1: temp = temp_choice(temp_result, x) # calculating ppb & ppm ppb_value = ((we_value - we_zero[x - 1]) - temp * (ae_value - ae_zero[x - 1])) / \ sens[x - 1] no2 = round(ppb_value, 3) data[2] = no2 print(air_list[x - 1] + ' : ' + str(no2) + 'ppb') elif x == 2: temp = temp_choice(temp_result, x) # calculating ppb & ppm ppb_value = ((we_value - we_zero[x - 1]) - (0 - (-1))) - temp * (ae_value - ae_zero[x - 1]) / \ sens[x - 1] o3 = round(ppb_value / 1000, 3) data[3] = o3 print(air_list[x - 1] + ' : ' + str(o3) + 'ppm') elif x == 3: temp = temp_choice(temp_result, x) # calculating ppb & ppm ppb_value = ((we_value - we_zero[x - 1]) - temp * (ae_value - ae_zero[x - 1])) / \ sens[x - 1] co = round(ppb_value / 1000, 3) data[4] = co print(air_list[x - 1] + ' : ' + str(co) + 'ppm') elif x == 4: temp = temp_choice(temp_result, x) # calculating ppb & ppm ppb_value = ((we_value - we_zero[x - 1])) - temp / \ sens[x - 1] so2 = round(ppb_value, 3) data[5] = so2 print(air_list[x - 1] + ' : ' + str(so2) + 'ppb') print('n Table = > ' + str(temp)) elif x == 5: mux_control(x * 2 - 1) ads = ADS.ADS1115(i2c) chan = AnalogIn(ads, ADS.P0) pm25_value = chan.voltage v = pm25_value hppcf = 240 * (v**6) - 2491.3 * (v**5) + 9448.7 * ( v**4) - 14840 * (v**3) + 10684 * (v**2) + 2211.8 * v + 7.9623 ugm3 = .518 + .00274 * hppcf pm25 = round(ugm3, 3) data[6] = pm25 pm10 = round(ugm3, 3) data[7] = pm10 print(air_list[x - 1] + ' : ' + str(pm25) + 'ug/m^3') print(air_list[x] + ' : ' + str(pm10) + 'ug/m^3') print('*******************************')
def work_ADS1115(name, data): def getRanges(settings): ranges = [] b = OrderedDict(sorted(settings.items())) for i in b: if 'range' in i: c = b[i].split('->') if len(c) == 2: try: d = c[0].split('|') try: e = c[1].split('|') f = [float(e[0].lstrip()), float(e[1].lstrip())] except: f = c[1].lstrip() ranges.append( [[int(d[0].lstrip()), int(d[1].lstrip())], f]) except: pass return ranges def getPaths(ranges, value, voltage, key, offset, raw): Erg = '' if ranges: result = '' for i, v in enumerate(ranges): r1 = ranges[i][0] r2 = ranges[i][1] if value >= r1[0] and value <= r1[1]: if type(r2) == list: a = r1[1] - r1[0] b = value - r1[0] pc = b * 100 / a c = r2[1] - r2[0] d = c * pc / 100 result = r2[0] + d else: result = r2 if result: try: result2 = float(result) Erg += '{"path": "' + key + '","value":' + str( offset + result2) + '},' except: Erg += '{"path": "' + key + '","value":"' + str( result) + '"},' else: Erg += '{"path": "' + key + '","value": null},' if raw and voltage and value: value = '{"value":' + str(value) + ',"voltage":' + str( voltage) + '}' Erg += '{"path": "' + key + '.raw","value":' + value + '},' return Erg A0key = data['data'][0]['SKkey'] A1key = data['data'][1]['SKkey'] A2key = data['data'][2]['SKkey'] A3key = data['data'][3]['SKkey'] if A0key or A1key or A2key or A3key: import adafruit_ads1x15.ads1115 as ADS from adafruit_ads1x15.analog_in import AnalogIn from collections import OrderedDict address = data['address'] gain = 1 if 'sensorSettings' in data: if 'gain' in data['sensorSettings']: try: gain = eval(data['sensorSettings']['gain']) except: pass i2c = busio.I2C(board.SCL, board.SDA) ads = ADS.ADS1115(i2c, address=int(address, 16), gain=gain) if A0key: A0chan = AnalogIn(ads, ADS.P0) A0raw = data['data'][0]['raw'] A0rate = data['data'][0]['rate'] A0offset = data['data'][0]['offset'] A0Ranges = [] if 'magnitudeSettings' in data['data'][0]: A0settings = data['data'][0]['magnitudeSettings'] A0Ranges = getRanges(A0settings) if A1key: A1chan = AnalogIn(ads, ADS.P1) A1raw = data['data'][1]['raw'] A1rate = data['data'][1]['rate'] A1offset = data['data'][1]['offset'] A1Ranges = [] if 'magnitudeSettings' in data['data'][1]: A1settings = data['data'][1]['magnitudeSettings'] A1Ranges = getRanges(A1settings) if A2key: A2chan = AnalogIn(ads, ADS.P2) A2raw = data['data'][2]['raw'] A2rate = data['data'][2]['rate'] A2offset = data['data'][2]['offset'] A2Ranges = [] if 'magnitudeSettings' in data['data'][2]: A2settings = data['data'][2]['magnitudeSettings'] A2Ranges = getRanges(A2settings) if A3key: A3chan = AnalogIn(ads, ADS.P3) A3raw = data['data'][3]['raw'] A3rate = data['data'][3]['rate'] A3offset = data['data'][3]['offset'] A3Ranges = [] if 'magnitudeSettings' in data['data'][3]: A3settings = data['data'][3]['magnitudeSettings'] A3Ranges = getRanges(A3settings) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) port = data['port'] tick1 = time.time() tick2 = tick1 tick3 = tick1 tick4 = tick1 while True: time.sleep(0.1) try: Erg = '' if A0key: tick0 = time.time() if tick0 - tick1 > A0rate: A0value = A0chan.value A0voltage = A0chan.voltage Erg += getPaths(A0Ranges, A0value, A0voltage, A0key, A0offset, A0raw) tick1 = time.time() if A1key: tick0 = time.time() if tick0 - tick2 > A1rate: A1value = A1chan.value A1voltage = A1chan.voltage Erg += getPaths(A1Ranges, A1value, A1voltage, A1key, A1offset, A1raw) tick2 = time.time() if A2key: tick0 = time.time() if tick0 - tick3 > A2rate: A2value = A2chan.value A2voltage = A2chan.voltage Erg += getPaths(A2Ranges, A2value, A2voltage, A2key, A2offset, A2raw) tick3 = time.time() if A3key: tick0 = time.time() if tick0 - tick4 > A3rate: A3value = A3chan.value A3voltage = A3chan.voltage Erg += getPaths(A3Ranges, A3value, A3voltage, A3key, A3offset, A3raw) tick4 = time.time() if Erg: SignalK = '{"updates":[{"$source":"OpenPlotter.I2C.' + name + '","values":[' SignalK += Erg[0:-1] + ']}]}\n' sock.sendto(SignalK.encode('utf-8'), ('127.0.0.1', port)) except Exception as e: print("ADS1115 reading failed: " + str(e))
i2c = busio.I2C(board.SCL, board.SDA) # Choose a gain of 1 for reading voltages from 0 to 4.09V. # Or pick a different gain to change the range of voltages that are read: # - 2/3 = +/-6.144V # - 1 = +/-4.096V # - 2 = +/-2.048V # - 4 = +/-1.024V # - 8 = +/-0.512V # - 16 = +/-0.256V # See table 3 in the ADS1015/ADS1115 datasheet for more info on gain. GAIN = 1 # Create an ADS1115 ADC (16-bit) instance. #adc = Adafruit_ADS1x15.ADS1115() ads = ADS.ADS1115(i2c, GAIN) # Create single-ended input on channel 0 #chan = AnalogIn(ads, ADS.P0) # Create differential input between channel 0 and 1 #chan = AnalogIn(ads, ADS.P0, ADS.P1) # Create differential input between channel 2 and 3 chan = AnalogIn(ads, ADS.P2, ADS.P3) #print('Press Ctrl-C to quit...') t_start = time.time() #time.sleep(3.1) #print(t_start) # => 3.0999999046325684
import time import board import busio import math import adafruit_ads1x15.ads1115 as ADC from adafruit_ads1x15.analog_in import AnalogIn # Create the I2C bus i2c = busio.I2C(board.SCL, board.SDA) # Create the ADC object using the I2C bus adc = ADC.ADS1115(i2c) #dirty_water_voltage = 2.85 # ntu_dirty_water selain 0 - 5 def check_turbidity_values(): #channel 0 in ADS1115 module channel = AnalogIn(adc, ADC.P0) ntu = (-26.7641 * channel.voltage) + 135.0524 if (ntu > 5 and ntu < 0): return True else: return False
data = ts.recv(1024) rcv = data.decode('ascii') result = ack_process(rcv, sha) if result == "70": print("Successfully logged on") else: print("Login failed") sys.exit(1) #import antigravity i2c = busio.I2C(board.SCL, board.SDA) # Create an ADS1115 ADC (16-bit) instance. ads = ads1115.ADS1115(i2c) VOLTAGE = 120 GAIN = 2 startTime = datetime.datetime.now() file = open("./Data/{0:%Y-%m-%d %H:%M:%S}".format(datetime.datetime.now()),"w") print('Reading ADS1x15 values, press Ctrl-C to quit...') # Print nice channel column headers. header='dt [s]\tP0 [W]\tP1 [W]\tP2 [W]' header2='_' * 35 print(header) print(header2) file.write(header + "\n") file.write(header2 + "\n")
import time # import random import mysql.connector # #pt ads1115 (placa care citeste senzori de temp) import board import busio i2c = busio.I2C(board.SCL, board.SDA) import adafruit_ads1x15.ads1115 as ADS from adafruit_ads1x15.analog_in import AnalogIn ads1 = ADS.ADS1115(i2c) #prima placa ads1115 ads2 = ADS.ADS1115(i2c, address=0x49) #pentru a doua placa #ST1 # ads1_chan_0 = AnalogIn(ads1, ADS.P0) #canalul 0 de pe placa 1 # #ST2 # ads1_chan_1 = AnalogIn(ads1, ADS.P1) #canalul 1 de pe placa 1 # ads1_chan_2 = AnalogIn(ads1, ADS.P2) # # ads1_chan_3 = AnalogIn(ads1, ADS.P3) # # ads2_chan_0 = AnalogIn(ads1, ADS.P0) #canalul 0 de pe placa 2 # #ST6 # ads2_chan_1 = AnalogIn(ads1, ADS.P1) #canalul 1 de pe placa 2 # am grupat ce era mai sus intr-un vector channels = [ AnalogIn(ads1, ADS.P0),
def __init__(self): self.i2c = busio.I2C(board.SCL, board.SDA) self.ads = ADS.ADS1115(self.i2c) self.ads.gain = 2/3
def __init__(self, gps: UBX): # self.steer = SteeringController(i2c=i2c) # self.speed = SpeedController(i2c=i2c, gps=gps) self.sampling_time = 0.001 self.time_stamp = 0. # Steering Digital Pins self.left_pin = DIO.DigitalInOut(board.D21) # D1 self.right_pin = DIO.DigitalInOut(board.D20) # D2 # Set as outputs self.left_pin.direction = DIO.Direction.OUTPUT self.right_pin.direction = DIO.Direction.OUTPUT # Drive Controller (Millipak) Digital Pins self.forward = DIO.DigitalInOut(board.D16) # D3 self.reverse = DIO.DigitalInOut(board.D26) # D4 self.fs1 = DIO.DigitalInOut(board.D19) # D5 self.seat = DIO.DigitalInOut(board.D13) # D6 self.power = DIO.DigitalInOut(board.D6) # D7 # Set as outputs self.forward.direction = DIO.Direction.OUTPUT self.reverse.direction = DIO.Direction.OUTPUT self.fs1.direction = DIO.Direction.OUTPUT self.seat.direction = DIO.Direction.OUTPUT self.power.direction = DIO.Direction.OUTPUT # GPS self._gps = gps # self._gps.start_reading() # I2C and ADC Setup self._i2c_interface = busio.I2C(board.SCL, board.SDA) # Setup Steering Angle ADC adc = ADC.ADS1115(self._i2c_interface, address=72) self.steer_adc = AnalogIn(adc, ADC.P0) # Setup Steering Angle DAC self.steer_dac = DAC.MCP4725(self._i2c_interface, address=97) # Setup Drive Speed DAC self.speed_dac = DAC.MCP4725(self._i2c_interface, address=96) # Speed self._measured_speed = 0. self._speed_set_point = 0. self._stop = False # Speed PID Controller self._prev_error_speed = 0. self._cumulative_error_speed = 0. # Original non-time related # self.p_gain_speed = 0.01 # self.d_gain_speed = 1. # self.i_gain_speed = 0. # Sample time related self.p_gain_speed = 0.01 self.d_gain_speed = 1. / 1000 self.i_gain_speed = 0. * 1000 self._speed_output_voltage = 0 self._max_speed_voltage = 1.6 self.driving_forward = True # Steering # 0 Degree Steer = 2.582V self._steer_output_voltage = 0. self._max_steer_voltage = 4.5 self._min_steer_voltage = 0.05 self._steering_angle_set_point = 0. self._current_steering_angle = 0. self._steer_adc_measurements = deque(maxlen=1) self._steering_changed = False self._steer_adc_average = 0. self._steer_adc_set_point = 0. self.left_max = 20 self.right_max = -20 # Steering PID Controller # Original non-time related # self.p_gain_steer = 15. # self.d_gain_steer = 0. # self.i_gain_steer = .2 # Sampling time related self.p_gain_steer = 15. self.d_gain_steer = 0. / 1000 self.i_gain_steer = .2 * 1000 self._prev_error_steer = 0. self._cumulative_error_steer = 0. # Set DAC Output self.steer_dac.value = 0 self.speed_dac.value = 0 # Threading self._stop_threads = False self._control_thread = None
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(1,[5],'lowpass','butter',fs=1000) CurFilter = IIR2Filter(1,[200],'lowpass','butter',fs=1000) #-------------------------------------------------------------------------------------------------- #-----------------------------------------PID SETUP----------------------------------------------- #pid = PID(0.55,0.9,0.005) #pid = PID(0.55,1,0.01) if (qkp.empty()==False): kp = qkp.get() qkp.put(kp) else: kp = 0.55 if (qki.empty()==False): ki = qki.get() qki.put(ki) else: ki = 1 if (qkd.empty()==False): kd = qkd.get() qkd.put(kd) else: kd = 0.01 pid = PID(kp,ki,kd) npid.set("PID = {0}, {1}, {2}".format(str(pid.getKp()),str(pid.getKi()),str(pid.getKd()))) print('PID = {0},{1},{2}'.format(pid.getKp(),pid.getKi(),pid.getKd())) time.sleep(1) #-------------------------------------------------------------------------------------------------- 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('') starttime = time.time() self.powermeter.start() #------------------------------------- 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()-starttime) 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]) qpower.put(DataPower[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')
import plotly.plotly as py import plotly.graph_objs as go from plotly.graph_objs import Scatter, Layout, Figure, Data, Stream, YAxis import time import readadc from datetime import datetime import board import busio import time import os i2c = busio.I2C(board.SCL, board.SDA) import adafruit_ads1x15.ads1115 as ADS from adafruit_ads1x15.analog_in import AnalogIn ads = ADS.ADS1115(i2c, gain=2 / 3) chan1 = AnalogIn(ads, ADS.P1) chan0 = AnalogIn(ads, ADS.P0) #temphead = (chan1.voltage - 1.25) / 0.005 username = '******' api_key = '' stream_token_temp = '' stream_token_pressure = '' py.sign_in(username, api_key) trace1 = Scatter(x=[], y=[], name='Brew Temp', stream=dict(token=stream_token_temp, maxpoints=10000)) trace2 = go.Scatter(x=[],
from adafruit_ads1x15.analog_in import AnalogIn import busio import board # Set GAIN to +/- 4.096V GAIN = 1 # Create the I2C bus i2c = busio.I2C(board.SCL, board.SDA) # Define address for ADCs ADC1 = 0x48 ADC2 = 0x49 # Create ADC objects adc1 = ADS.ADS1115(i2c, address=ADC1) adc2 = ADS.ADS1115(i2c, address=ADC2) # Define index for sensors PRESSURE1 = ADS.P0 PRESSURE2 = ADS.P1 PRESSURE3 = ADS.P2 PRESSURE4 = ADS.P0 PRESSURE5 = ADS.P1 OXYGEN1 = ADS.P2 class Sensors: """This class contains methods for directly interacting with the sensors. Attributes:
def main(): if (len(sys.argv) != 4): sys.stderr.write('Usage: "{0}" $aIOUsername $aIOKey \ $aIOFeedKeyPersonsUltrasonic \n'.format(sys.argv[0])) os._exit(1) # 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 chan = AnalogIn(ads, ADS.P0) # Dict with some GPIO pin numbers pinList = {"countState": 7, "count": 8} # Setup GPIO setmode GPIO.setmode(GPIO.BCM) # Set GPIO pin signal OUT and initial value "shutdown" GPIO.setup(list(pinList.values()), GPIO.OUT, initial=GPIO.LOW) aIOUsername = sys.argv[1] aIOKey = sys.argv[2] # Beware, your Key is Secret! # Feed key's where data is management aIOFeedKeyPersonsMagnetic = sys.argv[3] # Connect to Adafruit IO Server aioClient = Client(username=aIOUsername, key=aIOKey) # Link to feeds personsMagneticFeed = aioClient.feeds(aIOFeedKeyPersonsMagnetic) # Control of count system peopleCount = DataCount(aioClient, personsMagneticFeed) # When magnetic element is far the min value is reached sensorValueMin = 6900 # When magnetic element is near the max value is reached sensorValueMax = 10300 """When magnectic element are middle of distances between min and max """ sensorValueMedium = (int( (sensorValueMax - sensorValueMin) / 2) + sensorValueMin) baseTime = time.time() countTemp = 0 # Count value while state count and doesn't show countTempLast = 0 # For toggle LED alert count +1 # Flags for execute only one time (turn off, turn on) counted = False countState = False countTempLastState = True countRate = 0.6 # Setup Threading, to show data every 20 seconds hilo0 = threading.Thread(target=show_data, args=[ peopleCount, ]) hilo0.start() while True: sensorValue = chan.value # Distance of magnetic sensor # Case if are plaque in high position if (sensorValue >= sensorValueMedium): baseTime = time.time() if (countTemp != 0): lock.acquire() peopleCount.countTimes += countTemp lock.release() countTemp = 0 # Turn off LED to alert plaque in high position if (countState): countState = False GPIO.output(pinList.get("countState"), GPIO.LOW) else: # Case if are plaque in low position """Triggered every showDataTime-1 seconds for update counTimes """ # print("is",sensorValue, sensorValueMedium) if (int(time.time()) % (showDataTime - 1) == 0): # Do only one time per showDataTime-1 if (not counted): lock.acquire() peopleCount.countTimes += countTemp lock.release() # Update base time with rate residue baseTime = time.time() - (time.time() % countRate) # Update countTempLast for LED count alert continueTime = time.time() - baseTime countTempLast = int(continueTime / countRate) + 1 counted = True else: counted = False continueTime = time.time() - baseTime # Count rate + 1 more (case 0 to 0.6) countTemp = int(continueTime / countRate) + 1 # Turn on LED to alert plaque in low position if (not countState): countState = True GPIO.output(pinList.get("countState"), GPIO.HIGH) # Turn on LED to alert every counted +1 for 1 cycle time if (countTempLast != countTemp): countTempLast = countTemp countTempLastState = False GPIO.output(pinList.get("count"), GPIO.HIGH) elif (not countTempLastState): countTempLastState = True GPIO.output(pinList.get("count"), GPIO.LOW) time.sleep(0.1) # Cycle time
from matplotlib import pyplot as plt import RPi.GPIO as GPIO # 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 ads1015 = ADS0.ADS1015(i2c) ads1115 = ADS1.ADS1115(i2c, address=0x4a) # Create single-ended input on channel 0 #chan0 = AnalogIn(ads1015, ADS0.P0) #chan1 = AnalogIn(ads1015, ADS0.P1) #chan2 = AnalogIn(ads1015, ADS0.P2) chan3 = AnalogIn(ads1015, ADS0.P3) #chanB0 = AnalogIn(ads1115, ADS1.P0) #chanB1 = AnalogIn(ads1115, ADS1.P1) #chanB2 = AnalogIn(ads1115, ADS1.P2) chanB3 = AnalogIn(ads1115, ADS1.P3) # ADC Configuration ads1115.mode = Mode.SINGLE ads1115.data_rate = RATEB
class X360controler: i2c = busio.I2C(board.SCL, board.SDA) # Create the I2C bus ads = ADS.ADS1115(i2c) # Create the ADC object using the I2C bus ads_pin = [ADS.P0, ADS.P1, ADS.P2, ADS.P3] silnik_1 = DuzySilnik(22, 12, 7, ads, ads_pin[0]) # Przegub w podstawie silnik_2 = DuzySilnik(23, 13, 25, ads, ads_pin[1]) # Przegub w połowie ramienia silnik_chwytak = MalySilnik(16, 19, 20, 21) numberOfEngines = 0 numberOfValues = 2 stara_pozycja_1 = 0 stara_pozycja_2 = 0 AM1 = 0 AM2 = 0 run = True left_stick = [0, 0] right_stick = [0, 0] left_trigger = 0.0 right_trigger = 0.0 deadzone = 0.05 engines = numberOfValues * [0] # x_vel, y_vel, z_vel, yaw_vel #engines = 10 * [0.0] swiatla = 0 obslugaDanych = None buttons = {'A': False, 'B': False, 'X': False, 'Y': False, 'LB': False, 'RB': False, 'LS': False, 'RS': False, 'back': False, 'start': False, 'mode': False, 'DU': False, 'DD': False, 'DL': False, 'DR': False} switches = {'A': False, 'B': False, 'X': False, 'Y': False, 'LB': False, 'RB': False, 'LS': False, 'RS': False, 'back': False, 'start': False, 'mode': False, 'DU': False, 'DD': False, 'DL': False, 'DR': False} """ buttonsReactions: 'Releasedbutton_a','Releasedbutton_b','Releasedbutton_x','Releasedbutton_y','Releasedbutton_trigger_l','Releasedbutton_trigger_r': self._rb, ,'Releasedbutton_thumb_l','Releasedbutton_thumb_r','Releasedbutton_select','Releasedbutton_start': self._start,'Releasedbutton_mode', 'Releasedbutton_back' 'Pressedbutton_a','Pressedbutton_b','Pressedbutton_x','Pressedbutton_y','Pressedbutton_trigger_l','Pressedbutton_trigger_r': self._rb, ,'Pressedbutton_thumb_l','Pressedbutton_thumb_r','Pressedbutton_select','Pressedbutton_start': self._start,'Pressedbutton_mode', 'Pressedbutton_back' """ def __init__(self): self.buttonReactions = defaultdict(lambda: None, {'a':'b'}) #self.buttonReactions = {'Pressedbutton_a':self.RPI.pid_turn_on, # 'Pressedbutton_b':self.RPI.pid.turn_off, # 'Pressedbutton_y':self.RPI.pid_hold_depth} #buttonReactions= defaultdict(lambda: None,{'a':'b'}) def sign(self, val): if val != 0: return val / abs(val) else: return 0 def adjust_deadzone(self, value, dzone): if abs(value) > dzone: return (value - self.sign(value) * dzone) / (1 - dzone) else: return 0 # PAD ACTIONS def a(self): # button_a self.buttons['A'] = True self.switches['A'] = not self.switches['A'] print('A') #if self.buttonReactions['PressedButton_a'] != None: # self.buttonReactions['PressedButton_a']() def _a(self): # button_a self.buttons['A'] = False print('_A') self._run_in_thread(self.silnik_chwytak.OtworzChwytak) #if self.buttonReactions['Releasedbutton_a'] != None: # self.buttonReactions['Releasedbutton_a']() def b(self): # button_b self.buttons['B'] = True self.switches['B'] = not self.switches['B'] print('B') #if self.buttonReactions['PressedButton_b'] != None: # self.buttonReactions['PressedButton_b']() def _b(self): # button_b self.buttons['B'] = False print('_B') self._run_in_thread(self.silnik_chwytak.ZamknijChwytak) #if self.buttonReactions['Releasedbutton_b'] != None: # self.buttonReactions['Releasedbutton_b']() def x(self): # button_x self.buttons['X'] = True self.switches['X'] = not self.switches['X'] print('X') #if self.buttonReactions['PressedButton_x'] != None: # self.buttonReactions['PressedButton_x']() def _x(self): # button_x self.buttons['X'] = False print('_X') #if self.buttonReactions['Releasedbutton_x'] != None: # self.buttonReactions['Releasedbutton_x']() def y(self): # button_y self.buttons['Y'] = True self.switches['Y'] = not self.switches['Y'] print('Y') #if self.buttonReactions['PressedButton_y'] != None: # self.buttonReactions['PressedButton_y']() def _y(self): # button_y self.buttons['Y'] = False print('_Y') #if self.buttonReactions['Releasedbutton_y'] != None: # self.buttonReactions['Releasedbutton_y']() def lb(self): # button_trigger_l self.buttons['LB'] = True self.switches['LB'] = not self.switches['LB'] print('LB') def _lb(self): # button_trigger_l self.buttons['LB'] = False print('_LB') def rb(self): # button_trigger_r self.buttons['RB'] = True self.switches['RB'] = not self.switches['RB'] print('RB') def _rb(self): # button_trigger_r self.buttons['RB'] = False print('_RB') def ls(self): # button_thumb_l self.buttons['LS'] = True self.switches['LS'] = not self.switches['LS'] print('LS') self.cur_mode = not self.cur_mode print('Mov mode: {}'.format(self.cur_mode)) def _ls(self): # button_thumb_l self.buttons['LS'] = False print('_LS') def rs(self): # button_thumb_r self.buttons['RS'] = True self.switches['RS'] = not self.switches['RS'] print('RS') self.cur_precision = not self.cur_precision print('Precision mode: {}'.format(self.cur_precision)) def _rs(self): # button_thumb_r self.buttons['RS'] = False print('_RS') def back(self): # button_select self.buttons['back'] = True self.switches['back'] = not self.switches['back'] print('back') if self.buttonReactions['Pressedbutton_back'] != None: self.buttonReactions['Pressedbutton_back']() def _back(self): # button_select self.buttons['back'] = False print('_back') if self.buttonReactions['Releasedbutton_back'] != None: self.buttonReactions['Releasedbutton_back']() def start(self): # button_start self.buttons['start'] = True self.switches['start'] = not self.switches['start'] print('start') if self.buttonReactions['PressedButton_start'] != None: self.buttonReactions['PressedButton_start']() def _start(self): # button_start self.buttons['start'] = False print('_start') if self.buttonReactions['ReleasedButton_y'] != None: self.buttonReactions['ReleasedButton_y']() def mode(self): # button_mode self.buttons['mode'] = True self.switches['mode'] = not self.switches['mode'] print('mode') self.run = False if self.buttonReactions['Pressedbutton_mode'] != None: self.buttonReactions['Pressedbutton_mode']() def _mode(self): # button_mode self.buttons['mode'] = False print('_mode') if self.buttonReactions['Releasedbutton_mode'] != None: self.buttonReactions['Releasedbutton_mode']() def left(self, axis): # axis_l self.left_stick[0] = self.adjust_deadzone(axis.x, 3 * self.deadzone) self.left_stick[1] = -self.adjust_deadzone(axis.y, 3 * self.deadzone) def right(self, axis): # axis_r self.right_stick[0] = self.adjust_deadzone(axis.x, 3 * self.deadzone) self.right_stick[1] = -self.adjust_deadzone(axis.y, 3 * self.deadzone) def hat(self, axis): # hat if axis.x == 1: self.buttons['DR'] = True self.buttons['DL'] = False self.switches['DR'] = not self.switches['DR'] elif axis.x == -1: self.buttons['DL'] = True self.buttons['DR'] = False self.switches['DL'] = not self.switches['DL'] else: self.buttons['DR'] = False self.buttons['DL'] = False if axis.y == 1: self.buttons['DU'] = True self.buttons['DD'] = False self.switches['DU'] = not self.switches['DU'] elif axis.y == -1: self.buttons['DD'] = True self.buttons['DU'] = False self.switches['DD'] = not self.switches['DD'] else: self.buttons['DD'] = False self.buttons['DU'] = False def lt(self, axis): # trigger_l self.left_trigger = axis.value def rt(self, axis): # trigger_r self.right_trigger = axis.value def on_pressed(self, button): options = {'button_a': self.a, 'button_b': self.b, 'button_x': self.x, 'button_y': self.y, 'button_trigger_l': self.lb, 'button_trigger_r': self.rb, 'button_thumb_l': self.ls, 'button_thumb_r': self.rs, 'button_select': self.back, 'button_start': self.start, 'button_mode': self.mode} options[button.name]() def on_released(self, button): options = {'button_a': self._a, 'button_b': self._b, 'button_x': self._x, 'button_y': self._y, 'button_trigger_l': self._lb, 'button_trigger_r': self._rb, 'button_thumb_l': self._ls, 'button_thumb_r': self._rs, 'button_select': self._back, 'button_start': self._start, 'button_mode': self._mode} options[button.name]() def on_moved(self, axis): options = {'axis_l': self.left, 'axis_r': self.right, 'hat': self.hat, 'trigger_l': self.lt, 'trigger_r': self.rt} options[axis.name](axis) # STEERING FUNCTIONS #def steering(self): def cart2coord(self, x_coord, y_coord, z_coord, o_coord, a_coord, t_coord): # to add inverse kinematics! pair1 = 1 * x_coord pair2 = 1 * y_coord pair3 = 1 * z_coord pair4 = 1 * o_coord pair5 = 1 * a_coord pair6 = 1 * t_coord return [pair1, pair2, pair3, pair4, pair5, pair6] def updateAngle(self): #funkcja aktualizjaca kąt VM1=self.silnik_1.pozycja.voltage -0.68 #volltage motor 1 - napiecie na siniku 1 VM2=self.silnik_2.pozycja.voltage #napiecie na siniku 2 self.AM1=12 + round((VM1-0.391)*360/(1.906 - 0.391), 0) #angle motor 1 - kąt na silniku 1 self.AM2=163 + round((VM2-0.391)*360/(1.906 - 0.391), 0) #angle motor 2 - kąt na silniku 2 def Start(self): with Xbox360Controller(0, axis_threshold=self.deadzone) as controller: # BUTTONS controller.button_a.when_pressed = self.on_pressed # A controller.button_a.when_released = self.on_released controller.button_b.when_pressed = self.on_pressed # B controller.button_b.when_released = self.on_released controller.button_x.when_pressed = self.on_pressed # X controller.button_x.when_released = self.on_released controller.button_y.when_pressed = self.on_pressed # Y controller.button_y.when_released = self.on_released controller.button_trigger_l.when_pressed = self.on_pressed # LB controller.button_trigger_l.when_released = self.on_released controller.button_trigger_r.when_pressed = self.on_pressed # RB controller.button_trigger_r.when_released = self.on_released controller.button_thumb_l.when_pressed = self.on_pressed # LS controller.button_thumb_l.when_released = self.on_released controller.button_thumb_r.when_pressed = self.on_pressed # RS controller.button_thumb_r.when_released = self.on_released controller.button_select.when_pressed = self.on_pressed # back controller.button_select.when_released = self.on_released controller.button_start.when_pressed = self.on_pressed # start controller.button_start.when_released = self.on_released controller.button_mode.when_pressed = self.on_pressed # mode controller.button_mode.when_released = self.on_released # AXES controller.axis_l.when_moved = self.on_moved # left controller.axis_r.when_moved = self.on_moved # right controller.hat.when_moved = self.on_moved # hat controller.trigger_l.when_moved = self.on_moved # LT controller.trigger_r.when_moved = self.on_moved # RT # The Loop counter =0 minA = 250 #kat do warunkow, z zapasem w góre zamiast 180 maxA = 350 #kat do warunkow, z zapasem w dół zamiast 360 minB = 100 #kat do warunkow, z zapasem w dół zamiast 450 maxB = 260 #kat do warunkow, z zapasem w dół zamiast 450 dodatnia = 0.5 #rotation speed ujemna = -0.5 #predkosc obrotow przeciwnie z wskazówkami zegara while self.run: time.sleep(0.005) try: #print("przed metoda") # self.updateAngle() # if (self.AM2 < self.AM1 and self.AM1 - self.AM2 < 180): self._run_in_thread2(self.silnik_1.Jedz, self.right_stick[1]) # Dzialania silnika sa uruchamiane w watku zeby mozna bylo sterowac np. dwoma silnikami jednoczenie bez self._run_in_thread2(self.silnik_2.Jedz, self.left_stick[1]) # przerywania pracy programu i monitorowania pada ## elif (self.AM1 <= minA): ## self._run_in_thread2(self.silnik_1.Jedz, ujemna) ## print("A<minA") ## ## elif (sef.AM1 >= maxA): ## self._run_in_thread2(self.silnik_1.Jedz, dodatnia) ## print("A>=maxA") # elif (self.AM2 + 5 >= self.AM1): # self._run_in_thread2(self.silnik_2.Jedz, ujemna) # print("B+5>=A") ## elif (self.AM2 <= minB): ## self._run_in_thread2(self.silnik_2.Jedz, dodatnia) ## print("B<=minB") ## elif (self.AM2 >= maxB): ## self._run_in_thread2(self.silnik_2.Jedz, ujemna) ## print("B>=maxB") #elif (self.AM1 - self.AM2 >= 180): # self._run_in_thread2(self.silnik_2.Jedz, dodatnia) # print("A-B>=180") ## if(AM1 != oldAM1 or AM2 != oldAM2) ## if(self.stara_pozycja_1 != (self.silnik_1.pozycja.voltage-0.780)*360/(3.946 - 0.780) or self.stara_pozycja_2 != (self.silnik_2.pozycja.voltage-0.780)*360/(3.946 - 0.780)): ## os.system("clear") ## #print("Silnik 1: \t{:>5.3f}".format((self.silnik_1.pozycja.voltage-0.780)*360/(3.946 - 0.780))) #========================================================= ## #print("Silnik 2: \t{:>5.3f}".format((self.silnik_2.pozycja.voltage-0.780)*360/(3.946 - 0.780)) ## print("Silnik 1: \t{:>5.3f}".format(AM1) ## print("Silnik 1: \t{:>5.3f}".format(AM2) #=MA RAZIE NIE DZIALA TRZEBA USTAWIC ODPOWIEDNIO ENKODERY= ## self.stara_pozycja_1 = (self.silnik_1.pozycja.voltage-0.780)*360/(3.946 - 0.780) #=WYSKALOWAC ENKODERY WZGLEDEM MOZLIWYCH OBROTOW MANIPU. = ## self.stara_pozycja_2 = (self.silnik_2.pozycja.voltage-0.780)*360/(3.946 - 0.780) #=ZEBY NIE BYLO W POLOWIE OBROTU RAMIENIA ZMIANY ODCZYTU = ## print("za metoda") #=Z 0 NA 2V. = ## #========================================================= except Exception as e: print(e) pass def _run_in_thread2(self, func, predkosc): # Ta metoda sluzy dla silnikow thread = Thread(target=func, args=[predkosc]) thread.start() def _run_in_thread(self, func): # Ta metoda jest gdzies w programie - klasa z niej korzysta gdzies tam print("przed watkiem 1") thread = Thread(target=func) thread.start()
# SPI/GPIO, top edge of board SPI_CE1 = 7 #BOARD 26, BCM 7 SPI_CE0 = 8 #BOARD 24, BCM 8 SPI_SCLK = 11 #BOARD 23, BCM 11 SPI_MISO = 9 #BOARD 21, BCM 9 SPI_MOSI = 10 #BOARD 19, BCM 10 GPIO_PINS = [GPIO1, GPIO2, GPIO3, GPIO4, SPI_CE1, SPI_CE0,\ SPI_SCLK, SPI_MISO, SPI_MOSI] for pin in GPIO_PINS: GPIO.setup(pin, GPIO.OUT) # ADC ads1 = ADS.ADS1115(i2c, address=0x49, data_rate=860, mode=0) ads2 = ADS.ADS1115(i2c, address=0x48, data_rate=860, mode=0, gain=2) CHAN0 = AnalogIn(ads1, ADS.P0) CHAN1 = AnalogIn(ads1, ADS.P1) CHAN2 = AnalogIn(ads1, ADS.P2) CHAN3 = AnalogIn(ads1, ADS.P3) CHAN4 = AnalogIn(ads2, ADS.P0) CHAN5 = AnalogIn(ads2, ADS.P1) CHAN6 = AnalogIn(ads2, ADS.P2) CHAN7 = AnalogIn(ads2, ADS.P3) # Channels for the pot and force sensors POT_CHAN = CHAN2 X_LOAD_CHAN = CHAN4 Y_LOAD_CHAN = CHAN3
def main(): if (len(sys.argv) != 2): sys.stderr.write('Usage: "{0}" $hostAddress\n'.format(sys.argv[0])) os._exit(1) # 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 chan = AnalogIn(ads, ADS.P0) # Dict with some GPIO pin numbers pinList = {"countState": 7, "count": 8} # Setup GPIO setmode GPIO.setmode(GPIO.BCM) # Set GPIO pin signal OUT and initial value "shutdown" GPIO.setup(list(pinList.values()), GPIO.OUT, initial=GPIO.LOW) # Setup MQTT instance client = mqtt.Client() # Setup the callback functions client.on_connect = on_connect client.on_disconnect = on_disconnect # Setup Control vars client.connectedFlag = False # Connect to the Broker server. print("conectando al broker") client.connect(sys.argv[1], 1883, 60) client.loop_start() while not client.connectedFlag: print("Esperando conexión") time.sleep(1) # Control of count system peopleCount = DataCount(client) # When magnetic element is far the min value is reached sensorValueMin = 6900 # When magnetic element is near the max value is reached sensorValueMax = 10300 """When magnectic element are middle of distances between min and max """ sensorValueMedium = (int( (sensorValueMax - sensorValueMin) / 2) + sensorValueMin) baseTime = time.time() countTemp = 0 # Count value while state count and doesn't show countTempLast = 0 # For toggle LED alert count +1 # Flags for execute only one time (turn off, turn on) counted = False countState = False countTempLastState = True countRate = 0.6 # Setup Threading, to show data every 20 seconds hilo0 = threading.Thread(target=show_data, args=[ peopleCount, ]) hilo0.start() while True: sensorValue = chan.value # Distance of magnetic sensor # Case if are plaque in high position if (sensorValue >= sensorValueMedium): baseTime = time.time() if (countTemp != 0): lock.acquire() peopleCount.countTimes += countTemp lock.release() countTemp = 0 # Turn off LED to alert plaque in high position if (countState): countState = False GPIO.output(pinList.get("countState"), GPIO.LOW) else: # Case if are plaque in low position """Triggered every showDataTime-1 seconds for update counTimes """ # print("is",sensorValue, sensorValueMedium) if (int(time.time()) % (showDataTime - 1) == 0): # Do only one time per showDataTime-1 if (not counted): lock.acquire() peopleCount.countTimes += countTemp lock.release() # Update base time with rate residue baseTime = time.time() - (time.time() % countRate) # Update countTempLast for LED count alert continueTime = time.time() - baseTime countTempLast = int(continueTime / countRate) + 1 counted = True else: counted = False continueTime = time.time() - baseTime # Count rate + 1 more (case 0 to 0.6) countTemp = int(continueTime / countRate) + 1 # Turn on LED to alert plaque in low position if (not countState): countState = True GPIO.output(pinList.get("countState"), GPIO.HIGH) # Turn on LED to alert every counted +1 for 1 cycle time if (countTempLast != countTemp): countTempLast = countTemp countTempLastState = False GPIO.output(pinList.get("count"), GPIO.HIGH) elif (not countTempLastState): countTempLastState = True GPIO.output(pinList.get("count"), GPIO.LOW) time.sleep(0.1) # Cycle time
def run(self): global DAC, WPt, WPpw, 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) i = 0 #------------------------------------- MAIN LOOP-------------------------------------------------- for i in range(500): 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) 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') pid.SetPoint = 10 #--------------------------------Para graficar la consigna----------------------------------------- if i == 0: consigna.append(0) else: 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')
import time import busio import adafruit_ads1x15.ads1115 as ADC from adafruit_ads1x15.analog_in import AnalogIn ADC_CLOCK = 3 ADC_SDATA = 2 if __name__ == "__main__": try: # Terminal initialisieren screen = curses.initscr() # A/D-Konverter initialisieren i2c_bus = busio.I2C(ADC_CLOCK, ADC_SDATA) ad_converter = ADC.ADS1115(i2c_bus) adc_channel0 = AnalogIn(ad_converter, ADC.P0) adc_channel1 = AnalogIn(ad_converter, ADC.P1) # Endlosschleife, damit das Programm weiterläuft while True: # Achsen messen x_voltage = adc_channel0.voltage x_value = adc_channel0.value y_voltage = adc_channel1.voltage y_value = adc_channel1.value # Ergebnis anzeigen screen.clear()
def main(): # 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 chan = AnalogIn(ads, ADS.P0) # Dict with some GPIO pin numbers pinList = {"countState": 7, "count": 8} # Setup GPIO setmode GPIO.setmode(GPIO.BCM) # Set GPIO pin signal OUT and initial value "shutdown" GPIO.setup(list(pinList.values()), GPIO.OUT, initial=GPIO.LOW) # Control of count system countPeople = DataCount() # When magnetic element is near the min value is reached sensorValueMin = 6900 # When magnetic element is far the max value is reached sensorValueMax = 10300 """When magnectic element are middle of distances between min and max, 85% of delta + minvalue is 85% traveled distance """ sensorValueMedium = int( (sensorValueMax - sensorValueMin) * 0.85) + sensorValueMin baseTime = time.time() countTemp = 0 # Count value while state count and doesn't show countTempLast = 0 # For toggle LED alert count +1 # Flags for execute only one time (turn off, turn on) counted = False countState = False countTempLastState = True countRate = 0.6 # Setup Threading, to show data every 20 seconds hilo0 = threading.Thread(target=show_data, args=[ countPeople, ]) hilo0.start() while True: sensorValue = chan.value # Distance of magnetic sensor # Case if pressure plate is not pressed magnetic element is far (max value) if (sensorValue >= sensorValueMedium): baseTime = time.time() if (countTemp != 0): lock.acquire() countPeople.countTimes += countTemp lock.release() countTemp = 0 # Turn off LED to alert plaque in high position if (countState): countState = False GPIO.output(pinList.get("countState"), GPIO.LOW) else: # Case if are plaque in low position """Triggered every showDataTime-1 seconds for update counTimes """ # print("is",sensorValue, sensorValueMedium) if (int(time.time()) % (showDataTime - 1) == 0): # Do only one time per showDataTime-1 if (not counted): lock.acquire() countPeople.countTimes += countTemp lock.release() # Update base time with rate residue baseTime = time.time() - (time.time() % countRate) # Update countTempLast for LED count alert continueTime = time.time() - baseTime countTempLast = int(continueTime / countRate) + 1 counted = True else: counted = False continueTime = time.time() - baseTime # Count rate + 1 more (case 0 to 0.6) countTemp = int(continueTime / countRate) + 1 # Turn on LED to alert plaque in low position if (not countState): countState = True GPIO.output(pinList.get("countState"), GPIO.HIGH) # Turn on LED to alert every counted +1 for 1 cycle time if (countTempLast != countTemp): countTempLast = countTemp countTempLastState = False GPIO.output(pinList.get("count"), GPIO.HIGH) elif (not countTempLastState): countTempLastState = True GPIO.output(pinList.get("count"), GPIO.LOW) time.sleep(0.1) # Cycle time
tipping.compute() return tipping.output['tip'] def adc_converter(chan1, chan2): v1 = chan1.voltage #0to3.3V v2 = chan2.voltage #0to3.3V return np.minimum(10, (v1 * 10 / 3.3)), np.minimum(10, (v2 * 10 / 3.3)) return if __name__ == "__main__": start = time.time() i2c = busio.I2C(board.SCL, board.SDA) ads = ADS.ADS1115(i2c, address=0x48) dac = adafruit_mcp4725.MCP4725 fuzzySistem = Fuzzy() #Create single-ended input on channel 0 chan1 = AnalogIn(ads, ADS.P0) chan2 = AnalogIn(ads, ADS.P1) while True: qual, serv = adc_converter(chan1, chan2) print('Quality:', qual) print('Servicio:', serv) u = fuzzy_control(fuzzySistem, qual, serv) print('Fuzzy Output: ' + str(u)) dt = time.time() - start print('Time: ' + str(dt)) print(' ')
def slidingWindow(): i2c = busio.I2C(board.SCL, board.SDA) ads = ADS.ADS1115(i2c) chan0 = AnalogIn(ads, ADS.P0) chan1 = AnalogIn(ads, ADS.P1) chan2 = AnalogIn(ads, ADS.P2) chan3 = AnalogIn(ads, ADS.P3) i=0 amplitude=[] time_signal=[] temps_actuel=time.time() # Save the data in two lists while time.time()-temps_actuel<60: tension=chan0.value amplitude.append(tension) time_signal.append(time.time()-temps_actuel) print("while finit") # Ending time of the signal end_time = time_signal[-1] # Starting time of the signal start_time = time_signal[0] # Window size window_size = 30 for i in range(0, round(end_time)-window_size): time_window_30sec = [t for t in time_signal if i <= t <= t+30] # Extract the min and the max of the signal inside the window min_time = min(time_window_30sec) max_time = max(time_window_30sec) # Index of min and max time index_min_time = time_window_30sec.index(min_time) index_max_time = time_window_30sec.index(max_time) # Amplitude of signal inside window amplitude_window_30sec = amplitude[index_min_time:index_max_time] print("CSV amp,time") # Create csv file to save signal (amplitude and time) inside the window x = get_rr_list_amp(amplitude_window_30sec,time_window_30sec) BPM_result = BPM(x) IBI_result = IBI(x) SDNN_result = SDNN(x) SDSD_result = np.std(SDSD(x)) RMSD_result = np.sqrt(np.mean(SDSD(x))) #BalanceSV_result = np.sqrt(np.mean(sympatho_vagal_balance(x))) # Export data into a CSV file print("CSV dataset") saveToCSV("TEST_dataset.csv",BPM_result,IBI_result,SDNN_result,SDSD_result,RMSD_result) print("END")
import os import time import board import busio import numpy as np import matplotlib.pyplot as plt import adafruit_ads1x15.ads1115 as ADS from adafruit_ads1x15.analog_in import AnalogIn from IIR2Filter import IIR2Filter import Adafruit_MCP4725 # 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 a DAC instance. DAC = Adafruit_MCP4725.MCP4725(address=0x60, busnum=1)
import bme280 import datetime import time import pymysql.cursors import signal import board import busio import adafruit_ads1x15.ads1115 as ADS from adafruit_ads1x15.analog_in import AnalogIn import adafruit_bme280 i2c = busio.I2C(board.SCL,board.SDA) bme280 = adafruit_bme280.Adafruit_BME280_I2C(board.I2C(),address = 0x76) ADS0 = ADS.ADS1115(i2c,gain = 1,address = 0x48) ADS1 = ADS.ADS1115(i2c,gain = 1,address = 0x49) ch0_10 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] connection = pymysql.connect( user = "******", passwd = "minoru0869553434", # host = "localhost", # host = "192.168.1.104", host = "127.0.0.1", db = "IoT_TEST", charset = "utf8mb4", ) def getData(arg1,args2): #EnvData = bme280.sample(bus, BMP280address,BMP280calibration_params)