def main(): global isConnected # Create an MQTT client for connecting to AWS IoT via MQTT. client = mqtt.Client(deviceName + "_sr") # Client ID must be unique because AWS will disconnect any duplicates. client.on_connect = on_connect # When connected, call on_connect. client.on_message = on_message # When message received, call on_message. client.on_log = on_log # When logging debug messages, call on_log. # Set the certificates and private key for connecting to AWS IoT. TLS 1.2 is mandatory for AWS IoT and is supported # only in Python 3.4 and later, compiled with OpenSSL 1.0.1 and later. client.tls_set(awsCert, deviceCertificate, devicePrivateKey, ssl.CERT_REQUIRED, ssl.PROTOCOL_TLSv1_2) # Connect to AWS IoT server. Use AWS command line "aws iot describe-endpoint" to get the address. print("Connecting to AWS IoT...") client.connect("A1P01IYM2DOZA0.iot.us-west-2.amazonaws.com", 8883, 60) # Start a background thread to process the MQTT network commands concurrently, including auto-reconnection. client.loop_start() # Configure the Grove LED port for output. grovepi.pinMode(led, "OUTPUT") time.sleep(1) # Loop forever. while True: try: # If we are not connected yet to AWS IoT, wait 1 second and try again. if not isConnected: time.sleep(1) continue # Read Grove sensor values. Prepare our sensor data in JSON format. payload = { "state": { "reported": { # Uncomment the next line if you're using the Grove Analog Temperature Sensor. # "temperature": round(grovepi.temp(temp_sensor, '1.1'), 1), # Comment out the next 2 lines if you're using the Grove Analog Temperature Sensor. "temperature": grovepi.dht(dht_sensor, 0)[0], # The first 0 means that the DHT module is DHT11. "humidity": grovepi.dht(dht_sensor, 0)[1], "light_level": grovepi.analogRead(light_sensor), "sound_level": grovepi.analogRead(sound_sensor), "timestamp": datetime.datetime.now().isoformat() } } } print("Sending sensor data to AWS IoT...\n" + json.dumps(payload, indent=4, separators=(',', ': '))) # Publish our sensor data to AWS IoT via the MQTT topic, also known as updating our "Thing Shadow". client.publish("$aws/things/" + deviceName + "/shadow/update", json.dumps(payload)) print("Sent to AWS IoT") # Wait 30 seconds before sending the next set of sensor data. time.sleep(30) except KeyboardInterrupt: break except IOError: print("Error")
def _poll(self): device = self.sensor.device pin = self.sensor.pin value = None grovepilib.pinMode(pin,"INPUT") if device == 'GroveButton': value = grovepilib.digitalRead(pin) elif device == 'GroveLight': raw = grovepilib.analogRead(pin) if raw == 0: value = 0 else: coefficient = ((1023.0-raw) * 10.0/raw) * 15.0 exponent = 4.0/3.0 value = 10000.0/pow(coefficient, exponent) elif device == 'GroveRotaryAngle': adc_ref = 5 full_angle = 300 grove_vcc = 5 sensor_value = grovepilib.analogRead(pin) voltage = round((float)(sensor_value) * adc_ref / 1023, 2) degrees = round((voltage * full_angle) / grove_vcc, 2) value = degrees elif device == 'GroveSound': value = grovepilib.analogRead(pin) elif device == 'GroveTemperature': value = grovepilib.temp(pin,'1.1') elif device == 'GroveTouch': value = grovepilib.digitalRead(pin) return SensorReading(self.sensor, value)
def calibrate(self): analogValue = grovepi.analogRead(self.pin) for x in range(1,self.calibrationSampleSize): print analogValue analogValue += grovepi.analogRead(self.pin) analogValue /= self.calibrationSampleSize sensorVoltage = (analogValue * 1.0) / 1024.0 * 5.0 RS = (5.0 - sensorVoltage) / sensorVoltage self.R0 = RS / 9.8
def get_sound(port, settings): try: if settings['sound_mode'] == 'raw_volume': if settings['units'] == 'voltage': return (grovepi.analogRead(port)/1024) * 5 elif settings['units'] == 'analog': return grovepi.analogRead(port) except ValueError: return "Not found"
def menu(): while grovepi.digitalRead(button) == True: pass if alm["set"] == "": set_alarm_time() else: items = float(len(menu_items)) val = int(grovepi.analogRead(rotary) / (1023 / items)) old_val = val lcd.text("Select option:\n" + menu_items[val]) while True: lcd.text try: val = int(grovepi.analogRead(rotary) / (1023 / items)) if val == items: val = items - 1 if val <> old_val: lcd.text("Select option:\n" + menu_items[val]) old_val = val if grovepi.digitalRead(button) == True: break except IOError: pass if val == 0: lcd.text("Alarm set for:\n%02d:%02d" % (alm["hour"], alm["minute"])) sleep(2) lcd.text("") elif val == 1: set_alarm_time() elif val == 2: alm["set"] = "" lcd.text("Alarm cancelled.") sleep(2) lcd.text("") else: lcd.text("") #Ensure button has been released: while True: try: if grovepi.digitalRead(button) == False: break except IOError: pass
def read_sensor(): try: moisture=grovepi.analogRead(mositure_sensor) light=grovepi.analogRead(light_sensor) [temp,humidity] = grovepi.dht(temp_himidity_sensor,white) #Return -1 in case of bad temp/humidity sensor reading if math.isnan(temp) or math.isnan(humidity): #temp/humidity sensor sometimes gives nan return [-1,-1,-1,-1] return [moisture,light,temp,humidity] #Return -1 in case of sensor error except IOError as TypeError: return [-1,-1,-1,-1]
def get_rotary_angle_sensor(port, settings): try: if settings['angle_mode'] == 'raw_angle': if settings['units'] == 'analog': return grovepi.analogRead(port) elif settings['units'] == 'degrees': sensor_value = grovepi.analogRead(port) voltage = round((float)(sensor_value)*5/1023, 2) degrees = round((voltage*300)/5, 2) # 300 is the full value of the rotary angle return degrees except ValueError: return "Not found"
def readData(): try: json_obj = json.dumps({ 'temp' : grovepi.dht(DHT_pin,1)[0], 'hum' : grovepi.dht(DHT_pin,1)[1], 'lum' : grovepi.analogRead(0), 'dist' : grovepi.ultrasonicRead(US_pin), 'pot' : grovepi.analogRead(1), 'pir' : grovepi.digitalRead(PIR_pin) }) return json_obj except IOError: print "Erreur d'entrée/sortie"
def readSensors(self): try: while True: [ temperature, humidity ] = dht(constants.TEMP_HUMIDITY_PIN,0) moisture = grovepi.analogRead(constants.MOISTURE_PIN) light = grovepi.analogRead(constants.LIGHT_PIN) if temperature < 200 and temperature >= 0 and humidity >=0 and humidity <= 100 and moisture >= 0 and moisture <= 700 and light >= 0 and light <= 700: self.temperature = temperature self.humidity = humidity self.moisture = moisture self.light = light break except Exception as e: self.readSensors() #keep trying until it works
def getRoomTemperature(self): # ratio for translating from 3.3V to 5.0V (what we read is in the range of 0 -> 3.3V) voltage_ratio = 5.0 / 3.3 # and multiply what we read by that ratio # and read it for about 12 times -> this way we get smoother readings # the reason we average it is because the table we provided isn't big enough # and as a consequence you'd get values like (20 degrees, 24 degrees and so on) analog_sum = 0 for step in range(12): analog_sum += grovepi.analogRead(self.temperature_pin) pass analog_value = (analog_sum / 12) * voltage_ratio # see the datasheet for more information try: calculated_resistance = (1023 - analog_value) * 10000 / analog_value calculated_temperature = 1 / (math.log(calculated_resistance / 10000) / 3975 + 1 / 298.15) - 273.15 # if the values exceed a certain threshold # then raise a ValueError exception if not (calculated_temperature >= -50.0 and calculated_temperature <= 145.0): raise ValueError('temperature out of range') # and return what we got calculated return calculated_temperature except ZeroDivisionError: return 0
def run_light_sensor(): light_sense = grovepi.analogRead(light_sensor) resistance = (float)(1023 - light_sense) * 10 / light_sense if resistance > threshold: print("arrrgh light") #print "sensor_value = ", light_sense, " resistance = ", resistance return light_sense, resistance
def analog_max(it, a, wait): # read it values of data from analog pin a and maximise # wait is number of seconds between reads # returns negative number if error # this is slow, it must take a long time to interface between the GrovePi and Rpi i=0 ierr=0 amax=0 #print "analog_max it, a, wait ", it, a, wait while i<it and ierr<it: try: # Get sensor value from analog sensor # time.sleep(wait) raw = grovepi.analogRead(a) i=i+1 if raw > amax: amax=raw # time.sleep(wait) # print "max i ierr ", amax, i, ierr except IOError: ierr=ierr+1 # print "IOError analog max", ierr # end try # end while if i>0: #print "result amax i ierr", amax, i, ierr return(amax); else: return(-ierr)
def analog_ave(it, a, wait): # read it values of data from analog pin a and average # wait is number of seconds between reads # returns negative number if error i=0 ierr=0 s=0. tcall=0. # print "raw_aiir_ave it, a, wait ", it, a, wait while i<it and ierr<it: try: # Get sensor value from gas sensor time.sleep(wait) t0=time.time() raw = grovepi.analogRead(a) dt=time.time() - t0 tcall=tcall+dt s=s + raw i=i+1 # print "sum i ierr ", s, i, ierr except IOError: ierr=ierr+1 # print "IOError analog ave", ierr # end try # end while if i>0: ave=s/i tcall=tcall/i # print "analog read time: ", tcall # print "result s i", ave, s, i return(ave); else: return(-ierr)
def init(): global int_lastSound global float_tempOutMax global float_tempInMin global float_tempOutMax global float_tempOutMin global int_currentHour try: [temp,humidity] = grovepi.dht(temperatureSensorIn,0) float_tempOutMax = temp float_tempInMin = temp [temp,humidity] = grovepi.dht(temperatureSensorOut,1) float_tempOutMax = temp float_tempOutMin = temp int_lastSound = grovepi.analogRead(soundSensor) int_currentHour = datetime.datetime.now().hour except: error(" init") init()
def get_light_level(): #Light sensor reading try: level = int(grovepi.analogRead(light_sensor) / 15) + 3 lcd.rgb(level, level, level) except IOError: pass
def read_slider_value(slider, old_value): try: # try to normalize to 0 - 100 slider_value = (int)(grovepi.analogRead(slider) / 10.23) # print("slider value: ", slider_value) except IOError: print("IOError communicating with HW - can and will continue though.") slider_value=old_value return(slider_value)
def read(self): if(not self.validPin): self.logError('No valid pin provided') return '0' try: analogValue = grovepi.analogRead(self.pin) return str(analogValue) except (IOError, TypeError) as e: self.logError('Could not read value from sensor') return '0'
def get_data(): """ Read sensor data right from grovepi. Don't call in more than one thread. """ loopstate = get_loopstate() loudness = grovepi.analogRead(LOUDNESS_SENSOR) [temp, hum] = grovepi.dht(TEMP_HUM_SENSOR, module_type=0) return [loopstate, loudness, temp, hum]
def sensorCheck(dht_pin, light_sensor_pin, DHTtype): try: light_value = grovepi.analogRead(light_sensor_pin) except IOError: return "error" try: [temp,humidity] = grovepi.dht(dht_pin,DHTtype) except IOError: return "error" result = "%s temp = %.1f , humidity = %.1f , light = %d" % (datetime.now().strftime("%H:%M:%S "), temp, humidity, light_value) return result
def read(self): if(not self.validPin): self.logError('No valid pin provided') return '0' try: analogValue = grovepi.analogRead(self.pin) density = (analogValue * 1.0) / 1024.0 return "%.4f" % density or "0" except (IOError, TypeError) as e: self.logError('Could not read value from sensor') return '0'
def read(self): if(not self.validPin): self.logError('No valid pin provided') return 0 try: analogValue = grovepi.analogRead(self.pin) temperature = (5.0 * analogValue * 100.0) / 1024 return temperature except (IOError, TypeError) as e: self.logError('Could not read value from sensor') return 0
def read_sensor(): try: light = grovepi.analogRead(light_sensor) distance = grovepi.ultrasonicRead(ultrasonic_ranger) [temp, humidity] = grovepi.dht(temp_humidity_sensor, blue) #Return -1 in case of bad temp/humidity sensor reading if math.isnan(temp) or math.isnan(humidity): return [-1, -1, -1, -1] return [light, distance, temp, humidity] except IOError as TypeError: return [-1, -1, -1, -1]
def _readPin(self,pinValue): voltage = None errorCpt = 0 while( (errorCpt<10) and (voltage is None) ): try: voltage = grovepi.analogRead(pinValue) if self._DEBUG: print "readPin, voltage =" + str(voltage) except IOError: errorCpt+=1 if self._DEBUG: print "readPin, errorCpt =" + str(errorCpt) return voltage
def main(): # ply = Plotly_writer() # ply.open_stream() mac_address = get_mac('wlan0') co2_value = grove_co2_lib.CO2() # インスタンス作成時に protocol v3.1.1 を指定します client = mqtt.Client(client_id="hoge", protocol=mqtt.MQTTv311) client.connect(mqtt_host, port=mqtt_port, keepalive=60) client.loop_start() print("starting post to the api...") while True: print("fetching data from sensor...") # 各種センサー情報の取得 loudness = grovepi.analogRead(LOUDNESS_PORT) light = grovepi.analogRead(LIGHT_PORT) air_cleanness = grovepi.analogRead(AIR_PORT) (temp, humid) = grovepi.dht(TEMP_HUMID_PORT, 0) (ppm, temp_from_co2) = co2_value.read() now_time = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') client.publish(mqtt_topic, mqtt_message) sleep(10) person_data = read_data() print(person_data) # ply.write_stream(x=now_time, loudness=loudness, light=light) req = RequestToApi('https://anaba-works.herokuapp.com/api/environments/', time=now_time, place=mac_address, loudness=loudness, light=light, air_cleanness=air_cleanness, temp=temp, humid=humid, co2_ppm=ppm, no_of_person=person_data) req.execute_request() sleep(300)
def getLightSensorResistance(): sensor_value = grovepi.analogRead(light_sensor_port) if (not math.isnan(sensor_value)): if (sensor_value == 0): sensor_value = 1 # Calculate resistance of sensor in K resistance = (float)(1023 - sensor_value) * 10 / sensor_value return(resistance) else: print "ERROR: grovepi.analogRead(", light_sensor_port, "): ", sensor_value return("ERROR")
def read_sensor(readouts,sensor,interval): import time from time import gmtime, strftime import grovepi while readouts > 0: try: print("{}, {}".format(strftime("%d-%m-%Y, %H:%M:%S", gmtime()), grovepi.analogRead(sensor))) time.sleep(interval) readouts=readouts-1 except KeyboardInterrupt: break except IOError: print ("Error")
def handlerequests(req): if req.operation==0: pin = req.pin.split("Pin")[1] grovepi.pinMode(int(pin), "INPUT") try: sensorval = grovepi.digitalRead(int(pin)) except: sensorval =0 msgtx = Python2Sharp(msg.isRequest, msg.watcherid, msg.syncid, str(sensorval), msg.operation) sys.stdout.write(json.dumps(msgtx.__dict__)+"\n") elif req.operation == 1: pin = req.pin.split("Pin")[1] grovepi.pinMode(int(pin), "OUTPUT") try: grovepi.digitalWrite(int(pin), int(req.payload)) except: grovepi.digitalWrite(int(pin), int(req.payload)) elif req.operation == 2: pin = req.pin.split("Pin")[1] grovepi.pinMode(int(pin), "INPUT") try: sensorval = grovepi.analogRead(int(pin)) except: sensorval = 0 msgtx = Python2Sharp(msg.isRequest, msg.watcherid, msg.syncid, str(sensorval), msg.operation) sys.stdout.write(json.dumps(msgtx.__dict__)+"\n") elif req.operation ==4: pin = req.pin.split("Pin")[1] try: [temp,humidity] = grovepi.dht(int(pin),1) except: temp=0 humidity =0 a= json.dumps({'temp':temp,'humidity':humidity}) msgtx = Python2Sharp(msg.isRequest,msg.watcherid,msg.syncid,a,msg.operation) sys.stdout.write(json.dumps(msgtx.__dict__)+"\n") elif req.operation == 5: pin = req.pin.split("Pin")[1] try: sensorval=grovepi.ultrasonicRead(int(pin)) except: sensorval=0 msgtx = Python2Sharp(msg.isRequest, msg.watcherid, msg.syncid, str(sensorval), msg.operation) sys.stdout.write(json.dumps(msgtx.__dict__)+"\n") elif req.operation == 6: try: setRGB(0,128,64) setText(req.payload) except: pass
def read_sensor(): try: # pressure=pressure = bmp.readPressure()/100.0 light=grovepi.analogRead(light_sensor) [temp,humidity] = grovepi.dht(temp_humidity_sensor,therm_version) # Here we're using the thermometer version. #Return -1 in case of bad temp/humidity sensor reading if math.isnan(temp) or math.isnan(humidity): #temp/humidity sensor sometimes gives nan # return [-1,-1,-1,-1] return [-1,-1,-1] # return [pressure,light,temp,humidity] return [light,temp,humidity] #Return -1 in case of sensor error except (IOError,TypeError) as e: return [-1,-1,-1]
def update(self): try: brightness = grovepi.analogRead(pins_brightness) self.dataDict["p_brightness"] = brightness except: print "[logger] update: analogRead error" try: [temperature, humidity] = grovepi.dht(pins_dht, 1) self.dataDict["p_temperature"] = temperature self.dataDict["p_humidity"] = humidity except: print "[logger] update: dht error" try: pressure = self.bmp.readPressure() self.dataDict["p_pressure"] = pressure / 100.0 except: print "[logger] update: readPressure error" self.serial.flush() while True: gps = self.serial.readline() if gps[:6] == "$GPGGA": break; time.sleep(0.1) try: index = gps.index("$GPGGA", 5, len(gps)) gps = gps[index:] except: pass gga = gps.split(",") if len(gga) > 9: lat = gga[2] lat_ns = gga[3] lon = gga[4] lon_ew = gga[5] alt = gga[9] if lat.replace(".", "", 1).isdigit(): lat = self.decimal_degrees(float(lat)) if lat_ns == "S": lat = -lat self.dataDict["p_lat"] = lat if lon.replace(".", "", 1).isdigit(): lon = self.decimal_degrees(float(lon)) if lon_ew == "W": lon = -lon self.dataDict["p_lon"] = lon if alt.replace(".", "", 1).isdigit(): self.dataDict["p_alt"] = float(alt)
def sensor_read_sound(): retry = 3 while retry > 0: try: sensor_value = grovepi.analogRead(sound_sensor) time.sleep(.01) break except: print 'can not read sound sensor, retry again' retry = retry - 1 time.sleep(.1) if retry == 0: return -1 else: return sensor_value
temp = db.reference('temperature') hum = db.reference('humidity') son = db.reference('sound') #variables for the minmum and max temperature of the baby room, noise allows and counters before emailing the parent min = 24 max = 25 warning = 0 noiseallow = 260 # 260db for demostration but the noise should be considered 400db for a baby cry warningcry = 0 while True: [temperature, humidity] = grovepi.dht(temp_humidity_sensor, therm_version) sound = grovepi.analogRead(sound_sensor) print("Let's start with getting python to read from the sensor..") print("humidity is", humidity) print("temperature is", temperature) print("sound is", sound) # Condition which control the temperature min & max of the baby room if temperature > max: print "WARNING!" print "Baby's room temperature too hot." print "........................." warning = warning + 1 if temperature < min: print "WARNING!"
import time import grovepi # Connect the Sound Sensor to analog port A0 soundsensor = 0 # Connect the LED to digital port D5 #led = 5 #grovepi.pinMode(led,"OUTPUT") #time.sleep(1) #i = 0 while True: try: # Read volume from soundsensor i = grovepi.analogRead(soundsensor) print(i) # Send PWM signal to LED ## grovepi.analogWrite(led,i//4) except IOError: print("Error")
dist /= 5 #average on 5 polls print("Distance:" + str(dist)) #read humidity&temp sensor with lock: [temp, humidity] = grovepi.dht(DHT, 0) time.sleep(0.2) if math.isnan(temp) == False and math.isnan(humidity) == False: print("temp : %.02f C \nhumidity :%.02f%%" % (temp, humidity)) #read light sensor with lock: light_value = grovepi.analogRead(LIGHT) time.sleep(0.2) print("Light:" + str(light_value)) except IOError: print("Error") #send data to influxdb sendInflux.send('Temperature', temp) sendInflux.send('Humidity', humidity) sendInflux.send('Light', light_value) sendInflux.send('Distance', dist) #measures every 10 seconds time.sleep(10)
import time import grovepi # Connect the Grove Piezo Vibration Sensor to analog port A0 # OUT,NC,VCC,GND piezo = 0 grovepi.pinMode(piezo,"INPUT") while True: try: # When vibration is detected, the sensor outputs a logic high signal print grovepi.analogRead(piezo) time.sleep(.5) except IOError: print "Error"
temperature_sensor = 4 water_sensor = 3 light_sensor = SI1145.SI1145() while True: try: start = time.time() # get the timestamp for obervation timestamp = get_timestamp() # get temperature and humidity readings [temp, humidity] = grovepi.dht(temperature_sensor, 1) # get hcho gas reading and voltage hcho = grovepi.analogRead(hcho_sensor) voltage = float(hcho * 5 / 1024) # water status water_status = grovepi.pinMode(water_sensor, "INPUT") # light related visibility = light_sensor.readVisible() ir = light_sensor.readIR() uv = light_sensor.readUV() # parse the results together data = [timestamp, temp, humidity, hcho, voltage, water_status, visibility, ir, uv] # decide if humidity needs to increase
furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' import time import grovepi # Connect the Grove Loudness Sensor to analog port A0 # SIG,NC,VCC,GND loudness_sensor = 0 while True: try: # Read the sound level sensor_value = grovepi.analogRead(loudness_sensor) print(("sensor_value = %d" % sensor_value)) time.sleep(.5) except IOError: print("Error")
def get_light_sensor(port, settings): try: if settings['light_mode'] == 'raw_light': return grovepi.analogRead(port) except ValueError: return "Not found"
def getLuminosity(): return grovepi.analogRead(light_sensor)
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' # NOTE: The sensitivity can be adjusted by the onboard potentiometer import time import grovepi # Connect the Grove Piezo Vibration Sensor to analog port A0 # OUT,NC,VCC,GND piezo = 0 grovepi.pinMode(piezo,"INPUT") while True: try: # When vibration is detected, the sensor outputs a logic high signal print(grovepi.analogRead(piezo)) time.sleep(.5) except IOError: print ("Error")
import time import grovepi sensor = 0 i = 0 data = [] while i < 10: data[i] = grovepi.analogRead(sensor) print(grovepi.analogRead(sensor)) i += 1 time.sleep(.5) ave = sum(data) / len(data) print(ave)
# Sensor settings light = 1 # Light sensor is connected to Analog port A1 # Other global variables baseurl = "http://piland.socialdevices.io" baseurl = baseurl + "/" + str(room) + "/write/" + str( slot) + "?name=" + name + "&value=" while True: try: # Read the light level from the sensor light_level = grovepi.analogRead(light) url = baseurl + "%d" % light_level print url requests.get(url) # write data time.sleep(2.0) # 2 second delay except KeyboardInterrupt: print "Terminating" break except IOError: print "IOError" except:
else: # switch off grovepi.digitalWrite(relay, 0) switchOn = False # blue=0, white=1 [temp, humidity] = grovepi.dht(dht_sensor, 0) firstRow = "" secondRow = "" if math.isnan(temp) is False and math.isnan(humidity) is False: firstRow = "%dC %d%%" % (temp, humidity) # Get sensor values light_value = grovepi.analogRead(light_sensor) moist_value = grovepi.analogRead(moist_sensor) secondRow = "%d %d" % (light_value, moist_value) if x == 0: log(temp, humidity, moist_value, light_value, switchOn) uploadValues(temp, humidity, moist_value, light_value, switchOn) if x != 4: sleep(10.00) setRGB(32, 128, 32) setText(firstRow + "\n" + secondRow) except KeyboardInterrupt: grovepi.digitalWrite(relay, 0)
import time import grovepi import argparse ap = argparse.ArgumentParser() ap.add_argument("-p", "--pin", required=True, help="GrovePi Pin") args = vars(ap.parse_args()) pin = int(args['pin']) while True: try: value = grovepi.analogRead(pin) print("value = {}".format(value)) time.sleep(.5) except IOError: print ("Error")
f = open(file_name, "w") f.write( "Time,Temperature,Humidity,Quality Score,PM10 count,PM2.5 count,PM10 conc,PM2.5 conc,Lat,Long,Alt,Speed,Climb{}" .format("\n")) f.write( "------------------------------------------------------------------------------------------------------------\n" ) f.close() TurnOff = False while True: while (GPIO.input(22) == True): GPIO.output(10, 1) Time = time.strftime("%H:%M:%S %m/%d/%Y", time.localtime()) [Temperature, Humidity] = grovepi.dht(3, 1) QualityScore = grovepi.analogRead(air_sensor) PM = "" while (len(PM) < 2): PM = ser.readline() PM = PM.strip() Lat = gpsd.fix.latitude Long = gpsd.fix.longitude Alt = gpsd.fix.altitude Speed = gpsd.fix.speed Climb = gpsd.fix.climb TurnOff = True print("{},{},{},{},{},{},{},{},{},{}{}".format(Time, Temperature, Humidity, QualityScore, PM, Lat, Long, Alt, Speed, Climb, "\n")) f = open(file_name, "a")
import grovepi import time print "time,motion,sound" while True: motion=grovepi.digitalRead(4) sound=grovepi.analogRead(4) # do some sensor processing here print time.time(),",",motion,",",sound time.sleep(1)
import time import grovepi sensor = 0 vibration_motor = 8 while True: try: #Vibrate and read data grovepi.digitalWrite(vibration_motor, 1) print 'start' print grovepi.analogRead(sensor) time.sleep(.5) # Stop vibrating for 5 second, then repeat grovepi.digitalWrite(vibration_motor, 0) print 'stop' time.sleep(5) except KeyboardInterrupt: grovepi.digitalWrite(vibration_motor, 0) break except IOError: print "Error"
# Maximum distance threshold to be set with rotary angle sensor maxThreshold = 50 # Set to green as default setRGB(143, 189, 119) while True: #So we do not poll the sensors too quickly which may introduce noise, #sleep for a reasonable time of 200ms between each iteration. time.sleep(0.2) # Read Ultrasonic Ranging sensor ultrasonicDistance = grovepi.ultrasonicRead(PORT) # Read angle value from potentiometer sensor_value = grovepi.analogRead(potentiometer) setThreshold = int(sensor_value * maxThreshold / 1024) # Delay so I2C bus can settle time.sleep(0.1) print(setThreshold) print(ultrasonicDistance) # Compare if the threshold set by the rotary angle sensor is less than the # distance measured by the ultrasonic sensor if (ultrasonicDistance < setThreshold): lcdText = "{:>3d}".format( setThreshold) + "cm OBJ Pres \n" + "{:>3d}".format( ultrasonicDistance) + "cm" setText_norefresh(lcdText) setRGB(189, 83, 72)
def analogRead(sensor_port=0): try: return grovepi.analogRead(sensor_port) except Exception as e: logger.exception(f'{e}')
def main(): timer = -1 #Calcul nombre de lignes dans la table log while(True): try: # orientation: (0 = red to green, 1 = green to red) grovepi.ledBar_init(ledbar, 0) time.sleep(.5) grovepi.fourDigit_init(display) time.sleep(.5) sensor_value = grovepi.analogRead(air_sensor) val = str(sensor_value) horloge= datetime.datetime.now().strftime("%H:%M:%S") print ("Qualite de l air : " + val) time.sleep(1) [temp,humidity] = grovepi.dht(sensor,blue) if math.isnan(temp) == False and math.isnan(humidity) == False: timer = timer+1 print ("timer" + str(timer)) print("temp = %.02f C humidity =%.02f%%"%(temp,humidity)) setText("Temp : " + str(temp) + " Hum : " + str(humidity)+"%") if (timer%12==0): print("La temperature de la piece a " +str(horloge) + " est de : " + str(temp) + " C") api.PostUpdate("La temperature de la piece a " +str(horloge) + " est de : " + str(temp) + " C") else: pass if sensor_value > 130: setText("Temp : " + str(temp) + " Hum : " + str(humidity)+"%") setRGB(247,35,12) digitalWrite(ledvert,0) digitalWrite(ledrouge,1) time.sleep(.5) digitalWrite(ledrouge,0) grovepi.ledBar_setLevel(ledbar, 2) time.sleep(.5) elif sensor_value > 70: setText("Temp : " + str(temp) + " Hum : " + str(humidity)+"%") setRGB(255,215,0) digitalWrite(ledvert,0) digitalWrite(ledrouge,1) time.sleep(2) digitalWrite(ledrouge,0) grovepi.ledBar_setLevel(ledbar, 5) time.sleep(.5) else: setText("Temp : " + str(temp) + " Hum : " + str(humidity)+"%") setRGB(15,157,232) digitalWrite(ledrouge,0) digitalWrite(ledvert,1) time.sleep(1) grovepi.ledBar_setLevel(ledbar, 11) time.sleep(.5) curs.execute("SELECT COUNT(*) FROM log2") lignes=curs.fetchone() nblignes=lignes[0] compteur = nblignes print("Il y a " + str(compteur) + " personnes " ) leading_zero = 0 grovepi.fourDigit_number(display,compteur,leading_zero) time.sleep(.5) if (compteur !=0): digitalWrite(lumiere,1) else: digitalWrite(lumiere,0) f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000) if ( f.verifyPassword() == False ): raise ValueError('The given fingerprint sensor password is wrong!') except Exception as e: print('The fingerprint sensor could not be initialized!') print('Exception message: ' + str(e)) #while ( f.readImage() == False ): # pass try: key= f.readImage() today= datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") rdy = datetime.datetime.now().strftime("%b %d %Y") #str(today) clock= datetime.datetime.now().strftime("%H:%M:%S") if (key == False): pass if (key != False): curs.execute("SELECT COUNT(*) FROM log2") lignes=curs.fetchone() nblignes=lignes[0] print(nblignes) ## Converts read image to characteristics and stores it in charbuffer 1 f.convertImage(0x01) ## Searchs template result = f.searchTemplate() positionNumber = result[0] curs.execute("SELECT statut FROM user WHERE id_finger= ('%s')" %positionNumber) statut = curs.fetchone() stat=statut[0] print("Vous etes un : " + str(stat)) salle ="T229" if (stat == "PROF"): today= datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") str(today) print(today) curs.execute("SELECT nomP FROM prof WHERE id_finger = ('%s')" %positionNumber) nomP= curs.fetchone() nomtemp = nomP[0] print( nomtemp) curs.execute("SELECT numP FROM prof WHERE id_finger = ('%s')" %positionNumber) numP= curs.fetchone() numtemp = numP[0] print( numtemp) sql=("SELECT COUNT(*) FROM log2 WHERE(nom='%s')" %(nomtemp)) curs.execute(sql) nboccu=curs.fetchone() noccu=nboccu[0] if (noccu==0): curs.execute("INSERT INTO log2 (nom, date, salle, num, statut) VALUES ('%s', '%s', '%s','%s','%s')" %(nomtemp, today, salle, numtemp, stat)) db.commit() else: curs.execute("DELETE FROM log2 WHERE num = ('%s')" %numtemp) db.commit() else: today= datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") str(today) print(today) curs.execute("SELECT nomE FROM eleve WHERE id_finger = ('%s')" %positionNumber) nomE= curs.fetchone() nomtemp = nomE[0] print( numtemp) sql=("SELECT COUNT(*) FROM log2 WHERE(nom='%s')" %(nomtemp)) curs.execute(sql) nboccu=curs.fetchone() noccu=nboccu[0] if (noccu==0): curs.execute("INSERT INTO log2 (nom, date, salle, num, statut) VALUES ('%s', '%s', '%s','%s','%s')" %(nomtemp, today, salle, numtemp, stat)) db.commit() else: curs.execute("DELETE FROM log2 WHERE num = ('%s')" %numtemp) db.commit() except KeyboardInterrupt: digitalWrite(lumiere,0) digitalWrite(ledrouge,0) digitalWrite(lumiere,0) digitalWrite(ledvert,0) quit(1) except Exception as e: print("Empreinte non reconnue , reesayez") print("Duplicate Tweet or Twitter Refusal: {}".format(e))
def check_entrance_status(): # Connect the Grove Light Sensor to analog port # SIG,NC,VCC,GND light_sensor_in = 1 light_sensor_out = 2 grovepi.pinMode(light_sensor_in, "INPUT") grovepi.pinMode(light_sensor_out, "INPUT") camera = PiCamera() camera.resolution = (1024, 768) while True: try: # Get sensor value entrance_value = grovepi.analogRead(light_sensor_in) exit_value = grovepi.analogRead(light_sensor_out) if entrance_value < threshold_light: display("Welcome in!") in_plate = str(plate_recognize(camera)) if in_plate == "error": continue camera.stop_preview() in_vehicle = Vehicle.query.filter_by(plate=in_plate).first() if in_vehicle is None: display("No permit in!") else: spot = search_spot() if in_plate == "EA7THE": send_data(1) if spot != -1: in_spot = Spot.query.filter_by(spot_id=spot).first() text = "Welcome in!\n" + "Spot:" + str(in_spot.spot_id) #sendSMS(text) display(text) set_in_servo(07) in_vehicle.status = 1 in_vehicle.spot = spot in_spot.start_time = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') print(in_vehicle.status, in_vehicle.spot, in_spot.start_time, in_spot.rate) in_spot.rate = global_rate db.session.commit() while grovepi.analogRead( light_sensor_in) < threshold_light: time.sleep(2) time.sleep(2) set_out_servo(07) display("Ready for service") else: display("No vacant spot!") if exit_value < threshold_light: print("23123131") display("Welcome out!") out_plate = str(plate_recognize(camera)) if out_plate == "error": continue camera.stop_preview() out_vehicle = Vehicle.query.filter_by(plate=out_plate).first() out_spot = Spot.query.filter_by( spot_id=out_vehicle.spot).first() out_account = Account.query.filter_by( user_id=out_vehicle.user_id).first() end_time = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') end_time = datetime.datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S') start_time = datetime.datetime.strptime( out_spot.start_time, '%Y-%m-%d %H:%M:%S') fee = (end_time - start_time).total_seconds() * out_spot.rate client_fee.connect(host, 1883, 60) client_fee.publish(topic_fee, json.dumps({'Fee': fee})) print(fee, out_account.deposit) if out_account.deposit < fee: text = "No sufficient fund!" #sendSMS(text + " Please refill account!") display(text) else: if out_plate == "EA7THE": send_data(0) text = "See you!\n" + "Plate:" + str(out_vehicle.plate) sendSMS(text + "\nFee:" + str(fee)) display(text) out_account.deposit -= fee new_record = Record(user_id=out_vehicle.user_id, spot=out_vehicle.spot, plate=out_vehicle.plate, start=out_spot.start_time, end=datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S'), rate=out_spot.rate) db.session.add(new_record) print(fee, out_account.deposit) out_vehicle.status = 0 out_vehicle.spot = 0 out_spot.start_time = None db.session.commit() while grovepi.analogRead( light_sensor_out) < threshold_light: time.sleep(2) display("Ready for service") time.sleep(2) except Exception as e: continue return
last_sound = 0 screen = False while True: # Error handling in case of problems communicating with the GrovePi try: # Get value from temperature sensor [temp,humidity] = grovepi.dht(temperature_sensor,0) # Get value from light sensor light_intensity = grovepi.analogRead(light_sensor) if light_intensity/10>10: screen = True else: setText("") textCommand(0x00) screen = False # Get sound level sound_level = grovepi.analogRead(sound_sensor) if sound_level > 0: last_sound = sound_level # Post a tweet out_msg=("T: %.0dC H: %.1f%% \nL: %d S: %d" %(temp,humidity,light_intensity/10,last_sound)) R=int(light_intensity/10.*255)
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' import time import grovepi #Sensor connected to A0 Port sensor = 14 # Pin 14 is A0 Port. grovepi.pinMode(sensor,"INPUT") while True: try: sensor_value = grovepi.analogRead(sensor) print ("sensor_value =", sensor_value) time.sleep(.5) except IOError: print ("Error")
import sys import os import time import grovepi # Connect the Grove Moisture Sensor to analog port A0-A2 # SIG,NC,VCC,GND # Read sensor port (0 - 2) from argument 1 analog_sensor_port = int(sys.argv[1]); # Print the initial id String: script=<script>&port=<port> print('script=' + os.path.basename(__file__) + '&' + 'port=' + str(analog_sensor_port)); try: moist = grovepi.analogRead(analog_sensor_port); #Get the moisture value from analog_sensor_port except IOError: print('Error') sys.exit(12); # NOTE for wiki values <DryHumidWiki>: # The wiki suggests the following analog_sensor_port values: # Min Typ Max Condition # 0 0 0 analog_sensor_port in open air # 0 20 300 analog_sensor_port in dry soil # 300 580 700 analog_sensor_port in humid soil # 700 940 950 analog_sensor_port in water # Sensor values observer: # Val Condition # 0 analog_sensor_port in open air # 18 analog_sensor_port in dry soil
try: #get the barmeter information degrees = sensor.read_temperature() pascals = sensor.read_pressure() hectopascals = (pascals / 100) humidity = sensor.read_humidity() #print ('Temp = {0:0.3f} deg C'.format(degrees)) #print ('Pressure = {0:0.2f} hPa'.format(hectopascals)) #print ('Humidity = {0:0.2f} %'.format(humidity)) bar_string = str("%.2f" % degrees) + "," + str( "%.2f" % hectopascals) + "," + str("%.2f" % humidity) #sensor 0 = sound. Sensor2 = light sensor_value0 = grovepi.analogRead(sensor0) sensor_value1 = grovepi.analogRead(sensor1) sensor_value2 = grovepi.analogRead(sensor2) #temperature sensor data temperatureV = 0 humidityV = 0 [temp, humidity] = grovepi.dht(temp_hum_sensor, blue) if math.isnan(temp) == False and math.isnan(humidity) == False: #print("temp = %.02f C humidity = %.02f%%" %(temp, humidity)) temperatureV = temp humidityV = humidity #get the GPS data, or return 'bno data' if there is none try:
########################## # main loop ########################## while True: try: # if the lights are on, test whether it's time for a long nappy if lights_on == True: sleeptime() # test included in this function call. if grovepi.digitalRead(pir_sensor): # switch on for 5 seconds print("blink on") blink(5) print("blink off") light_sensor_value = grovepi.analogRead(light_sensor) # is it getting dark? if light_sensor_value < light_threshold: # turn lights on if lights_on == False: lights_on = True start_sleeptime = time.time() print("turning lights on ") grovepi.digitalWrite(relay, 1) # is it getting light? else: # turn lights off if lights_on == True: lights_on = False
if en_debug: print "Rx:", msg if msg == 'SETUP': print "Setting up sensors done" elif msg == 'START': running = True if thread1.is_alive() == False: thread1.start() print "Service Started" elif match_sensors(msg, analog_sensors) >= 0: if en_grovepi: s_no = match_sensors(msg, analog_sensors) sens = analog_sensors[s_no] port = int(msg[len(sens):]) a_read = grovepi.analogRead(port) s.sensorupdate({sens: a_read}) if en_debug: print msg print sens + 'op:' + str(a_read) elif msg[:8].lower() == "setInput".lower(): if en_grovepi: port = int(msg[8:]) grovepi.pinMode(port, "INPUT") if en_debug: print msg elif msg[:9].lower() == "setOutput".lower(): if en_grovepi:
def readAnalogSensors(): for sensor in config.analogSensors: pin = config.analogSensors[sensor] if pin >= 0: sensorValues[sensor] = grovepi.analogRead(pin)
#Digital Port D2~D8 DHT_Senor_Port = 2 # Connect the DHT sensor to port D2 Green_LED_Port = 3 # Connect the GREEN LED to port D3 RED_LED_Port = 4 # Connect the RED LED to port D4 #------------------------------------------------------- #--------------Senor Grove pi setting End---------------------------# try: time.sleep(10) Light_value = 0 temp = 0 hum = 0 Sound_value = 0 Air_value = 0 while Light_value == 0: Light_value = grovepi.analogRead(Light_Senor_Port) while Sound_value == 0: Sound_value = grovepi.analogRead(Sound_Senor_Port) while Air_value == 0: Air_value = grovepi.analogRead(Air_Senor_Port) if Light_value != 0: resistance = (float)(1023 - Light_value) * 10 / Light_value else: resistance = 0 while temp == 0: [t, h] = grovepi.dht(DHT_Senor_Port, 0) temp = float(t) hum = float(h) Sound = Sound_value / 100 Air = Air_value / 100
threshold = 10 grovepi.pinMode(sound_sensor, "INPUT") grovepi.pinMode(light_sensor, "INPUT") grovepi.pinMode(led, "OUTPUT") threshold_value = 400 # temp_humidity_sensor_type # Grove Base Kit comes with the blue sensor. blue = 0 # The Blue colored sensor. white = 1 # The White colored sensor. while True: try: # Get sensor values lightsensor_value = grovepi.analogRead(light_sensor) soundsensor_value = grovepi.analogRead(sound_sensor) [temp, humidity] = grovepi.dht(dhtsensor, blue) # Calculate resistance of sensor in K resistance = (float)(1023 - lightsensor_value) * 10 / lightsensor_value ts = datetime.datetime.now() if resistance > threshold: # Send HIGH to switch on LED grovepi.digitalWrite(led, 1) else: # Send LOW to switch off LED grovepi.digitalWrite(led, 0) if math.isnan(temp) == False and math.isnan(humidity) == False: print("temp = %.02f C humidity =%.02f%%" % (temp, humidity))
def main(): global isConnected # Create an MQTT client for connecting to AWS IoT via MQTT. client = mqtt.Client( deviceName + "_sr" ) # Client ID must be unique because AWS will disconnect any duplicates. client.on_connect = on_connect # When connected, call on_connect. client.on_message = on_message # When message received, call on_message. client.on_log = on_log # When logging debug messages, call on_log. # Set the certificates and private key for connecting to AWS IoT. TLS 1.2 is mandatory for AWS IoT and is supported # only in Python 3.4 and later, compiled with OpenSSL 1.0.1 and later. client.tls_set(awsCert, deviceCertificate, devicePrivateKey, ssl.CERT_REQUIRED, ssl.PROTOCOL_TLSv1_2) # Connect to AWS IoT server. Use AWS command line "aws iot describe-endpoint" to get the address. print("Connecting to AWS IoT...") client.connect("A1P01IYM2DOZA0.iot.us-west-2.amazonaws.com", 8883, 60) # Start a background thread to process the MQTT network commands concurrently, including auto-reconnection. client.loop_start() # Configure the Grove LED port for output. grovepi.pinMode(led, "OUTPUT") time.sleep(1) # Loop forever. while True: try: # If we are not connected yet to AWS IoT, wait 1 second and try again. if not isConnected: time.sleep(1) continue # Read Grove sensor values. Prepare our sensor data in JSON format. payload = { "state": { "reported": { # Uncomment the next line if you're using the Grove Analog Temperature Sensor. # "temperature": round(grovepi.temp(temp_sensor, '1.1'), 1), # Comment out the next 2 lines if you're using the Grove Analog Temperature Sensor. "temperature": grovepi.dht(dht_sensor, 0) [0], # The first 0 means that the DHT module is DHT11. "humidity": grovepi.dht(dht_sensor, 0)[1], "light_level": grovepi.analogRead(light_sensor), "sound_level": grovepi.analogRead(sound_sensor), "timestamp": datetime.datetime.now().isoformat() } } } print("Sending sensor data to AWS IoT...\n" + json.dumps(payload, indent=4, separators=(',', ': '))) # Publish our sensor data to AWS IoT via the MQTT topic, also known as updating our "Thing Shadow". client.publish("$aws/things/" + deviceName + "/shadow/update", json.dumps(payload)) print("Sent to AWS IoT") # Wait 30 seconds before sending the next set of sensor data. time.sleep(30) except KeyboardInterrupt: # Stop the program when we press Ctrl-C. break except Exception as e: # For all other errors, we wait a while and resume. print("Exception: " + str(e)) time.sleep(10) continue