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 read_buttons(): startTime = datetime.now() while (datetime.now() - startTime).seconds < 1: button1 = grovepi.digitalRead(BUTTON1_PIN) if button1: print "button 1 down" buttonTime = datetime.now() while grovepi.digitalRead(BUTTON1_PIN) and (datetime.now() - buttonTime).seconds < 1: time.sleep(.001) downTime = (datetime.now() - buttonTime).microseconds if downTime > 120000: print "Returning 1, down time " + str(downTime) return 1 else: print "Phantom press, down time " + str(downTime) button2 = grovepi.digitalRead(BUTTON2_PIN) if button2: print "button 2 down" buttonTime = datetime.now() while grovepi.digitalRead(BUTTON2_PIN) and (datetime.now() - buttonTime).seconds < 1: time.sleep(.001) downTime = (datetime.now() - buttonTime).microseconds if downTime > 120000: print "Returning 2, down time " + str(downTime) return 2 else: print "Phantom press, down time " + str(downTime) return 0
def io_actions(sock): if 1 == grovepi.digitalRead(input): time.sleep(0.05) if 1 == grovepi.digitalRead(input): print "HIGH" grovepi.digitalWrite(speaker, 1) sock.send("action") time.sleep(3) grovepi.digitalWrite(speaker, 0)
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 main(): cfg = { "consumer_key":'9iHdYDCrzpNefQqtUyDh7tScN', "consumer_secret":'pYP8c8njj3vtJqeoDNZpR2kMwuNi0LQKmiGnBlL1Dg5sylEUyI', "access_token":'756129972075556864-8G9mT1j8RxOx7cgrTbWsQ9CqrK3f0iG', "access_token_secret":'ZmjDVFHZgYKNvI0Cr2bKQfSYue2tOh4R6uLBWblRUndvN' } grovepi.pinMode(button, "INPUT") print "Waiting for button to be pressed" while True: try: # get value of button status button_status = grovepi.digitalRead(button) # if button pressed if button_status == 1: api = get_api(cfg) print "I am posting a tweet via GrovePi!" # captures distance between ultrasonic sensor and the closest object distance = grovepi.ultrasonicRead(ultrasonic_ranger) tweet = "There is currently an object " + str(distance) + " cm away from my$ status = api.update_status(status=tweet) # immediately print tweet print(tweet) except IOError: print("Error") except KeyboardInterrupt: exit()
def get_loopstate(): """ Get state of loop, with whatever the system ends up being. For now, since it's grovepi, don't call in multiple threads """ return grovepi.digitalRead(LOOP)
def demoButton(self): while True: try: print(grovepi.digitalRead(button)) time.sleep(.5) except IOError: print ("Error") except KeyboardInterrupt: break
def isFireDected(): #GrovePi output 1 means no fire. if (grovepi.digitalRead(flame)): grovepi.digitalWrite(led, 0) return "no" #return False #Fire detected, set fire message else: grovepi.digitalWrite(led, 1) return "yes"
def sound_alarm(): type = "" exit_flag = False now = datetime.datetime.now() alm_min = now.minute now_min = now.minute val = 10 lcd.rgb(255, 0, 0) lcd.text(" Alarm!!!") while alm_min == now_min: now = datetime.datetime.now() now_min = now.minute grovepi.analogWrite(buzzer, val) if grovepi.digitalRead(button) == True: break else: if val == 10: val = 70 else: val = 10 sleep(1) grovepi.analogWrite(buzzer, 0) #Wait for button to be releasd while True: try: if grovepi.digitalRead(button) == False: break except IOError: pass lcd.text("") lcd.rgb(50,50,50) alm["quiet"] = "X"
def release(self): try: sensor = grovepi.digitalRead(button) if sensor == 0 or sensor == 1: # check if reads were 0 or 1 it can be 255 also because of IO Errors so remove those values if sensor == 1: return 1 else: return 0 except IOError: print("Error")
def get_motion_grove(): grovepi.pinMode(PORT, "INPUT") MOTION = grovepi.digitalRead(PORT) if MOTION == 0 or MOTION == 1: if MOTION == 1: return jsonify({'motion': MOTION, 'text': 'motion detected'}) else: return jsonify({'motion': MOTION, 'text': 'no motion detected'}) else: return jsonify({'text': '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 sensorTest(): motion_sensor_value = grovepi.digitalRead(pir_sensor) motion = False if motion_sensor_value==0 or motion_sensor_value==1: if motion_sensor_value==1: motion = True else: motion = False return jsonify({ 'motion': motion })
def run(self): t = time.time() while t + self.temps > time.time(): try: e = grovepi.digitalRead(button1) if e == 1: self._return = True return time.sleep(0.5) except IOError: print("Problème lecture bouton 1")
def calculateOverride(): isButtonPressed = grovepi.digitalRead( iButtonPort ) if isButtonPressed: client.iOverride = client.iOverride + 1 logging.info( "Button depressed current state: TRUE Override has increased to: " + str( client.iOverride ) + "\n" ) else: logging.debug( "Button depressed current state: FALSE" ) if client.iOverride == 0: logging.debug( "Override value cannot fall below zero") else: client.iOverride = client.iOverride - 1 logging.info( "Override value invoked but decreased to: " + str( client.iOverride ) + "\n" )
def checkButtons(in_button_pin, out_button_pin): try: in_button = grovepi.digitalRead(in_button_pin) except IOError: print "In button error" return -1 try: out_button = grovepi.digitalRead(out_button_pin) except IOError: print "Out button error" return -1 print "%s In button (3) : %d , Out button (4) : %d" % ( datetime.now().strftime("%Y/%m/%d %H:%M:%S"), in_button, out_button) if in_button == 0 and out_button == 0: return 0 if in_button == 0 and out_button == 1: return 2 if in_button == 1 and out_button == 0: return 1 if in_button == 1 and out_button == 1: return 3
def get_input(): if grovepi.digitalRead(2) == 1: return { 'clientname': clientname, 'tappedkey': 2, 'timestamp': str(datetime.now()) } if grovepi.digitalRead(3) == 1: return { 'clientname': clientname, 'tappedkey': 3, 'timestamp': str(datetime.now()) } if grovepi.digitalRead(4) == 1: return { 'clientname': clientname, 'tappedkey': 4, 'timestamp': str(datetime.now()) } if grovepi.digitalRead(5) == 1: return { 'clientname': clientname, 'tappedkey': 5, 'timestamp': str(datetime.now()) } if grovepi.digitalRead(6) == 1: return { 'clientname': clientname, 'tappedkey': 6, 'timestamp': str(datetime.now()) } if grovepi.digitalRead(7) == 1: return 'end'
def affichageInstru() : test = True instru = int ecran.resetEcran() ecran.setRGB(0,250,130) time.sleep(0.3) bouton = False ecran.setText_norefresh("Choississez votre instrument") time.sleep(2) ecran.resetEcran() time.sleep(.5) while test : # Si la distance est entre 3 et 20 l'utilisateur choisit la guitare while 3 <= distance() <= 20 : ecran.setText_norefresh("Tu choisis \nla guitare") time.sleep(.02) # Si on apuie sur le bouton on sort de la boucle et on renvoie instru = 1 if grovepi.digitalRead(button) == 1 : instru = 1 test = False # Si la distance est entre 21 et 30 l'utilisateur choisit le piano while 21 <= distance() <= 30 : ecran.setText_norefresh("Tu choisis \nle piano") time.sleep(.02) # Si on apuie sur le bouton on sort de la boucle et on renvoie instru = 2 if grovepi.digitalRead(button) == 1 : instru = 2 test = False # Si la distance est entre 31 et 40 l'utilisateur choisit la batterie while 31 <= distance() <= 40 : ecran.setText_norefresh("Tu choisis \nla batterie") time.sleep(.02) # Si on apuie sur le bouton on sort de la boucle et on renvoie instru = 3 if grovepi.digitalRead(button) == 1 : instru = 3 test = False print(instru) return instru
def greengrass_sensor_run(): try: temp_value = 0.1 mois_value = 0 light_value = 0 switch_status = 0 lastTemp = 0.1 lastMois = 0 # Get value from temperature sensor temp_value = grovepi.temp(temp_sensor, "1.2") #temp_value = random.uniform(22.0, 23.9) # Get value from moisture sensor mois_value = grovepi.analogRead(mois_sensor) #mois_value = random.randint(150,350) # Get value from light sensor light_value = grovepi.analogRead(light_sensor) #light_value = random.randint(590,620) moment = "D" if light_value > 200 else "N" # Get status from relay switch_status = grovepi.digitalRead(relay) #switch_status = random.randint(0,1) # Set temperature and moisture to LCD if (abs(temp_value - lastTemp) >= 0.1) or (mois_value != lastMois): lastTemp = temp_value lastMois = mois_value bgList = calcBG(mois_value) setRGB(bgList[0], bgList[1], bgList[2]) setText("Temp: %.1f C *%s\nMoisture: %d " % (temp_value, moment, mois_value)) # build the message to be sent message = { "clientId": "sensor001", "timestamp": int(datetime.now(timezone.utc).timestamp() * 1000), "temp": format(temp_value, '0.1f'), "moisture": mois_value, "light": light_value, "switch": switch_status } logger.info('Triggering publish to topic ' + sensor_topic + ' with ' + json.dumps(message)) client.publish(topic=sensor_topic, queueFullPolicy='AllOrException', payload=json.dumps(message)) except IOError: logger.error('IO Error') except Exception as e: logger.error('Failed to publish message: ' + repr(e)) # Asynchronously schedule this function to be run again in 5 seconds Timer(5, greengrass_sensor_run).start()
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 getMotion(): while True: try: # Sense motion, usually human, within the target range motion = grovepi.digitalRead(pir_sensor) if motion == 0 or motion == 1: # check if reads were 0 or 1 if motion == 1: print("Motion Detected") grovepi.analogWrite(buzzer, 100) # Make a sound on the Buzzer return grovepi.digitalRead(pir_sensor) time.sleep(.1) else: print("-") grovepi.analogWrite(buzzer, 0) # Turn off the Buzzer #return grovepi.digitalRead(pir_sensor) return grovepi.digitalRead(pir_sensor) time.sleep(5) except KeyboardInterrupt: break except IOError: print "IOError happened"
def read_distance(): try: # Sensor returns LOW and onboard LED lights up when the # received infrared light intensity exceeds the calibrated level if grovepi.digitalRead(sensor) == 0: return True else: return False time.sleep(.5) except IOError: return "Error distance"
def check(self): try: val = grovepi.digitalRead(self.pin) print(val) if val == 0: return True time.sleep(.5) except IOError: print("Error") return False
def changerEtat(self): """ Change d'état l'actionneur, fonction basculement (toggle). Lit l'état logique présent à l'entrée de l'actionneur puis envoie l'état logique opposé pour faire changer d'état l'actionneur. Les attributs m_isActionneurActif et m_niveauActuel sont mis à jour """ self.m_niveauActuel = not grovepi.digitalRead(self.m_pinActionneur) grovepi.digitalWrite(self.m_pinActionneur, self.m_niveauActuel) if self.m_niveauActuel == self.s_ACTIF: self.m_isActionneurActif = self.s_ACTIF # Actionneur activé else: self.m_isActionneurActif = not self.s_ACTIF # Actionneur désactivé
def read_start_stop_switch(self, q): while True: try: button = grovepi.digitalRead(self.digital_port) if button == 1: # print("Button pressed!") q.queue.clear() q.put(1) time.sleep(1) except IOError: print("Error")
def handle(self): grovepi.pinMode(self.port, "INPUT") while True: try: value = grovepi.digitalRead(self.port) if value: # GOAL!! #print "gooooool!!!!!", value for s in self.subscribers: # notify s.notify(1) time.sleep(.2) except TypeError: print ("Error") 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 goStraight(): lineSensor = grovepi.digitalRead(8) #a function to ignore the left line and go straight to pass a dropoff site if lineSensor == 1: leftMotorSpeed = -15 rightMotorSpeed = -80*1.12 else: leftMotorSpeed = -80 rightMotorSpeed = -15 * 1.12 BP.set_motor_power(BP.PORT_B, leftMotorSpeed) #update motor speeds BP.set_motor_power(BP.PORT_C, rightMotorSpeed) #time.sleep(0.1) return()
def set_relay(port, settings): try: if settings['relay_mode'] == 'on': grovepi.digitalWrite(port, 1) elif settings['relay_mode'] == 'off': grovepi.digitalWrite(port, 0) elif settings['relay_mode'] == 'switch': state = grovepi.digitalRead(port) if state == 1: grovepi.digitalWrite(port, 0) elif state == 0: grovepi.digitalWrite(port, 1) except ValueError: return "Not found"
def buttonF(): time.sleep(0.10) try: #switch turn on/off pressed =(grovepi.digitalRead(button)) if pressed==True: #grovepi.digitalWrite(led1,1) time.sleep(0.20) client.publish("takePicture", 1) client.publish("motion", 1) except (IOError,TypeError) as ex: error="Error: " + str(ex)
def button(): # Connect the Grove Button to digital port D3 # SIG,NC,VCC,GND button = 3 grovepi.pinMode(button,"INPUT") press = 0 while True: try: press = grovepi.digitalRead(button) if press == True: return True except IOError: print ("Error")
def button_read(): retry = 3 while retry > 0: try: status = grovepi.digitalRead(button) time.sleep(.01) break except: print 'can not read button, retry again' retry = retry - 1 time.sleep(.1) if retry == 0: return -1 else: return status
def lineFollow(): # a function to follow the line NXTLight = BP.get_sensor(BP.PORT_2) lineSensor = grovepi.digitalRead(8) if lineSensor == 1: leftMotorSpeed = -300 rightMotorSpeed = 460 * 1.12 elif(NXTLight > 2400): leftMotorSpeed = 460 rightMotorSpeed = -300*1.12 else: leftMotorSpeed = -360 rightMotorSpeed = -360*1.12 BP.set_motor_dps(BP.PORT_C, leftMotorSpeed) #update motor speeds BP.set_motor_dps(BP.PORT_B, rightMotorSpeed) return()
def lcdcallback(client,userdata,msg): freq = int(str(msg.payload, "utf-8")) while True: buttonpress = grovepi.digitalRead(button) if(buttonpress): print("buttonpressed") for i in tones: #if(note_produced == tones[i]): #if(freq - 20 < tones[i] < freq + 20): if(abs(freq - tones[i]) <= 20): grove_rgb_lcd.setText(i) break client.subscribe("theduo/defaultCallback")
def read_sensor(self): new_value = bool(False) try: new_value = bool(grovepi.digitalRead(self.connector)) except IOError: self.logger.debug("Error in reading sensor at pin " + str(self.connector)) if not self.is_equal(self.value, new_value): self.value = new_value self.notify_all_actuators() self.updated_state() self.logger.debug( "------------------read_sensor called in ButtonResource instance" )
def detect(self): det = False while True: try: # Sense motion, usually human, within the target range if grovepi.digitalRead(self.pir_sensor): print 'motion detected' det = True else: print '-' # if your hold time is less than this, you might not see as many detections time.sleep(.8) except IOError: print "Error" return det
def runLoop(): isMotionActive = False while True: try: if grovepi.digitalRead(digitalPins.get('motion')): if isMotionActive: isMotionActive = False else: print('Motion detected') getEnvironmentData() else: print('No motion detected') time.sleep(1) except IOError: print('IO Error')
def lire(self): """ Lit l'état logique actuel du capteur et met à jour les attributs de l'objet """ # niveau logique envoyé par capteur (0 ou 1) # ??? BUG ??? parfois, la lecture de l'entrée du capteur retourne 255 !!! # utilisation m_niveauPrecedent pour corriger ce bug self.m_niveauPrecedent = self.m_niveauActuel self.m_niveauActuel = grovepi.digitalRead(self.m_pinCapteur) if (self.m_niveauActuel != 0 and self.m_niveauActuel != 1): self.m_niveauActuel = self.m_niveauPrecedent if (self.m_niveauActuel == self.m_niveauActif): self.m_isActionneurActif = True # capteur actif else: self.m_isActionneurActif = False # capteur au repos return self.m_isActionneurActif
def cozmo_program(robot: cozmo.robot.Robot): while True: try: motion = grovepi.digitalRead(motion_sensor) #überprüft, ob eine Bewegung wahrgenommen wurde mit 0 oder 1 if motion == 0 or motion == 1: #wenn Bewegung wahgenommen (1), dann... if motion == 1: print("Eine unbakannte Bewegung wurde erkannt") #ansonsten else: print("Nicht erkannt") time.sleep(0.2) except IOError: print("IOError")
def lineFollow(): # a function to follow the line line = BP.get_sensor(BP.PORT_2) lineSensor = grovepi.digitalRead(8) if lineSensor == 1: leftMotorSpeed = -50 rightMotorSpeed = 75 * 1.12 print(lineSensor) elif(line > 2400): leftMotorSpeed = 75 rightMotorSpeed = -50*1.12 print(line) else: leftMotorSpeed = -65 rightMotorSpeed = -65*1.12 BP.set_motor_power(BP.PORT_C, leftMotorSpeed) #update motor speeds BP.set_motor_power(BP.PORT_B, rightMotorSpeed) return()
def update(self, milliseconds): if milliseconds % self.msPerRead > 0: return try: motion = grovepi.digitalRead(self.motionSensorDigitalPort) if motion == 0 or motion == 1: self.buffer.append(motion) mean = numpy.average(self.buffer) if self.isOccupied and mean <= 1 / len(self.buffer): self.isOccupied = False elif not self.isOccupied: self.isOccupied = bool(mean >= 0.3) except BaseException as ex: print("[occupation] " + str(ex), file=sys.stderr)
def run(self): global grovepi global exchange_sensors while True: try: threadLock.acquire() self.motion=grovepi.digitalRead(self.pir_sensor) threadLock.release() if self.motion==0 or self.motion==1: if self.motion==1: print("Motion = 1") if self.last_motion_message==0: now = int(round(time.time() * 1000)) # Current time in miliseconds message = { "value": 1, "createdAt": now } message_json = json.dumps(message) self.channel.basic_publish(exchange=exchange_sensors, routing_key=self.routing_key_motion, body=message_json) print("---------- Sent %r:%r" % (self.routing_key_motion, message_json)) self.last_motion_message = 1 self.timer = 30 else: self.timer = 30 else: print("Motion = 0") if self.last_motion_message==1: if self.timer==0: now = int(round(time.time() * 1000)) # Current time in miliseconds message = { "value": 0, "createdAt": now } message_json = json.dumps(message) self.channel.basic_publish(exchange=exchange_sensors, routing_key=self.routing_key_motion, body=message_json) print("---------- Sent %r:%r" % (self.routing_key_motion, message_json)) self.last_motion_message = 0 if self.last_motion_message==1 and self.timer > 0: self.timer = self.timer - 1 print("Motion timer = " + str(self.timer) + "\n") time.sleep(1) except: print ("Error") self.connection.close()
def get_value(name, max): lcd.text("") while True: try: val = int(grovepi.analogRead(rotary) / (1023 / max)) if val > (max - 1): val = max - 1 lcd.text_norefresh("Alarm Set\nSelect %s: %02d" % (name, val)) if grovepi.digitalRead(button) == True: break except IOError: pass sleep(0.5) return val
def buttonflag (): button_flag = True while button_flag: try: value = grovepi.digitalRead(button) print( "Button Sensor = " + str(value)) if value==1: button_flag=False # Read the button value. # If it is pressed, then stop the loop and move on. time.sleep(.5) except TypeError: print(TypeError) except IOError: print(IOError) print('Got button press')
def startSensor(triggerPercent, callback, callbackId): global threshold threshold = int(triggerPercent) id = int(callbackId) triggered = False while not stop: try: light_value = grovepi.digitalRead(light_sensor) if (light_value >= threshold): if not triggered: triggered = True callback(id, light_value) if (triggered and light_value < threshold): triggered = False time.sleep(.05) except IOError: stopSensor() print("Error")
def switchF(): time.sleep(1) try: #switch turn on/off pressed =(grovepi.digitalRead(switch)) if pressed==True: #grovepi.digitalWrite(led1,1) time.sleep(0.20) client.publish("relay_status", 1) grovepi.digitalWrite(relay,1) if pressed==False: #grovepi.digitalWrite(led1,0) time.sleep(0.20) client.publish("relay_status", 0) grovepi.digitalWrite(relay,0) except (IOError,TypeError) as ex: error="Error: " + str(ex)
def manual(): #This is a program that allows you to control the blinds with a knob. global potentiometer_pin, button_pin, led1_pin, led2_pin adc_ref = 5 #Reference voltage of ADC is 5v grove_vcc = 5 #Vcc of the grove interface is normally 5v full_angle = 300 #Full value of the rotary angle is 300 degrees, as per it's specs (0 to 300) sensor_value = grovepi.analogRead(potentiometer_pin) #Read sensor value from potentiometer voltage = round((float)(sensor_value) * adc_ref / 1023, 2) #Calculate voltage degrees = round((voltage * full_angle) / grove_vcc, 2) #Calculate rotation in degrees (0 to 300) #This will be replaced with a distance measurment brightness = int(degrees / full_angle * 255) #Calculate LED brightess (0 to 255) from degrees (0 to 300) button_test = grovepi.digitalRead(button_pin) #Is the button on or off? On will control the blinds, off will control the shutters if (button_test==1): #Give PWM output to LED grovepi.analogWrite(led1_pin,brightness) #Move blinds else: grovepi.analogWrite(led2_pin,brightness) #Move shutters print("sensor_value =", sensor_value, " voltage =", voltage, " degrees =", degrees, " brightness =", brightness)
def formMenu(self, items): itemRange = int(1000/len(items)) while True: try: # Read sensor value from potentiometer sensor_value = grovepi.analogRead(potentiometer) selection = int(sensor_value/itemRange) # check to make sure that our index value isn't going over if selection >= len(items): selection = len(items) - 1 setText(list(items[selection])) self.colorSelect(selection) if grovepi.digitalRead(button) == 1: self.clear() return selection time.sleep(0.5) except KeyboardInterrupt: grovepi.analogWrite(gled,0) break except IOError: print ("Error")
def motion(): time.sleep(0.22) try: if grovepi.digitalRead(pir_sensor): global canEdit if canEdit==True: lcd.setText("Welkom thuis") global isNight isNight if isNight==True: lcd.setRGB(0,0,0) else: lcd.setRGB(100,100,100) display_status="" client.publish("motion", 1) #time.sleep(5) else: client.publish("motion", 0) except (IOError,TypeError) as ex: error="Error: " + str(ex) print(error)
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 # Connect the Grove Water Sensor to digital port D2 # SIG,NC,VCC,GND water_sensor = 2 grovepi.pinMode(water_sensor,"INPUT") while True: try: print(grovepi.digitalRead(water_sensor)) time.sleep(.5) except IOError: print ("Error")
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 # Connect the Grove Tilt Switch to digital port D3 # SIG,NC,VCC,GND tilt_switch = 3 grovepi.pinMode(tilt_switch,"INPUT") while True: try: print(grovepi.digitalRead(tilt_switch)) time.sleep(.5) except IOError: print ("Error")
port=int(msg[8:]) grovepi.pinMode(port,"INPUT") if en_debug: print msg elif msg[:9].lower()=="setOutput".lower(): if en_grovepi: port=int(msg[9:]) grovepi.pinMode(port,"OUTPUT") if en_debug: print msg elif msg[:11].lower()=="digitalRead".lower(): if en_grovepi: port=int(msg[11:]) d_read=grovepi.digitalRead(port) s.sensorupdate({'digitalRead':d_read}) if en_debug: print msg print "Digital Reading: " + str(d_read) elif match_sensors(msg,digitalInp) >=0: if en_grovepi: s_no=match_sensors(msg,digitalInp) sens=digitalInp[s_no] port=int(msg[len(sens):]) sens += str(port) grovepi.pinMode(port,"INPUT") d_read=grovepi.digitalRead(port) s.sensorupdate({sens:d_read}) if en_debug:
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/gpl-3.0.txt>. ''' import time import grovepi # Connect the Grove Magnetic Switch to digital port D3 # SIG,NC,VCC,GND magnetic_switch = 3 grovepi.pinMode(magnetic_switch,"INPUT") while True: try: print (grovepi.digitalRead(magnetic_switch)) time.sleep(.5) except IOError: print ("Error")
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 Line Finder to digital port D7 # SIG,NC,VCC,GND line_finder = 7 grovepi.pinMode(line_finder,"INPUT") while True: try: # Return HIGH when black line is detected, and LOW when white line is detected if grovepi.digitalRead(line_finder) == 1: print ("black line detected") else: print ("white line detected") time.sleep(.5) except IOError: print ("Error")
signal.signal(signal.SIGTERM, signal_term_handler) while True: try: # Encoder if radio_on == 1: [new_val, encoder_val] = grovepi.encoderRead() if new_val: print('====> Encoder: %d') % encoder_val if os.path.exists(lock_file2): print('====> Locking...') else: start_radio(encoder_val, radio_on) # Button for speaking self iCloud Calendar if grovepi.digitalRead(icloudBtnPort) == 1: print('====> Button: D%d') % icloudBtnPort # Turn feedback LED on grovepi.digitalWrite(feedbackLEDPort, 1) # Run speak_events if os.path.exists(lock_file1): print('====> Locking...') else: speak_events() # Button for turning Radio on/off if grovepi.digitalRead(radioBtnPort) == 1: print('====> Button: D%d') % radioBtnPort
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 # Connect the Grove Button to digital port D3 # SIG,NC,VCC,GND button = 3 grovepi.pinMode(button,"INPUT") while True: try: print(grovepi.digitalRead(button)) time.sleep(.5) except IOError: print ("Error")
IOT.send("false", Led) #provide feedback to the cloud that the operation was succesful else: print("unknown value: " + value) else: print("unknown actuator: " + id) IOT.on_message = on_message #make certain that the device & it's features are defined in the cloudapp IOT.connect() IOT.addAsset(Pir, "PIR", "PIR SENSOR", False, "boolean") IOT.addAsset(Led, "LED", "Light Emitting Diode", True, "boolean") IOT.subscribe() #starts the bi-directional communication #main loop: run as long as the device is turned on while True: try: if grovepi.digitalRead(Pir) == 1: if Pir_Prev == False: print("PIR activated") IOT.send("true", Pir) Pir_Prev = True elif Pir_Prev == True: print("PIR deactivated") IOT.send("false", Pir) Pir_Prev = False sleep(.3) except IOError: print ""
currentStateD2 = 0 noMotionCountD2 = 0 currentStateD3 = 0 noMotionCountD3 = 0 currentStateD4 = 0 noMotionCountD4 = 0 while True: # SIG,NC,VCC,GND motion=0 grovepi.pinMode(2,"INPUT") #Reads from D2 try: # Sense motion, usually human, within the target range motion=grovepi.digitalRead(2) cTime = time.strftime("%H %M %S %d %m %Y") if motion == 1: noMotionCountD2 = 0 if currentStateD2 != 1: currentStateD2 = 1 s.send("D2 motion true " + cTime) elif motion==0: noMotionCountD2 += 1 if currentStateD2!=0 and noMotionCountD2 > 5: currentStateD2 = 0 s.send("D2 motion false " + cTime) except IOError: pass time.sleep (0.3)