def updateInt(): if not test_environment: emit('randint', [adc.read(0), adc.read(1), adc.read(2)]) else: emit('randint', [max(random.randint(latest_sensor_readings[0][-1] - 5, latest_sensor_readings[0][-1] + 5), 0), max(random.randint(latest_sensor_readings[1][-1] - 5, latest_sensor_readings[1][-1] + 5), 0), max(random.randint(latest_sensor_readings[2][-1] - 5, latest_sensor_readings[2][-1] + 5), 0)])
def update_recent_readings_adc(): for x in range(0, 3): if len(latest_sensor_readings[x]) < 200: latest_sensor_readings[x] += [adc.read(x)] else: latest_sensor_readings[x].pop(0) latest_sensor_readings[x] += [adc.read(x)] with open(csv_filename, 'a') as writeFile: writer = csv.writer(writeFile) writer.writerow([adc.read(1), adc.read(2), adc.read(3), time.strftime("%H:%M:%S", time.localtime())]) if running_status: threading.Timer(.3, update_recent_readings).start() else: print("Closing files, exiting threads", flush=True) writeFile.close()
def read_analog_input(board): ''' input parameters: - board: board address output parameters: - code: maximum value of last 10 measures (in Volts, from MIN_SCALE to FULL_SCALE) ---------------------------- description: this function reads an analog input (from -10V to 10V, but only used monopolar range, i.e., 0 to +10V, mapped in 0 to FULL_SCALE voltage). ''' global lock with lock: selection.adc(board) code = adc.read() # remove the oldest measure of the array ADC_array.pop(0) # append new value to the array ADC_array.append(code) # complete array size to be 10 (in case of error) while (len(ADC_array) != 10): ADC_array.append(0) #print(ADC_array) #print(max(ADC_array)) return max(ADC_array)
def joystick(): try: joystick_y = adc.read(1) joystick_x = adc.read(2) except: print("Fail PCF8591 adc module") if (joystick_x <= 120): pitch = (joystick_x - 120) / 120.0 * -6.5 elif (joystick_x >= 140): pitch = (joystick_x - 140) / 115.0 * -6.5 else: pitch = 0 if (joystick_y <= 120): roll = (joystick_y - 120) / 120.0 * -6.5 elif (joystick_y >= 140): roll = (joystick_y - 140) / 115.0 * -6.5 else: roll = 0 values = (pitch, roll) return values
def read(): # Send a reset signal gpio.set(24, 1) gpio.set(23, 1) gpio.set(23, 0) gpio.set(24, 0) l = [] r = [] for i in range(7): gpio.set(23, 1) gpio.set(23, 0) l.append(adc.read(2)) r.append(adc.read(3)) return [l, r]
def sampling(): global freq while True: value = adc.read(A1) freq[0] = value // 10 freq[1] = freq[0] * 2 freq[2] = freq[0] * 4 sleep(50)
def battery(): try: value_adc = adc.read(3) sleep(0.01) except ValueError: print("Error adc module, voltage Battery") except: print("Error PCF8591 adc module") return value_adc
def server_thread(): global threadID threadID = threading.get_ident() try: server.listen(1) clientsocket, clientAddress = server.accept() global csocket global msg global command csocket = clientsocket print("Connection Established") print("Connection from : ", clientAddress) print(csocket.recv(1024)) msg = "0" while True: signal.alarm(3) data = csocket.recv(1024) signal.alarm(0) data = data.decode() data,ignore1,ignore2 = data.partition("0") if data == 'a': os.kill(os.getpid(), signal.SIGUSR1) elif data == 'kill': os.kill(os.getpid(), signal.SIGINT) break elif data != "": print(data) command = data data = "0" if GPIO.input(CH1) == GPIO.HIGH: Burn = "0" else: Burn = "1" #Pre = str(round(12.12165135, 1)) Pre = str(round(adc.read(), 1)) data_out ="" data_out = msg +";"+ Ign +";"+ Val +";"+ Burn +";"+ Pre +";" + ERROR + ";" #print(data_out) csocket.send(bytes(data_out,'utf-8')) except SocketError: print("EXCEPTION") os.kill(os.getpid(), signal.SIGINT) print("Connection Broken") threadID = 0
def read_analog_input_raw(board): ''' input parameters: - board: board address output parameters: - code: raw value of ADC measures (in Volts, from MIN_SCALE to FULL_SCALE) ---------------------------- description: this function reads an analog input (from -10V to 10V, but only used monopolar range, i.e., 0 to +10V, mapped in 0 to FULL_SCALE voltage). ''' global lock #global MIN_SCALE, MAX_SCALE, FULL_SCALE with lock: selection.adc(board) code = adc.read() #volts = adc.meanVolts(1000) #volts = adc.readVolts() #volts = (volts / 10) * (FULL_SCALE - MIN_SCALE) #return round(volts,6) return code
def _battery_level_calc(self, chg_state=False): chg = None if chg_state: chg = digitalRead(self.chg_pin) if chg == 0: chg = True else: chg = False val = adc.read(self.bat_sense) bat = val * (3.3 / 65535.0) * 1000 if bat > 2670: bat_level = 100 elif bat > 2500: bat_level = 50 * (bat - 2500) / 170.0 bat_level += 50 elif bat > 2430: bat_level = 20 * (bat - 2430) / 70.0 bat_level += 30 elif bat > 2370: bat_level = 20 * (bat - 2370) / 60.0 bat_level += 10 else: bat_level = 0 return bat_level, chg
digitalWrite(LED0, HIGH) sleep(delay) digitalWrite(LED0, LOW) sleep(delay) for retry in range(10): try: wifi.link(wifi_config.SSID, wifi.WIFI_WPA2, wifi_config.PASSWORD) break except Exception as e: on_error(100) if not wifi.is_linked(): on_error(200) else: digitalWrite(LED0, HIGH) while True: try: values = [] for i in range(200): values.append(clean_value(adc.read(A3))) requests.post(wifi_config.HOST, json={ "min": min(values), "max": max(values), "avg": sum(values) / len(values) }) except Exception as e: print(e)
################################################################################ # Toishield basic # # Created by VIPER Team 2015 CC # Authors: L. Rizzello, G. Baldi, D. Mazzei ############################################################################### import streams import adc from toishield import toishield streams.serial() # toishield defines pin names in a board indipendent manner # let's use them to read raw sensors values while True: print(" Microphone:",adc.read(toishield.microphone_pin)) print(" Light:",adc.read(toishield.light_pin)) print("Temperature:",adc.read(toishield.temperature_pin)) print(" Touch:",digitalRead(toishield.touch_pin)) # aux pins are also accessible! print(" AUX1:",adc.read(toishield.aux1.ADC)) print("-"*40) sleep(500) # this scripts runs on every supported board, without a single change...cool isn't it? :)
import adc # 別のファイルadc.pyで宣言した関数を使えるようにする。 import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BCM) adc.init() try: while True: inputVal0 = adc.read(0) print(inputVal0) sleep(0.2) except KeyboardInterrupt: pass GPIO.cleanup()
################################################################################ # Toishield basic # # Created by VIPER Team 2015 CC # Authors: L. Rizzello, G. Baldi, D. Mazzei ############################################################################### import streams import adc from drivers.toishield import toishield streams.serial() # toishield defines pin names in a board indipendent manner # let's use them to read raw sensors values while True: print(" Microphone:",adc.read(toishield.microphone_pin)) print(" Light:",adc.read(toishield.light_pin)) print("Temperature:",adc.read(toishield.temperature_pin)) print(" Touch:",digitalRead(toishield.touch_pin)) # aux pins are also accessible! print(" AUX1:",adc.read(toishield.aux1.ADC)) print("-"*40) sleep(500) # this scripts runs on every supported board, without a single change...cool isn't it? :)
streams.serial() # save the template.html in the board flash with new_resource new_resource("template.html") # connect to a wifi network try: cc3000.auto_init() print("Establishing Link...") wifi.link("Network-Name",wifi.WIFI_WPA2,"Wifi-Password") print("Ok!") except Exception as e: print(e) # Configure and run the ViperApp instance vp = viperapp.ViperApp("Oscilloscope","Yeah, a javascript oscilloscope","resource://template.html") vp.run() while True: sleep(500) # read from adc x = adc.read(A4) # send the value to the mobile app via a notification event called "adc" # the notification is sent only after the mobile app to viper script link is established ;) vp.notify("adc",x)
# connect to the wifi network (Set your SSID and password below) wifi_driver.auto_init() for i in range(0,5): try: wifi.link("SSID",wifi.WIFI_WPA2,"PASSWORD") break except Exception as e: print("Can't link",e) else: print("Impossible to link!") while True: sleep(1000) # Start the Zerynth app instance! # Remember to create a template with the files under the "template" folder you just cloned # upload it to the ADM and associate it with the connected device zapp.run() # Read ADC and send values to the ADM while True: sleep(1000) x = (adc.read(A4)*100)//4096 zapp.event({"data":x}) if x>95: # send mobile notification # (there is a limit of one notification per minute per device on the ADM sandbox) zapp.notify("ALARM!","The value is greater than 95!") except Exception as e: print(e)
def get_y(): y = adc.read(thunbVry) # values from 0 to 4095 print(y) return y
msg = "Opening the Valve" print("Opening the Valve") GPIO.output(CH4, GPIO.HIGH) ======= GPIO.output(CH2, GPIO.HIGH) Ign = "0" msg = "Opening the Valve" print("Opening the Valve") GPIO.output(CH4, GPIO.LOW) >>>>>>> e171732815b4e2932e13c3b76866fa8df5909a59 Val = "1" msg = "Waiting for pressure build" print("Waiting for pressure build") adc.set_ref_time() while adc.read() < 100: pass msg = "Waiting for pressure drop" print("Waiting for pressure drop") temp = adc.read() while temp > 70 and temp < 900: temp = adc.read() pass msg = "Closing the Valve" print("Closing the Valve") <<<<<<< HEAD GPIO.output(CH4, GPIO.LOW) ======= GPIO.output(CH4, GPIO.HIGH) >>>>>>> e171732815b4e2932e13c3b76866fa8df5909a59 Val = "0"
def repetibility_error(board): # run calibration function and get the step that should be used #step = calibration(2) # turns on DAC and ADC circuit dac.on(board) adc.on(board) # select DAC of the board requested selection.dac(board) dac.config() print " ======================================================\n" from time import gmtime, strftime timestr = strftime("%Y-%m-%d_%H-%M-%S", gmtime()) filename = "repetibility/" + timestr + "_error_log_file.csv" log = open(filename, "a+") # set tabs of .csv file log.write('Iteracao') log.write(';Status') log.write(';Horario') log.write(';Valor setado [LSB]') log.write(';Valor lido [LSB]') log.write(';Valor lido [V]') log.write(';Diferenca [LSB]') log.write('\n') # Update the file log.close() # save time when test started startTime = time.time() ############################################################ print " ============================================================================" print " | REPETIBILIDADE |" print " ============================================================================" print " | DAC\t\tMULT.\t\tMULT.(LSB)\tADC\tADC(V)\t\tTEMP.|" print " |--------------------------------------------------------------------------|" iteration = 0 error = 0 while (1): # read current time startTime = time.time() #while ((time.time() - startTime) < 1*60*60): points = 1024 while ((time.time() - startTime) < 1*60*60): for i in range(points): base = int((math.sin(i*1.0/points*2*math.pi) + 1)*131071.5) # select DAC and write correspondent value selection.dac(board) dac.write(base) #time.sleep(0.01) selection.adc(board) adc_value = adc.read() adc_volt = float(adc_value) / 262143 * 20 - 10 adc_volt_str = '{:.8f}'.format(adc_volt) # check if an error occurred if (abs(adc_value - base) > 100): error += 1 print error # write in log file log = open(filename, "a+") timestr = strftime("%Y/%m/%d_%H:%M:%S", gmtime()) log.write(str(iteration) + ";erro;" + timestr + ';' + str(base) + ';' + str(adc_value) + ';' + str(adc_volt) + ';' + str((adc_value - base)) + "\n") # Update the file log.close() # print data on terminal sys.stdout.write(" | " + str(base) + "\t" + "----- " + "\t" + " ----- " + "\t") # --------------------------------------------------------- sys.stdout.write(str(adc_value) + "\t") # --------------------------------------------------------- if (adc_volt < 0): sys.stdout.write(str(adc_volt_str) + "\t") else: sys.stdout.write("+" + str(adc_volt_str) + "\t") # --------------------------------------------------------- # sys.stdout.write(temp_str + "|" + "\n") sys.stdout.write('---\t' + "|" + "\n") print " |--------------------------------------------------------------------------|" print "ERROR = " + str(error) # write in log file log = open(filename, "a+") timestr = strftime("%Y/%m/%d_%H:%M:%S", gmtime()) log.write(str(iteration) + ";fim de ciclo;" + timestr + "\n") # Update the file log.close() iteration += 1 print "ERRO = " + str(error)
#----------Set angles servos----------# end_servo = bf.set_servo_values(servos_value, min_signal_degree, max_signal_degree, min_servo_signal, max_servo_signal, "online", servos) except ValueError: print( "\n\x1b[1;31m" + "Error: It isn't posible set the current position (MathDomain Error)\n" ) print("\x1b[0;37m", end="") set_plataform([0, 0, 0], [0, 0, 110]) t.sleep(1) set_plataform([0, 0, 0], [0, 0, 114]) while True: joystick_y = adc.read(1) joystick_x = adc.read(2) if (joystick_x <= 120): pitch = (joystick_x - 120) / 120.0 * -6.5 if (joystick_x >= 140): pitch = (joystick_x - 140) / 115.0 * -6.5 if (joystick_x > 120 and joystick_x < 140): pitch = 0 if (joystick_y <= 120): roll = (joystick_y - 120) / 120.0 * -6.5 if (joystick_y >= 140): roll = (joystick_y - 140) / 115.0 * -6.5 if (joystick_y > 120 and joystick_y < 140): roll = 0 set_plataform([0, pitch, roll], [0, 0, 117])
def repetibility(board): # select DAC of the board requested selection.dac(board) dac.config() print " ======================================================\n" from time import gmtime, strftime timestr = strftime("%Y-%m-%d_%H-%M-%S", gmtime()) filename = "repetibility/" + timestr + "_" tensoes = [-9, -5, 0, 5, 9] # total time of the test (in seconds) # total_time = 12*60*60 total_time = 0.07 * 60 * 60 # save time when test started startTime = time.time() ############################################################ for x in tensoes: if (x > 0): log = open(filename + "+" + str(x) + "V.csv", "a+") else: log = open(filename + str(x) + "V.csv", "a+") # set tabs of .csv file log.write(';Valor lido no multimetro (V)') log.write(';Valor lido no multimetro (LSB)') log.write(';ADC - Leitura do valor integrado (V)') log.write(';ADC - Leitura do valor integrado (LSB)') log.write(';MBTemp1:Channel5 (graus C)') log.write('\n') # Update the file log.close() print " ============================================================================" print " | REPETIBILIDADE |" print " ============================================================================" print " | DAC\t\tMULT.\t\tMULT.(LSB)\tADC\tADC(V)\t\tTEMP.|" print " |--------------------------------------------------------------------------|" while ((time.time() - startTime) < total_time): for x in tensoes: base = int(((x + 10) / (20 / float(262144)))) # select DAC and write correspondent value selection.dac(board) dac.write(base) time.sleep(0.01) # --------------------------------------------------- if (x > 0): log = open(filename + "+" + str(x) + "V.csv", "a+") else: log = open(filename + str(x) + "V.csv", "a+") # --------------------------------------------------- selection.adc(board) adc_value = adc.read() ''' measure = [] for j in range(100): measure.append(adc.read()) # #print numpy.mean(measure) adc_value = sum(measure) / len(measure) ''' if (abs(adc_value - base) > 1000): error += 1 print error # adc = "{:1}".format(adc) # adc = numpy.mean(measure) adc_volt = float(adc_value) / 262143 * 20 - 10 adc_volt_str = '{:.8f}'.format(adc_volt) #adc_volt_str = str(adc_volt) #adc_volt_str = adc_volt_str[0:adc_volt_str.find(".") + 8] # --------------------------------------------------- log.write(str(base) + ';' + ';' + str(adc_value) + ';' + str(adc_volt) + ';;') ''' for j in range(100): log.write(str(measure[j]) + ';') log.write('\n') ''' # Update the file log.close() # print data on terminal sys.stdout.write(" | " + str(base) + "\t" + "----- " + "\t" + " ----- " + "\t") # --------------------------------------------------------- sys.stdout.write(str(adc_value) + "\t") # --------------------------------------------------------- if (adc_volt < 0): sys.stdout.write(str(adc_volt_str) + "\t") else: sys.stdout.write("+" + str(adc_volt_str) + "\t") # --------------------------------------------------------- # sys.stdout.write(temp_str + "|" + "\n") sys.stdout.write('---\t' + "|" + "\n") print " |--------------------------------------------------------------------------|" print "ERROR = " + str(error)
# Analog Read # # Created by Zerynth Team 2015 CC # Authors: G. Baldi, D. Mazzei ################################################################################ import streams # import the streams module import adc # import the adc driver # create a stream linked to the default serial port streams.serial() while True: # Basic usage of ADC for acquiring the analog signal from a pin value = adc.read(A0) print("One sample:",value) # The complete definition of adc.read() is adc.read(pin, samples=1) # For an advanced usage of adc.read refer to the official Zerynth documentation #acquire 10 samples with default sampling period value2 = adc.read(A0,10) print("10 samples:\n",value2) #acquire 3 samples from the first 4 analog pins of the board with default sampling period value3= adc.read([A0,A1,A2,A3],3) print("3 samples from A0, A1, A2 and A3:\n",value3) print() sleep(300)
#!/usr/bin/python from Adafruit_BBIO.SPI import SPI import Adafruit_BBIO.GPIO as GPIO import dac import adc import sys import math import time #======================================================= # stability test #======================================================= dac.config() adc.read() from time import gmtime, strftime timestr = strftime("%Y-%m-%d_%H-%M-%S", gmtime()) filename = "ADC stability/" + timestr + "_" #from epics import caput #from epics import caget #import Agilent34420A #voltage = [-9, -5, 0, 5, 9] voltage = [9] #total time of the test (in seconds) total_measures = 10000 # defining variables for MAX, MIN and MEAN (ADC measure) min_adc = [0] * 5 max_adc = [0] * 5
#!/usr/bin/env python import sys, math, time import adc, eq, gpio, led while True: l = int(math.fabs(adc.read(0)-512)/13) r = int(math.fabs(adc.read(1)-512)/13) sys.stdout.write("\r") for i in range(l): sys.stdout.write('#') for i in range(39-l): sys.stdout.write(' ') for i in range(r): sys.stdout.write('#') for i in range(39-r): sys.stdout.write(' ') sys.stdout.write(repr(eq.read())+" ") sys.stdout.flush()
################################################################################ # Analog Read to Voltage # # Created by Zerynth Team 2015 CC # Authors: G. Baldi, D. Mazzei ################################################################################ import streams import adc # import the adc module #create a serial port stream with default parameters streams.serial() while True: #read the input on analog pin 0 sensor_value = adc.read(A0) #convert the analog reading (which goes from 0 - 4095.0) to a voltage (0 - 3.3V): voltage = sensor_value * (3.3 / 4095.0) #print out the raw and converted values: print("sensor raw value:", sensor_value,"Voltage:",voltage) sleep(300)
def curvalue( self ): adc.read(self._adc, lightsensor._MUX)
from libs.apps import viperapp streams.serial() # save the template.html in the board flash with new_resource new_resource("template.html") # connect to a wifi network try: cc3000.auto_init() print("Establishing Link...") wifi.link("Network-Name", wifi.WIFI_WPA2, "Wifi-Password") print("Ok!") except Exception as e: print(e) # Configure and run the ViperApp instance vp = viperapp.ViperApp("Oscilloscope", "Yeah, a javascript oscilloscope", "resource://template.html") vp.run() while True: sleep(500) # read from adc x = adc.read(A4) # send the value to the mobile app via a notification event called "adc" # the notification is sent only after the mobile app to viper script link is established ;) vp.notify("adc", x)
def get_x(): x = adc.read(thunbVrx) print(x) return x
def sampling(): global input_val while True: input_val['pot_val'] = helpers.map_range(adc.read(pot_pin),0,4000,1,1000) input_val['prox_val'] = helpers.map_range(adc.read(prox_pin),300,3800,1,1000) sleep(50)
def readSound(self): sound = adc.read(self.sndSnsr) multiplier = adc.read( self.potentiometer ) / 1500.0 # Al posto di 4095.0 per usare il potenziometro in posizione centrale return sound * multiplier
############################################################################### # Zerynth oscilloscope # # Created by Zerynth Team 2015 CC # Authors: G. Baldi, D. Mazzei ############################################################################### import streams import adc streams.serial() while True: value = adc.read(A4) conv = value * 80 // 4095 print("|", "#" * conv, " " * (80 - conv), "|") sleep(200)
#!/usr/bin/env python import sys, math, time import adc, eq, gpio, led while True: raw_l = adc.read(0) raw_r = adc.read(1) raw_eq = eq.read() l1 = 255-int(math.fabs(raw_l-512)/2) r1 = 255-int(math.fabs(raw_r-512)/2) l1 = 255 l2 = 255 led.led_send([l1, r1, l1]) # l2 = (128-l1 / 2) + 128 # r2 = (127-r1 / 2) + 128 r = (raw_eq[0][0] + raw_eq[0][1] + raw_eq[1][0] + raw_eq[1][1]) / 4 g = (raw_eq[0][2] + raw_eq[0][3] + raw_eq[1][2] + raw_eq[1][3]) / 4 b = (raw_eq[0][5] + raw_eq[0][6] + raw_eq[1][5] + raw_eq[1][6]) / 4 r = int(r/10)+128 g = int(g/10)+128 b = int(b/10)+128 p = [] for count in range(led.rgb_count):
def child(Command = 0): while True: if Command == "1": if GPIO.input(Burn_Wire) == GPIO.HIGH: print("ERROR: Burn wire cut") os._exit(1) #Ignition countdown print("Three") time.sleep(1) print("Two") time.sleep(1) print("One") time.sleep(1) start_time = time.perf_counter() Deluge_timer = time.perf_counter() Deluge_on = False print("Start Ignition") while GPIO.input(Burn_Wire) == GPIO.LOW: if time.perf_counter() - start_time < 10: GPIO.output(Igniter, GPIO.HIGH) if time.perf_counter() - Deluge_timer > 1 and Deluge_on == False: print("Starting Deluge") Deluge_on = True GPIO.output(Deluge, GPIO.HIGH) else: print("ERROR: Ignition timeout") reset(0) os._exit(1) print("Stopping Igniter") GPIO.output(Igniter, GPIO.LOW) print("Starting Deluge") GPIO.output(Deluge, GPIO.HIGH) #print("Time to Ignite: " + str(time.perf_counter() - start_time)) print("Opening the Valve") GPIO.output(Valve, GPIO.HIGH) print("Waiting for pressure build") start_time = time.perf_counter() adc.set_ref_time() psi = adc.read() while psi < 220: if time.perf_counter() - start_time < 3: psi = adc.read() else: reset(0) print("Pressure Build Timeout") os._exit(1) break #Reset timer start_time = time.perf_counter() print("Waiting for pressure drop") while psi > 200: if time.perf_counter() - start_time < 6 and psi < 1000: psi = adc.read() else: reset(0) if psi >= 900: print("Over Pressure Failure") else: print("Pressure Drop Timeout") os._exit(1) print("Sequence Success: Closing the Valve") GPIO.output(Valve, GPIO.LOW) print("Command (input h for help): ") break elif Command == "2": print("Ignition ON") GPIO.output(Igniter, GPIO.HIGH) break elif Command == "3": print("Ignition OFF") GPIO.output(Igniter, GPIO.LOW) break elif Command == "4": print("Valve OPEN") GPIO.output(Valve, GPIO.HIGH) break elif Command == "5": print("Valve CLOSE") GPIO.output(Valve, GPIO.LOW) break elif Command == "6": print("Deluge ON") GPIO.output(Deluge, GPIO.HIGH) break elif Command == "7": print("Deluge OFF") GPIO.output(Deluge, GPIO.LOW) break elif Command == "8": print("Propane ON") GPIO.output(Propane, GPIO.HIGH) break elif Command == "9": print("Propane OFF") GPIO.output(Propane, GPIO.LOW) break elif Command == "h": print("1: Ignition Sequence") print("2: Ignition ON") print("3: Ignition OFF") print("4: Valve OPEN") print("5: Valve CLOSE") print("6: Deluge ON") print("7: Deluge OFF") print("8: Propane ON") print("9: Propane OFF") print("a: abort process") print("exit: exit program") break else: print("ERROR: invalid input") break os._exit(0)
def stability(board): # turns on DAC and ADC circuit dac.on(board) adc.on(board) # set up DAC selection.dac(board) dac.config(board) from time import gmtime, strftime timestr = strftime("%Y-%m-%d_%H-%M-%S", gmtime()) filename = "stability/" + timestr + "_" #from epics import caput #from epics import caget #import Agilent34420A voltage = [-9, -5, 0, 5, 9] #voltage = [9] #total time of the test (in seconds) total_measures = 10000 # defining variables for MAX, MIN and MEAN (ADC measure) min_adc = [0] * 5 max_adc = [0] * 5 mean_adc = [0] * 5 std_var = [0] * 5 i = 0 j = 0 ############################################################ for x in voltage: measure = [] if (x > 0): log = open(filename + "+" + str(x) + "V.csv", "a+") else: log = open(filename + str(x) + "V.csv", "a+") #set tabs of .csv file log.write('Indice') log.write(';Valor lido no multimetro (V)') log.write(';Valor lido no multimetro (LSB)') log.write(';ADC - Leitura do valor integrado (V)') log.write(';ADC - Leitura do valor integrado (LSB)') log.write(';MBTemp1:Channel5 (graus C)') log.write('\n') #Update the file log.close() print " ============================================================================" # sys.stdout.write(" | ESTABILIDADE: ") sys.stdout.write(" | STABILITY: ") if(x < 0): sys.stdout.write(str(x) + "V" + " |\n") elif(x > 0): sys.stdout.write("+" + str(x) + "V" + " |\n") else: sys.stdout.write(str(x) + "V" + " |\n") print " ============================================================================" print " | INDEX\tMULT.\t\tMULT.[LSB]\tADC\tADC(V)\t\tTEMP.|" print " |--------------------------------------------------------------------------|" # select DAC and write correspondent value base = int(((x+10)/(20/float(262144)))) selection.dac(board) dac.write(base) time.sleep(30) measure = [] for i in range (total_measures): if (x > 0): log = open(filename + "+" + str(x) + "V.csv", "a+") else: log = open(filename + str(x) + "V.csv", "a+") #--------------------------------------------------- selection.adc(board) mean_measure = [] for k in range(3): mean_measure.append(adc.read()) # #print numpy.mean(measure) adc_value = sum(mean_measure) / len(mean_measure) # adc_value = adc.read() measure.append(adc_value) # check if it is the first measure if(i == 0): min_adc[j] = measure[0] max_adc[j] = measure[0] mean_adc[j] = measure[0]*1.0 # if not, calculate max, min and mean else: if(measure[i] < min_adc[j]): min_adc[j] = measure[i] if(measure[i] > max_adc[j]): max_adc[j] = measure[i] mean_adc[j] = (mean_adc[j]*i + measure[i])/(i + 1) i += 1 #adc = "{:1}".format(adc) #adc = numpy.mean(measure) adc_volt = float(adc_value)/262143*20-10 adc_volt_str = str(adc_volt) adc_volt_str = adc_volt_str[0:adc_volt_str.find(".")+8] #--------------------------------------------------- #Get temperature #temp = caget("MBTemp_RAFAEL_1:Channel5") #temp_str = ("%.2f" %temp) #temp_str = str(temp_str) #temp_str = temp_str[0:temp_str.find(".")+3] #--------------------------------------------------- #Write all data #log.write(str(base+i)+ ';' + multimeter_int_str + ';' + str(multimeter_lsb) + ';' + str(adc) + ';' + str(adc_volt) + ';' + str(temp) + '\n') #log.write(str(base+i)+ ';' + multimeter_int_str + ';' + str(multimeter_lsb) + ';' + str(adc) + ';' + str(adc_volt) + ';' + '\n') #log.write(str(base+i)+ ';' + multimeter_int_str + ';' + str(multimeter_lsb) + ';' + str(adc) + ';' + str(adc_volt) + ';;') log.write(str(base+i)+ ';;;' + str(adc_value) + ';' + str(adc_volt) + ';;') # for k in range(100): # log.write(str(measure[k]) + ';') log.write('\n') #Update the file log.close() #print data on terminal sys.stdout.write(" | " + str(base) + "\t" + "------" + "\t\t" + "------\t" + "\t") #--------------------------------------------------------- sys.stdout.write(str(adc_value) + "\t") #--------------------------------------------------------- if(adc_volt < 0): sys.stdout.write(str(adc_volt_str) + "\t") else: sys.stdout.write("+" + str(adc_volt_str) + "\t") #--------------------------------------------------------- #sys.stdout.write(temp_str + "|" + "\n") sys.stdout.write('---\t' + "|" + "\n") print " | |" # #calculate standard deviation # part_sum = 0 # for i in range(len(measure)): # part_sum = part_sum + (measure[i] - mean_adc[j])**2 # std_var[j] = part_sum/(len(measure)*1.0) # std_var[j] = math.sqrt(std_var[j]) # std_var[j] = "{0:.4f}".format(std_var[j]) # mean_adc[j] = "{0:.2f}".format(mean_adc[j]) #--------------------------------------------------- # plot and save Histogram std_var[j] = plot_hist(board, x, measure, mean_adc[j]) mean_adc[j] = "{0:.2f}".format(mean_adc[j]) print " ============================================================================" #--------------------------------------------------- # print standard variation sys.stdout.write(" | std_dev = %s" %str(std_var[j])) for i in range (0, (6 - len(str(std_var[j])))): sys.stdout.write(' ') sys.stdout.write(' |\n') #------------------------------------------------------- # print minimum value acquired sys.stdout.write(" | ADC_min = %s" %min_adc[j]) for i in range (0, (6 - len(str(min_adc[j])))): sys.stdout.write(' ') sys.stdout.write(' |\n') #--------------------------------------------------- # print maximum value acquired sys.stdout.write(" | ADC_max = %s" %max_adc[j]) for i in range (0, (6 - len(str(max_adc[j])))): sys.stdout.write(' ') sys.stdout.write(' |\n') #--------------------------------------------------- # print mean sys.stdout.write(" | ADC_mean = %s" %mean_adc[j]) for i in range (0, (6 - len(str(mean_adc[j])))): sys.stdout.write(' ') sys.stdout.write(' |\n') #--------------------------------------------------- # print difference between max and min (histogram thickness) sys.stdout.write(" | diff = %s" %(max_adc[j] - min_adc[j])) for i in range (0, (6 - len(str(max_adc[j] - min_adc[j])))): sys.stdout.write(' ') sys.stdout.write(' |\n') #--------------------------------------------------- print " =============================" j += 1 # Print it all again after all the data were acquired j = 0 for x in voltage: sys.stdout.write(" | STABILITY: ") if(x > 0): sys.stdout.write("+") if(x == 0): sys.stdout.write(" ") sys.stdout.write(str(x) + "V |\n") print " =============================" #--------------------------------------------------- # print standard variation sys.stdout.write(" | std_dev = %s" %str(std_var[j])) for i in range (0, (6 - len(str(std_var[j])))): sys.stdout.write(' ') sys.stdout.write(' |\n') #------------------------------------------------------- # print minimum value acquired sys.stdout.write(" | ADC_min = %s" %min_adc[j]) for i in range (0, (6 - len(str(min_adc[j])))): sys.stdout.write(' ') sys.stdout.write(' |\n') #--------------------------------------------------- # print maximum value acquired sys.stdout.write(" | ADC_max = %s" %max_adc[j]) for i in range (0, (6 - len(str(max_adc[j])))): sys.stdout.write(' ') sys.stdout.write(' |\n') #--------------------------------------------------- # print mean sys.stdout.write(" | ADC_mean = %s" %mean_adc[j]) for i in range (0, (6 - len(str(mean_adc[j])))): sys.stdout.write(' ') sys.stdout.write(' |\n') #--------------------------------------------------- # print difference between max and min (histogram thickness) sys.stdout.write(" | diff = %s" %(max_adc[j] - min_adc[j])) for i in range (0, (6 - len(str(max_adc[j] - min_adc[j])))): sys.stdout.write(' ') sys.stdout.write(' |\n') #--------------------------------------------------- print " =============================" j += 1
# PotLED # Created at 2018-06-27 06:32:46.299130 import streams # import the streams module import adc streams.serial() led_1 = D11 pinMode(led_1, OUTPUT) while True: a = adc.read(A2) print(a) if a<512 : print("ON") digitalWrite(led_1,HIGH) # turn the LED ON by making the voltage HIGH sleep(1000) # wait for timeON else: print("OFF") digitalWrite(led_1,LOW) # turn the LED OFF by making the voltage LOW sleep(1000) # wait for timeOFF print("One sample:",a) print() sleep(300)
print("connecting...") print("connected.") #aqui o ESP8266 assina os tópicos abaixo client.subscribe([["desktop/samples", 1]]) client.subscribe([["desktop/others", 2]]) #habilita a publicação de dados client.on(mqtt.PUBLISH, print_sample, is_sample) client.loop(print_other) #dentro desse loop medimos a tensão que o sensor fornece para entrada analógica do ESP8266 e convertemos num valor de temperatura. while True: sleep(3000) value = adc.read(A0) print(value) Vout = (value * VCC) / adcRes Rth = (VCC * R2 / Vout) - R2 temperature = (1 / (A + (B * math.log(Rth)) + (C * math.pow( (math.log(Rth)), 3)))) temperature = temperature - 292.15 temperature = -1 * (temperature) #printamos o valor pela serial e logo em seguida enviamos o valor calculado para o Broker MQTT Mosquitto print(temperature) send_sample(temperature) if temperature % 10 == 0: publish_to_self( ) #caso ocorra alguma exceção ou erro, a temperatura publicada é um valor aleatório de 0 a 10 except Exception as e: