class Sensor(): def __init__(self, pin, name='Sensor', connection=default_connection, analog_pin_mode=False, key=None): self.pin = pin self.name = name self.key = key.replace( " ", "_").lower() if key is not None else self.name.replace( " ", "_").lower() self.analog_pin_mode = analog_pin_mode self.connection = connection self.api = ArduinoApi(connection) return def init_sensor(self): #Initialize the sensor here (i.e. set pin mode, get addresses, etc) pass def read(self): #Read the sensor(s), parse the data and store it in redis if redis is configured pass def readRaw(self): #Read the sensor(s) but return the raw data, useful for debugging pass def readPin(self): #Read the pin from the ardiuno. Can be analog or digital based on "analog_pin_mode" data = self.api.analogRead( self.pin) if analog_pin_mode else self.api.digitalRead(self.pin) return data
class Control(): def __init__(self, pin, name=None, connection=default_connection, analog_pin_mode=False, key=None, redis_conn=None): self.pin = pin if key is None: raise Exception('No "key" Found in Control Config') else: self.key = key.replace(" ", "_").lower() if name is None: self.name = self.key.replace("_", " ").title() else: self.name = name self.analog_pin_mode = analog_pin_mode self.connection = connection self.api = ArduinoApi(connection) try: self.r = redis_conn if redis_conn is not None else redis.Redis( host='127.0.0.1', port=6379) except KeyError: self.r = redis.Redis(host='127.0.0.1', port=6379) return def init_control(self): #Initialize the control here (i.e. set pin mode, get addresses, etc) self.api.pinMode(self.pin, self.api.INPUT) pass def read(self): #Read the sensor(s), parse the data and store it in redis if redis is configured return self.read_pin() def read_raw(self): #Read the sensor(s) but return the raw data, useful for debugging pass def read_pin(self): #Read the pin from the ardiuno. Can be analog or digital based on "analog_pin_mode" data = self.api.analogRead( self.pin) if self.analog_pin_mode else self.api.digitalRead( self.pin) return data def emitEvent(self, data): message = {'event': 'ControlUpdate', 'data': {self.key: data}} print(message["data"]) self.r.publish('controls', json.dumps(message))
def water_read_moisture(pin='A0'): air = 580 water = 277 connection = SerialManager() a = ArduinoApi(connection=connection) a.pinMode(pin, 'INPUT') moisture_read = ((a.analogRead(pin) * -1) + air) / 3.05 return moisture_read
def main(): connect_broker() connection = SerialManager(device='/dev/ttyACM0') a = ArduinoApi(connection=connection) a.pinMode(PIN, a.INPUT) try: client.loop_start() while True: value = a.analogRead(PIN) client.publish("messwerte/test", str(value), qos=1) print "value:" + str(value) sleep(1) except: client.loop_stop() print("publisher stopped")
class Control(): def __init__(self, pin, name='Control', connection=default_connection, analog_pin_mode=False, key=None): self.pin = pin self.name = name self.key = key.replace( " ", "_").lower() if key is not None else self.name.replace( " ", "_").lower() self.analog_pin_mode = analog_pin_mode self.connection = connection self.api = ArduinoApi(connection) return def init_control(self): #Initialize the control here (i.e. set pin mode, get addresses, etc) self.api.pinMode(self.pin, self.api.INPUT) pass def read(self): #Read the sensor(s), parse the data and store it in redis if redis is configured return self.readPin() def readRaw(self): #Read the sensor(s) but return the raw data, useful for debugging pass def readPin(self): #Read the pin from the ardiuno. Can be analog or digital based on "analog_pin_mode" data = self.api.analogRead( self.pin) if self.analog_pin_mode else self.api.digitalRead( self.pin) return data def emitEvent(self, data): message = {'event': 'ControlUpdate', 'data': {self.key: data}} print(message["data"]) variables.r.publish('controls', json.dumps(message))
sensor = device["type"] if (sensor == "dht22"): dht = DHT(device["port"], DHT.DHT22) type_values = device["type_values"] for type_value in type_values: name = type_value["name"] device_values = device["device_values"] if (name == "temperature"): device_values[name] = dht.readTemperature( False) elif (name == "humidity"): device_values[name] = dht.readHumidity() elif (sensor == "ldr"): a.pinMode(device["port"], a.INPUT) intensity = a.analogRead(device["port"]) type_values = device["type_values"] for type_value in type_values: name = type_value["name"] device_values = device["device_values"] if (name == "intensity"): device_values[name] = intensity elif (sensor == "pir"): a.pinMode(device["port"], a.INPUT) reading = a.digitalRead(device["port"]) motion = False if (reading == a.HIGH): motion = True type_values = device["type_values"] for type_value in type_values:
port = SerialManager(device='/dev/ttyACM0') # Sélection du port série (exemple : device = 'COM6') uno = ArduinoApi(connection=port) # Déclaration de la carte Arduino uno.pinMode(8, uno.OUTPUT) # Paramétrage de la broche 8 en sortie x = [] # Abscisse y = [] # Ordonnée # Décharge du condensateur avant les mesures uno.digitalWrite(8,0) # Broche 8 à OV sleep(2) # pendant 2 s # Début de la charge du condensateur uno.digitalWrite(8,1) # Broche 8 à 5V for i in range(40): # Boucle pour les mesures x.append(i) # Remplissage de x y.append(uno.analogRead(0)) # Mesure sur A0 et remplissage de y sleep(0.05) # Temporisation # Décharge du condesateur après mesures uno.digitalWrite(8,0) # Broche 8 à 0V port.close() # Fermeture du port série # Tracé de la courbe plt.plot(x,y,'r+') plt.title("R = 100k et C = 4,7uF (simple)") plt.xlabel("i") plt.ylabel("N") plt.ylim(0,1023) plt.grid() plt.show()
a.digitalWrite(relay1,a.HIGH) a.digitalWrite(relay2,a.LOW) print "Relay 1 OFF & Relay 2 ON" elif(val1 == 1 and val2 == 0): a.digitalWrite(relay1,a.LOW) a.digitalWrite(relay2,a.HIGH) print "Relay 1 ON & Relay 2 OFF" elif(val1 == 0 and val2 == 0): a.digitalWrite(relay1,a.HIGH) a.digitalWrite(relay2,a.HIGH) print "Both relays are OFF" else: print "only 0,1 is accepted" #power and timestamp upload I1 = a.analogRead(current1) I1= (I1-300)*0.025 I2 = a.analogRead(current2) I2 = (I2-400)*0.025 p1 = I1*4.06 p2 = I2*4.06 if(p1<0): p1 =0; if(p2<0): p2=0; print "power" p1=p1-21; p2=p2-11; print p1; print p2;
class CurrentSensor(threading.Thread): def __init__(self, _lcd): threading.Thread.__init__(self) try: self.conn = SerialManager() self.a = ArduinoApi(self.conn) except: print("Failed to connect to Arduino.") self.analogIn = '******' self.mVperAmp = 66 # use 100 for 20A Module and 66 for 30A Module self.voltage = 0 self.amps = 0 self.rawValue = 0 self.default = 510 # Current = Voltage You Applied / The Resistance of your Load self.lcd = _lcd def getAmps(self): self.readSensor() self.amps = round(((self.rawValue - self.default )* 27.03) / 1023,3) #self.amps = (self.default - self.a.analogRead(self.analogIn)) / 102.4 self.lcd.print("AMPS: {}".format(self.amps)) return self.amps def readSensor(self): count = 10 while count > 0: self.rawValue = self.a.analogRead(self.analogIn) if(self.rawValue < self.default): self.rawValue = self.default + (self.default - self.rawValue) count = count - 1 def run(self): try: while True: self.getAmps() self.saveReadings() #self.checkForLimit() time.sleep(1) except Exception as e: print("Reading error {}".format(str(e))) def getRawValue(self): self.readSensor() return self.rawValue def saveReadings(self): conn = ConnectionDB() query = ("""INSERT INTO tbl_liveamps(liveTime, liveValue, liveRaw) VALUES(CURRENT_TIME, %(lvValue)s, %(lvRaw)s)""") data = { 'lvValue': self.amps, 'lvRaw':self.rawValue,} conn.insertQueryArgs(query,data) def checkForLimit(self): conn = ConnectionDB() query = ("""SELECT value FROM tbl_settings WHERE stID = %s""") values = (1,) data = conn.execQueryArgs(query,values) if float(self.amps) > float(data['value']): #self.sendEmail(data['value']) print("more energy alert") def sendEmail(self, expected): sendMail = sendEmail() time_now = time.ctime() msg = """<html> <body> <h3 style="color:#FF0000">Motion Detected</h3> <p>Oops! Mr Molorane, your energy consumption has increased.Smart home strives always to help you save energy, save cost! <br/> Check the details below about the Energy consumption</p> <table border="2"> <tr> <td><b>Actual Energy Consumption</b></td> <td>{}amps</td> </tr> <tr> <td><b>Expected Energy Consumption</b></td> <td>{}amps</td> </tr> <tr> <td><b>Time </b></td> <td>{}</td> </tr> </table> <p style="color:#FF0000">Saving energy is important!</p> </body> </html>""".format(self.amps, expected, time_now) sendMail.send(msg)
from nanpy import (ArduinoApi, SerialManager) from time import sleep pot = 14 try: connection = SerialManager() a = ArduinoApi(connection=connection) except Exception as err: print(f"Failed to connect to Arduino {err}") # Setup the pinModes as if we were in the Arduino IDE #a.pinMode(ledPin, a.OUTPUT) #a.pinMode(buttonPin,a.INPUT) try: while True: val = a.analogRead(pot) print(f'{val/1023*5:.2f} {val}') sleep(0.1) except Exception as err: print(f'{err}')
uno.pinMode(8, uno.OUTPUT) # Paramétrage de la broche 8 en sortie n = 30 # Nombre de points de mesure temps = np.zeros(n) # Tableau temps y = np.zeros(n) # Tableau ordonnée # Décharge du condensateur avant les mesures uno.digitalWrite(8, 0) # Broche 8 à OV sleep(2) # pendant 2 s # Début de la charge du condensateur t0 = uno.millis() # Instant initial uno.digitalWrite(8, 1) # Broche 8 à 5V for i in range(n): temps[i] = uno.millis() y[i] = uno.analogRead(0) # Lecture tension sur A1 puis affichage sleep(0.1) # Décharge du condesateur après mesures uno.digitalWrite(8, 0) # Broche 8 à 0V port.close() # Fermeture du port série # Calculs des variables t = temps - t0 u = y * 5 / 1023 # Modélisation def expo(x, A, tau, xo): # Definition de la fonction return A * (1 - np.exp(-(x - xo) / tau)) # Expression du modèle
from nanpy import (ArduinoApi, SerialManager) import requests from time import sleep try: connection = SerialManager() a = ArduinoApi(connection=connection) except: print('Failed to connect to Arduino.') ldrPin = 0 a.pinMode(ldrPin, a.INPUT) while True: ldrStatus = a.analogRead(ldrPin) if ldrStatus >= 300: requests.post('https://api.simplepush.io/send', data={ 'key': 'Q4bcip', 'title': 'Washroom Lights', 'msg': 'The washroom lights are on!' }) else: pass sleep(120)
# Moisture power input connected to Arduino Nano digital pin 5, # while analog data output connected to Arduino analog pin 1 connection = SerialManager(device='/dev/ttyUSB0') arduino = ArduinoApi(connection=connection) arduino.pinMode(15, arduino.INPUT) arduino.pinMode(5, arduino.OUTPUT) # Turn on moisture sensor power arduino.digitalWrite(5, arduino.HIGH) print('Waiting 5 seconds') for i in range(5): time.sleep(1) sys.stdout.write('.') sys.stdout.flush() print('') humidity, temperature = DHT.read_retry(11, 4) moisture = arduino.analogRead(15) # Turn off moisture sensor power arduino.digitalWrite(5, arduino.LOW) connection.close() print('Temperature %dC' % temperature) print('Humidity %d%%' % humidity) print('Moisture %d' % moisture)
from nanpy import SerialManager from nanpy import ArduinoApi conn = SerialManager(device='/dev/ttyACM0') print(conn) a = ArduinoApi(connection=conn) print('test') a.analogRead('A0') print(a)
from nanpy import (ArduinoApi, SerialManager) from time import sleep import math batMonPin = 14 val = 0 pinVoltage = 0 BatteryVolatge = 0 try: connection = SerialManager() a = ArduinoApi(connection=connection) except: print("failed to connect to Arduino") a.pinMode(batMonPin, a.INPUT) try: while True: val = a.analogRead(batMonPin) print(a.analogRead(batMonPin)) pinVolatge = (val * 0.0020283) batteryVoltage = (pinVolatge * 60.992) print("Our Total is: {}".format(batteryVoltage)) sleep(1) except: print("Check man")
video_src = video_src[0] except: video_src = 0 args = dict(args) cascade_fn = args.get( '--cascade', "../../data/haarcascades/haarcascade_frontalface_alt.xml") nested_fn = args.get('--nested-cascade', "../../data/haarcascades/haarcascade_eye.xml") cascade = cv.CascadeClassifier(cascade_fn) nested = cv.CascadeClassifier(nested_fn) cam = create_capture(video_src, fallback='synth:bg=../data/lena.jpg:noise=0.05') while True: sensor1 = motorunit.analogRead( 0) #Sensor 1 functioning for the Back infrared sensor2 = motorunit.analogRead( 1) #Sensor 2 functioning for the front ultrasonics ret, img = cam.read() gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) gray = cv.equalizeHist(gray) t = clock() rects = detect(gray, cascade) vis = img.copy() draw_rects(vis, rects, (0, 255, 0)) if not nested.empty(): for x1, y1, x2, y2 in rects: print("Back sensor detection:") print(sensor1) print("Fron sensor distance :") print(sensor2)
#! /usr/bin/env python # Author: Gopal Krishan Aggarwal and Piyush Mangtani # Contact: [email protected] # Desc: This assumes arduino is connected as /dev/ttyACM0 device to RasPi. It reads the analog 0 pin of arduino and calculates the wind direction from the analog value as done below. Read sparkfun weather meter's datasheet for more details. from nanpy import ArduinoApi from nanpy import SerialManager c = SerialManager(device='/dev/ttyACM0') from time import sleep a = ArduinoApi(c) direction = a.analogRead(0) if direction >= 728 and direction <= 792: d = 0 #print "The wind direction is : NORTH " + str(direction) elif direction >= 228 and direction <= 257: d = 180 # print "The wind direction is : SOUTH " + str(direction) elif direction >= 0 and direction <= 97: d = 90 # print "The wind direction is : EAST " + str(direction) elif direction >= 924 and direction <= 961: d = 270 # print "The wind direction is : WEST " + str(direction) elif direction >= 384 and direction <= 442:
# -*- coding: utf-8 -*- # Lecture d'une tension sur l'entréé analogique A0 # Mesure en temps réel dans un boucle longue # from nanpy import ArduinoApi # Gestion Arduino from nanpy import SerialManager # Gestion port série from time import sleep # Importation de sleep(seconde) port = SerialManager(device='/dev/ttyACM0' ) # Sélection du port série (exemple : device = 'COM6') uno = ArduinoApi(connection=port) # Déclaration de la carte Arduino t = [] N = [] t0 = uno.millis() # Instant initial for i in range(20): t.append(uno.millis() - t0) # Temps N.append(uno.analogRead(0)) # Lecture CAN sur A0 #sleep(1) # Temporisation port.close() # Fermeture du port série print("Dt ; N ; U") print("ms ; _ ; V") for i in range(1, len(t)): print(t[i] - t[i - 1], ';', N[i], ';', round(N[i] * 5 / 1023, 2))
Servo7.write(angle7) # Sequence and pressure actuator control function def hydraulicsequence(goal1, goal2, goal3, goal4, Angle1, Angle2, Angle3, Angle4, pressure): # Pressure and angle control function for the hydraulic system hydraulicFrontlegLeft(goal1, Angle1, pressure) hydraulicFrontlegRight(goal2, Angle2, pressure) hydraulicBacklegRight(goal3, Angle3, pressure) hydraulicfBacklegLeft(goal4, Angle4, pressure) while True: #All Angle and sensor read for each condition Leg function AnglefrontLeft = hydraulicunit.analogRead(0) AngleBackRight = hydraulicunit.analogRead(1) AnglefrontRight = hydraulicunit.analogRead(2) AngleBackRight = hydraulicunit.analogRead(3) #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #Front head control sensor function Sensing1 = hydraulicunit.analogRead(4) #Front body Sensing2 = hydraulicunit.analogRead(5) #Back body Sensing3 = hydraulicunit.analogRead(6) # tail for the movment actiion Sensing4 = hydraulicunit.analogRead(7) #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #Gyroscope sensor bus = smbus.SMBus(1) # bus = smbus.SMBus(0) fuer Revision 1
) != Target: # Compare the data upto the dataget function #Backward part motorunit.analogWrite(6, 0) motorunit.analogWrite(10, 0) motorunit.analogWrite(4, 0) motorunit.analogWrite(3, 0) motorunit.analogWrite(9, SpeedStart) motorunit.analogWrite(11, SpeedStart) motorunit.analogWrite(2, SpeedStart) motorunit.analogWrite(5, SpeedStart) time.sleep(timechange) motorunit.analogWrite(6, 0) motorunit.analogWrite(10, 0) motorunit.analogWrite(4, 0) motorunit.analogWrite(3, 0) motorunit.analogWrite(9, SpeedEnd) motorunit.analogWrite(11, SpeedEnd) motorunit.analogWrite(2, SpeedEnd) motorunit.analogWrite(5, SpeedEnd) while True: sensor1 = motorunit.analogRead(0) #Sensor 1 functioning for the Back sensor2 = motorunit.analogRead(1) #Sensor 2 functioning for the front print("Back sensor detection:") print(sensor1) print("Front sensor distance :") print(sensor2) Foward_active(sensor1, sensor2, sensor3, 150, 130, 0.05, 4) # Target sensor input
from nanpy import (ArduinoApi, SerialManager) from time import sleep import threading batteryPin = 'A5' #connection = SerialManager('COM5') connection = SerialManager('/dev/ttyACM0') a = ArduinoApi(connection=connection) eps = 0.0048828125 #Setup a.pinMode(batteryPin, a.INPUT) #Loop batteryLevel = a.analogRead(batteryPin) converted = (batteryLevel * 12) / 5 if converted > 13: print('100') elif converted >= 12.75 and converted < 13: print('90') elif converted >= 12.50 and converted < 12.75: print('80') elif converted >= 12.30 and converted < 12.50: print('70') elif converted >= 12.15 and converted < 12.30: print('60') elif converted >= 12.05 and converted < 12.15: print('50') elif converted >= 11.95 and converted < 12.05:
camera = picamera.PiCamera() val = 0; sensor = 0 try: connection = SerialManager() a = ArduinoApi(connection = connection) except: print("failed to connect") a.pinMode(sensor, a.INPUT) while True: val = a.analogRead(sensor) print(val) sleep(0.1) if val > 200: camera.capture('image.jpg') sleep(0.1) SendSpMail('image.jpg')
# -*- coding: utf-8 -*- # Lecture d'une tension sur l'entréé analogique A0 from nanpy import ArduinoApi # Gestion Arduino from nanpy import SerialManager # Gestion port série from time import sleep # Importation de sleep(seconde) port = SerialManager(device='/dev/ttyACM0' ) # Sélection du port série (exemple : device = 'COM6') uno = ArduinoApi(connection=port) # Déclaration de la carte Arduino for i in range(10): N = uno.analogRead(0) # Lecture la valeur numérique de la tension sur A0 print("N = ", N) # Affichage U = N * 5 / 1023 # Calcul de la tension en volt print("U = ", round(U, 2), " V") # Affichage sleep(1) # Temporisation d'une seconde port.close() # Fermeture du port série
from nanpy import (ArduinoApi, SerialManager) from time import sleep import time lightPin = 'A0' connection = SerialManager('/dev/ttyACM0') #connection = SerialManager('COM5') a = ArduinoApi(connection = connection) #Setup a.pinMode(lightPin, a.INPUT) #Loop while True: print(a.analogRead(lightPin)) time.sleep(1)
#Conversion information from Arduino documentations #Resistor calculations: http://www.mouser.com/catalog/specsheets/Seeed_101020022.pdf from nanpy import (ArduinoApi, SerialManager) from time import sleep #Connect to Arduino. Automatically finds serial port. connection = SerialManager() a = ArduinoApi(connection=connection) sensor = 14 #Analog pin 0 a.pinMode(sensor, a.INPUT) #Setup sensor print("Sensor resistance is: ") while True: brightness = a.analogRead(sensor) #Get reading resistance = (1023 - brightness) * 10 / brightness #Resistance of sensor print(resistance) time.sleep(5)
pixels.fill((255 - (k), 0, 0)) pixels.show() connection = SerialManager(device='/dev/ttyACM0') a = ArduinoApi(connection=connection) a.pinMode(temp1Pin, a.INPUT) try: #GPS thread agps_thread = AGPS3mechanism() agps_thread.stream_data() agps_thread.run_thread() while True: value1 = a.analogRead(temp1Pin) value1 *= tempMult value2 = a.analogRead(temp2Pin) value2 *= tempMult avg_temp = (value1 + value2) / 2 #avg_temp -= 30 #GPS-Sample --->Remove it out later print("Sample Latitude try ", agps_thread.data_stream.lat) print(" and long ", agps_thread.data_stream.lon) print("Temperature: " + str(avg_temp) + "*C") flexADC = a.analogRead(flexPin) flexV = flexADC * VCC / 1023.0 prevFlexR = flexR flexR = R_DIV * (VCC / flexV - 1.0) print("flex:") print(flexR)
Y = Scale(Master,from_=0,to=500, orient=HORIZONTAL,command=Kinematicbase) Y.set(0) Y.pack() Z = Scale(Master,from_=0,to=500, orient=HORIZONTAL,command=) Z.set(0) Z.pack() button1 = Button(Master,text = "Control1",fg = 'blue',command=RunServo,activebackground = 'red') button1.pack() button2 = Button(Master,text = "Control2",fg = 'blue',command=RunServo1,activebackground = 'green') button2.pack() button3 = Button(Master,text = "Control3",fg = 'blue',command=RunServo2,activebackground = 'pink') button3.pack() button4 = Button(Master,text = "Control4",fg = 'blue',command=RunServo3,activebackground = 'blue') button4.pack() button5 = Button(Master,text = "Control5",fg = 'blue',command=RunServo4,activebackground = 'brown') button5.pack() button6 = Button(Master,text = "Control6",fg = 'blue',command=RunServo5,activebackground = 'black') button6.pack() mainloop() while(True): # Angle Analoginput and show the value of the angle AngleBase = (a.analogRead(0))*0.175953079 # Angle transformation conversion AngleShoulder = (a.analogRead(1))*0.175953079 AngleElbow = (a.analogRead(2))*0.175953079 AngleWristRot = (a.analogRead(3))*0.175953079 AngleWrist = (a.analogRead(4))*0.175953079 AngleGripper = (a.analogRead(5))*0.175953079 print(AngleBase,AngleShoulder,AngleElbow,AngleWristRot,AngleWrist,AngleGripper)
# -*- coding: utf-8 -*- # Mesure de la resistance d'une CTN et calcul de la température # Calcul de la température à partir de la relation de Steinhart-Hart from nanpy import ArduinoApi # Gestion de l'Arduino from nanpy import SerialManager # Gestion port série from time import sleep # Importation de sleep(seconde) from math import log Vcc = 5.0 # Tension d'alimentation Ro = 10000 # Résistance du pont A = 1.0832e-3 # Coeff. de Steinhart-Hart B = 2.1723e-4 # ... C = 3.2770e-7 # ... port = SerialManager(device='/dev/ttyACM0' ) # Sélection du port série (exemple : device = 'COM6') uno = ArduinoApi(connection=port) # Déclaration de la carte Arduino while True: U = uno.analogRead(0) * 5 / 1023 # Lecture la tension sur A0 R = Ro * U / (Vcc - U) # Calcul de la résistance T = (1.0 / (A + B * log(R) + C * log(R)**3)) T = T - 273.15 # Calcul de la température print("R = ", R, "T = ", T) # Affichage sleep(1) # Temporisation d'une seconde port.close() # Fermeture du port série
#Connect to Arduino. Automatically finds serial port. connection = SerialManager() a = ArduinoApi(connection=connection) sensor = 14 #A0 on shield B = 3975 #B value of the thermistor (Grove Starter Kit information) a.pinMode(sensor, a.INPUT) #Setup sensor while True: total = 0 #Each set of readings start with a total of 0 #Get all the readings: for i in range(0, 24): reading = a.analogRead(sensor) #Get reading resistance = ((1023 - reading) * 10000 / reading) #Find resistance log = math.log10(resistance / 10000) temp = (1 / (log / B + 1 / 298.15) - 273.15) #Find temperature readings[i] = temp #Place temp reading in i space of array sleep(0.1) #Time between readings #Add the readings: for i in range(0, 24): total += readings[i] #Find the average and print: average = total / 24 print("The average temp is ") print(average)
import serial from nanpy import (ArduinoApi, SerialManager) import time import board import neopixel from time import sleep import RPi.GPIO as GPIO import os import time import gpiozero from gpiozero import Button temp1Pin = 14 temp2Pin = 15 tempMult = .48828125 connection = SerialManager(device='/dev/ttyACM0') a = ArduinoApi(connection=connection) a.pinMode(temp1Pin, a.INPUT) while True: value1 = a.analogRead(temp1Pin) value1 *= tempMult value2 = a.analogRead(temp2Pin) value2 *= tempMult avg_temp = (value1 + value2) / 2 print("Temperature: " + str(avg_temp) + "*C") sleep(1)
readingsGND.append(0) print ("Our button State is: {}".format(readingVclamp[x])) except: print("Unable to clear sampling space") ''' try: while True: SumSqGND = 0 SumSqVClamp = 0 total = 0 totalI = 0 sleep(1) for i in range(300): #print (i) #if (a.analogRead(PinVClamp)>512) && (a.analogRead(PinVClamp)<516): readingsVClamp[i] = a.analogRead(PinVClamp) - a.analogRead( PinVirtGND) #readingsVClamp[i] = a.analogRead(PinVClamp) - 515 #print(i) #print(a.analogRead(PinVirtGND)) #print(a.analogRead(PinVClamp)) sleep(0.1) #Calculate Vrms for i in range(300): SumSqVClamp = SumSqVClamp + math.pow(readingsVClamp[i], 2) #print(SumSqVClamp) #print"%f" %(SumsqVclamp) #print"%f" %(numReadings) total = math.sqrt(SumSqVClamp / 300)
s.ehlo() s.starttls() s.ehlo() s.login(email, email_password) print(address_to_send) s.sendmail(email, address_to_send, msg.as_string()) s.quit() camera = picamera.PiCamera() val = 0 sensor = 0 try: connection = SerialManager() a = ArduinoApi(connection=connection) except: print("failed to connect") a.pinMode(sensor, a.INPUT) while True: val = a.analogRead(sensor) print(val) sleep(0.1) if val > 200: camera.capture('image.jpg') sleep(0.1) SendSpMail('image.jpg')