def colorWipePot(): """Wipe color across display a pixel at a time. color defined by analog read """ for i in range(strip.numPixels()): greenShade = int(analog.read(0) * 55) blueShade = int(analog.read(1) * 55) redShade = int(analog.read(2) * 55) strip.setPixelColor(i, Color(greenShade, blueShade, redShade)) strip.show()
def colorWipePot(): """Wipe color across display a pixel at a time. color defined by analog read """ for i in range(strip.numPixels()): greenShade = int(analog.read(0) * 55) blueShade = int(analog.read(1) * 55) redShade = int(analog.read(2) * 55) strip.setPixelColor(i, Color(greenShade, blueShade ,redShade)) strip.show()
def soil_moisture(): soil_data = open("moist_%d_%d_%d.txt" % (year, month, day), "ab") avg_moisture = (analog.read(0) + analog.read(1)) / 2 moisture = "%d %f %f %f" % (time.localtime()[3], avg_moisture, analog.read(0), analog.read(1)) soil_data.write(moisture) soil_data.write("\n") soil_data.close() os.system("scp %s %s@%s:~%s" % (soil_data.name, username, ip, directory)) return moisture
def handle(self, *args, **options): """ Log the temperature, light (normalised) and moisture (normalised) to the database. """ if not running_on_raspberry_pi: # Just put some dummy data in temperature = 10 moisture = 0.5 light_level = 1.0 else: light_sensor_max = 65535 light_sensor_min = 0 light_level = (light.light() - light_sensor_min) / ( light_sensor_max - light_sensor_min) moisture_sensor_max = 4.455 moisture_sensor_min = 0 moisture = (analog.read(0) - moisture_sensor_min) / ( moisture_sensor_max - moisture_sensor_min) temperature = self.get_calibrated_temperature() print(f"Light level: {light_level}") print(f"Temperature: {temperature}") print(f"Soil moisture: {moisture}") sensor_data = SensorData( temperature=temperature, moisture=moisture, light=light_level, ) sensor_data.save()
def main(): try: while True: heart = "{:.3f}".format(analog.read(0)) print(heart) sys.stdout.flush() time.sleep(.1) except Keyboard: close()
#!/usr/bin/python3 from envirophat import leds, motion, light, weather, analog import time import datetime leds.on() print('{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()), ",", light.light(), ",", light.rgb(), ",", weather.temperature(), ",", weather.pressure(unit='kPa'), ",", motion.heading(), ",", analog.read(0), ",", analog.read(1), ",", analog.read(2), ",", analog.read(3)) leds.off()
from envirophat import analog print(analog.read(2))
#Libray to post to CHoRDS import requests # EnviroPhat from envirophat import leds, motion, light, weather, analog ## Envirophat Units unit = 'Pa' # Pressure unit, can be either hPa (hectopascals) or Pa (pascals) ## Envirophat Analog TMP36 Pins cm0 = 0 cm5 = 1 cm10 = 2 ##Generate Ouput point0_C = (analog.read(cm0) - .5) * 100 point1_C = (analog.read(cm5) - .5) * 100 point2_C = (analog.read(cm10) - .5) * 100 #Libraries for the adafruit_si7021 import board import busio import adafruit_si7021 ## Relay Shield GPIO Pins import RPi.GPIO as GPIO # Relay Setup ## Relay shield GPIO.setmode(GPIO.BCM) ## pins
def readADC(channel): voltage = analog.read(channel) print "voltage value = ", voltage return float(voltage)
tx_data('green', g) tx_data('blue', b) if lsm303d_enabled: # Motion x, y, z = motion.accelerometer() tx_data('motion_x', x) tx_data('motion_y', y) tx_data('motion_z', z) # Heading h = motion.heading() tx_data('heading', h) if ads1015_enabled: # Analog 0 a0 = round(analog.read(0), 2) tx_data('analog_0', a0) # Analog 1 a1 = round(analog.read(0), 2) tx_data('analog_1', a1) # Analog 2 a2 = round(analog.read(0), 2) tx_data('analog_2', a2) # Analog 3 a3 = round(analog.read(0), 2) tx_data('analog_3', a3)
# https://learn.pimoroni.com/tutorial/sandyj/getting-started-with-enviro-phat import time import envirophat from envirophat import analog, leds analog.read(2) out = open('enviro.log', 'w') out.write('reading\n') try: while True: leds.on() analogRead = analog.read(2) out.write('%f\n' % (analogRead)) time.sleep(1) except KeyboardInterrupt: leds.off() out.close()
## pins #relay1=20 #relay2=19 ## Mode #GPIO.setup(relay1, GPIO.OUT) #GPIO.setup(relay2, GPIO.OUT) ## Envirophat Units unit = 'hPa' # Pressure unit, can be either hPa (hectopascals) or Pa (pascals) ## Envirophat Analoge TMP36 Pins cm0=0 cm5=1 cm10=2 ##To Turn on Relays ## GPIO.output(relay1, GPIO.HIGH) ## GPIO.output(relay2, GPIO.HIGH) ##Generate Ouput point0_C=(analog.read(cm0)-.5)*100 point1_C=(analog.read(cm5)-.5)*100 point2_C=(analog.read(cm10)-.5)*100 print ('{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.utcnow()),",",sensor.relative_humidity,",",sensor.temperature,",",light.light(),",",weather.temperature(),",",weather.pressure(unit=unit),",",point0_C,",",point1_C,",",point2_C,",",analog.read(3))
#!/usr/bin/env python import sys import time import requests from datetime import datetime from envirophat import light, weather, motion, analog print(analog.read(0)) print(analog.read(1))
def start_continous_scan(self): sensor_0_level = SignalLevel.UNKNOWN sensor_1_level = SignalLevel.UNKNOWN rev_counter = RevolutionCounter() while True: if (not getattr(self.worker, "do_run", True)): break self.reading_counter = self.reading_counter + 1 sensor_0_val = analog.read(0) sensor_1_val = analog.read(1) #print ('sensor_0_val', sensor_0_val, 'sensor_1_val', sensor_1_val) if self.logger != None: self.logger.get_hall_signal_0_logger().log_raw_signal_lst( [sensor_0_val]) self.logger.get_hall_signal_1_logger().log_raw_signal_lst( [sensor_1_val]) if self.sensor_0_buffer != None: self.sensor_0_buffer.append(sensor_0_val) if self.sensor_1_buffer != None: self.sensor_1_buffer.append(sensor_1_val) if self.logger: self.logger.log_hall_reading(time.time(), sensor_0_val, sensor_1_val, self.reading_counter) if self.logger: if ((time.time() - self.last_heading_sample_time) > self.sec_between_heading_loggings ) and self.heading_samples_counter > 0: self.logger.log_heading_event( start_time=time.time(), heading=(self.accumelated_heading_sum / self.heading_samples_counter)) self.last_heading_sample_time = time.time() self.heading_samples_counter = 0 self.accumelated_heading_sum = 0 else: self.heading_samples_counter += 1 self.accumelated_heading_sum += motion.heading() sensor_0_level = self.compute_signal_level( sensor_0_level, sensor_0_val, self.sensor_0_bottom_threshold, self.sensor_0_top_threshold) sensor_1_level = self.compute_signal_level( sensor_1_level, sensor_1_val, self.sensor_1_bottom_threshold, self.sensor_1_top_threshold) print('sensor_1_level', sensor_1_level, 'sensor_1_val', sensor_1_val, self.sensor_1_bottom_threshold, self.sensor_1_top_threshold) rev_counter_res = rev_counter.add_reading(sensor_0_level, sensor_1_level) forward_counter = rev_counter_res['forward_revolutions_counter'] backward_counter = rev_counter_res['backward_revolutions_counter'] # ('forward_counter', forward_counter, 'backward_counter', backward_counter) src.utils.monitor.show_counter_0(backward_counter) src.utils.monitor.show_counter_1(forward_counter) if (rev_counter_res['completed_forward_revolution'] or rev_counter_res['completed_backward_revolution']): if self.logger: self.logger.log_turn_event( time.time(), forward_counter, backward_counter, rev_counter_res['completed_forward_revolution'])
#!/usr/bin/python3 from envirophat import analog from time import sleep while True: pulse = analog.read(0) print("Pulse Voltage = {0}".format(pulse)) sleep(0.25)
print ("Starting collection #",i+1,"Temperature from pHat = ", weather.temperature()) time.sleep (.5) elif (s == 'p'): for i in range(r): leds.on() print("Starting collection #",i+1,"Pressure from pHat = ", weather.pressure(unit='kPa')) time.sleep (.5) elif (s == 'c'): for i in range(r): leds.on() print("Starting collection #",i+1,"Compass heading = ",motion.heading()) time.sleep (.5) elif (s == '0'): for i in range(r): leds.on() print ("Starting collection #",i+1,"Analog sensor 0= ",analog.read(0)) time.sleep (.5) elif (s == '1'): for i in range(r): leds.on() print ("Starting collection #",i+1,"Analog sensor 1= ",analog.read(1)) time.sleep (.5) elif (s == '2'): for i in range(r): leds.on() print ("Starting collection #",i+1,"Analog sensor 2= ",analog.read(2)) time.sleep (.5) elif (s == '3'): for i in range(r): leds.on() print ("Starting collection #",i+1,"Analog sensor 3= ",analog.read(3))
con = lite.connect('assets/db/enviro.db') try: while True: timestamp = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S") lux = light.light() leds.on() rgb = str(light.rgb())[1:-1].replace(' ', '') leds.off() acc = str(motion.accelerometer())[1:-1].replace(' ', '') heading = motion.heading() temp = (weather.temperature() - 10) press = weather.pressure() altitude = weather.altitude() moisture = analog.read(0) writeout = ( (timestamp, lux, rgb, acc, heading, temp, press, altitude, moisture), ) with con: cur = con.cursor() cur.execute("CREATE TABLE IF NOT EXISTS " + plant_type + " (Date DATETIME, Brightness INT, LightColor TEXT, Motion FLOAT, Heading INT, Temperature FLOAT, Pressure FLOAT, Altitude INT, Moisture FLOAT)") cur.executemany("INSERT INTO " + plant_type + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)", writeout) time.sleep(interval) finally: leds.off()
def read_analog(inp): if inp == 4: return analog.read_all() else: return analog.read(inp)
T = 1.0 stateChanged = 0 sampleCounter = 0 lastBeatTime = 0 firstBeat = True secondBeat = False Pulse = False IBI = 600 rate = [0] * 10 amp = 100 lastTime = int(time.time() * 1000) while True: # read from the ADC Signal = analog.read(0) curTime = int(time.time() * 1000) sampleCounter += curTime - lastTime lastTime = curTime N = sampleCounter - lastBeatTime # monitor the time since the last beat to avoid noise ## find the peak and trough of the pulse wave if Signal < thresh and N > ( IBI / 5.0) * 3.0: # avoid dichrotic noise by waiting 3/5 of last IBI if Signal < T: # T is the trough T = Signal # keep track of lowest point in pulse wave smallHeart(0.25) # measured a trough so show small heart if Signal > thresh and Signal > P: # thresh condition helps avoid noise P = Signal # P is the peak - keep track of highest point in pulse wave largeHeart(0.25) # measured a peak so show a large heart
import RPi.GPIO as GPIO from envirophat import analog from envirophat import light from envirophat import weather import time GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) GPIO.output(17, GPIO.HIGH) time.sleep(5) print(analog.read(0)) print(light.light()) print(weather.temperature()) print(weather.pressure()) GPIO.output(17, GPIO.LOW)
#!/usr/bin/python3 from envirophat import leds, motion, light, weather, analog import time leds.on() print("Starting collection") print("Light sensor = ", light.light()) print("RGB Ligt Sensor = ", light.rgb()) print("Temperature from pHat = ", weather.temperature()) print("Pressure from pHat = ", weather.pressure(unit='kPa')) print("Compass heading = ", motion.heading()) print("Analog sensor 0= ", analog.read(0)) print("Analog sensor 1= ", analog.read(1)) print("Analog sensor 2= ", analog.read(2)) print("Analog sensor 3= ", analog.read(3)) leds.off() input("Press Enter to continue ....")
return temp_c conn = sqlite3.connect('server.db') c = conn.cursor() GPIO.setmode(GPIO.BCM) GPIO.setup(22, GPIO.OUT) GPIO.output(22, GPIO.HIGH) try: lux = light.light() rgb = str(light.rgb())[1:-1].replace(' ', '') temp = int(weather.temperature()) press = int(weather.pressure()) water1 = analog.read(0) waterTemp = read_temp() if water1 < 0.5: r = requests.get('http://127.0.0.1:5000/relay/1/0') else: r = requests.get('http://127.0.0.1:5000/relay/1/1') datavals = [('light', lux), ('rgb', rgb), ('temp', temp), ('press', press), ('water1', water1), ('watertemp', waterTemp)] c.executemany('INSERT INTO sensor_log (sensor, value) VALUES (?, ?)', datavals) conn.commit() conn.close() GPIO.cleanup()
scanner = BeaconScanner(beaconMsg, packet_filter=[EddystoneUIDFrame]) # INITIALISATION DONE try: scanner.start() sio.connect('https://frequency-station-server.herokuapp.com/') print('started server') while True: (heading, minutes) = compass.getHeading() data = { "bt_addr": currentBeacon.bt_addr, "rssi": currentBeacon.rssi, # "packet": packet, # "additional_info": additional_info, "knobs": { "heading": heading, "balance": round(analog.read(0) / 5, 2), "variance": round(analog.read(1) / 5, 2), "frequency": round(analog.read(2) / 5, 2) } } print("data: ", data) time.sleep(.2) my_message(data) except KeyboardInterrupt: scanner.stop() disconnect() leds.off()