def buzzer_write(value): grovepi.pinMode(buzzer,"OUTPUT") grovepi.digitalWrite(buzzer,1) time.sleep(value) grovepi.digitalWrite(buzzer,0) time.sleep(.5)
def exit(): time.sleep(0.50) grovepi.digitalWrite(led1,0) time.sleep(0.50) grovepi.digitalWrite(led2,0) time.sleep(0.50) grovepi.digitalWrite(led3,0) time.sleep(0.50) grovepi.digitalWrite(buzzer,0) time.sleep(0.50) grovepi.digitalWrite(relay,0) time.sleep(0.50) client.publish("online", 0) client.publish("led1_status", 0) client.publish("led2_status", 0) client.publish("led3_status", 0) client.publish("relay_status", 0) client.publish("display_status", "") lcd.setRGB(100,100,100) lcd.setText("IOT-DEVICE \nSTOPPING") time.sleep(1) lcd.setRGB(0,0,0) lcd.setText("") time.sleep(0.50)
def internalFireActuateDoorNLCD(client, attribute, value, doorLocation): if attribute == "timestamp": # Ignore the timestamp attribute, it's only for info. return print("Setting " + attribute + " to " + value + "...") if attribute == "studentIDsInArea": print("INTERNAL FIRE***********************") print("COMMAND CENTER LCD******************************") #Actuate LCD - Command Center AlertText = "Fire:"+doorLocation+" StuIDs:"+value #AlertText = "Fire!"+doorLocation+"StudentIDs\n:"+value setText(AlertText) setRGB(0,128,64) for c in range(0,255): setRGB(c,255-c,0) time.sleep(0.01) setRGB(0,255,0) #setText("") setRGB(0,0,0) # Unlock Door. grovepi.digitalWrite(relay,0) #open door, cut power to relay # grovepi.digitalWrite(led, 0) #LED OFF - Simulate Door LED time.sleep(10) #Door left open number of seconds grovepi.digitalWrite(relay,1) #lock door, resume power to relay #Clear LCD setText("") #Update G49Trace send_reported_state(client, attribute, value, doorLocation) return # Show an error if attribute or value are incorrect. print("Error: Don't know how to set " + attribute + " to " + value)
def detectCrosswalkLines(resizedInputPhoto): # print threeFourthsDown height, width, channels = resizedInputPhoto.shape croppedInputPhoto = resizedInputPhoto[height / 4:height, :] cv2.imshow('image', croppedInputPhoto) cv2.waitKey(30) gray_img = cv2.cvtColor(croppedInputPhoto, cv2.COLOR_BGR2GRAY) ret, gray_img = cv2.threshold(gray_img, 150, 255, cv2.THRESH_BINARY) cv2.imshow('thresholded', gray_img) cv2.waitKey(30) img, contours, _ = cv2.findContours(gray_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cv2.imshow('img', img) cv2.waitKey(30) numContours = len(contours) possibleLines = {} midptMedian = streamMedian() if numContours > 0: for i in range(0, numContours): area = cv2.contourArea(contours[i], False) if area > 100: x, y, w, h = cv2.boundingRect(contours[i]) midPt = (x + x + w) / 2 midptMedian.insert(midPt) possibleLines[i] = [x, y, w, h] crossLineContourIndexes = [] median = midptMedian.getMedian() # print "ok, done. median is: ", median for key, val in possibleLines.iteritems(): x = val[0] w = val[2] midPt = (x + x + w) / 2 # print "MIDPT for {} is {}".format(key, midPt) if ((median - 40) <= midPt <= (median + 40)): crossLineContourIndexes.append(key) if len(crossLineContourIndexes) > 3: grovepi.digitalWrite(vibration_motor,1) #spend 3 seconds making 3 beeps for i in range(1,3): grovepi.digitalWrite(buzzer_motor,1) time.sleep(0.5) grovepi.digitalWrite(buzzer_motor,0) time.sleep(0.5) #end vibration grovepi.digitalWrite(vibration_motor,0) grovepi.digitalWrite(7,0) print "CROSSWALK DETECTED" for contour in crossLineContourIndexes: cv2.drawContours(croppedInputPhoto, contours, contour, (0,255,0), 3) cv2.imshow('FINAL IMAGE', croppedInputPhoto) cv2.waitKey(30)
def on_success(self, data): if 'text' in data: print data['text'].encode('utf-8') print # when tweet with #yes found, blink LED grovepi.digitalWrite(LED, 1) time.sleep(1) grovepi.digitalWrite(LED, 0)
def cleanup(): """Clean up at program end.""" broadcast_proc.terminate() subprocess.call('sudo hciconfig hci0 noleadv', shell=True) if CELL: ser_command('Cell off', cell_ser) cell_ser.close() grovepi.digitalWrite(LED, 0)
def set_buzzer(port, settings): try: if settings['buzz_mode'] == 'on': grovepi.digitalWrite(port, 1) elif settings['buzz_mode'] == 'off': grovepi.digitalWrite(port, 0) except ValueError: return "Not found"
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 cleanup(): print("Cleanup") try: grovepi.digitalWrite(led, 0) lcd.setRGB(0, 0, 0) lcd.setText("") fobj.close() except: pass
def message(self, pubnub, message): grovepi.digitalWrite(buzzer,1) setText(value) if message == "red": setRGB(255,0,0) elif message == "green": setRGB(0,255,0) elif message == "green": setRGB(0,0,255)
def sound(state): db_devices = MySQL('devices') buzzer = int(db_devices.get('name', 'Buzzer')[0]['code']) grovepi.digitalWrite(buzzer, state) if state == 1: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('192.168.0.47', 3458)) s.send("SOUNDGOON".encode()) db_devices.close()
def set_led(port, settings): try: # sets the LED to be the value thats passed in if settings['led_mode'] == 'on': grovepi.digitalWrite(port, 1) elif settings['led_mode'] == 'off': grovepi.digitalWrite(port, 0) except ValueError: return "Not found"
def start_radio(channel, doPlay): global color_rgb # create lock file f = open(lock_file2, 'w') f.close() if doPlay == 1: kill_mplayer() if channel > 5: channel = 2 # radio_timer.start() # else: # radio_timer.cancel() # Turn Chainable RGB LED on x = (channel * 21) / 100.0 (r, g, b) = generate_rgb_color(x) color_rgb = [r, g, b] grovepi.storeColor(r, g, b) grovepi.chainableRgbLed_pattern(rgbLEDPort, thisLedOnly, 0) print('====> color: %d, %d, %d') % (r, g, b) # If not found mplayer, run mplayer. print('====> start Radio channel: %s.') % radioChannels[channel] if channel == 0: # Bad script. But anti zombie process. cmd = "nohup sh -c \"rtmpdump --live -r %s" \ " | mplayer -novideo -af volnorm=2:%s - > /dev/null 2>&1\"" \ " > /dev/null 2>&1 &" % (radioChannels[channel], vol_agqr) subprocess.call(cmd, shell=True) else: # Bad script. But anti zombie process. if channel == 1: cmd = "nohup mplayer -af volnorm=2:%s %s" \ " > /dev/null 2>&1 &" % (vol_tko, radioChannels[channel]) else: cmd = "nohup mplayer -af volnorm=2:%s %s" \ " > /dev/null 2>&1 &" % (vol_norm, radioChannels[channel]) subprocess.call(cmd, shell=True) # subprocess.Popen( # cmd.split(), # stdout=open('/dev/null', 'w'), # stderr=open(mplayer_log, 'a'), # preexec_fn=os.setpgrp # ) else: print('====> stop Radio') kill_mplayer() # Remove lock file. os.remove(lock_file2) # Turn feedback LED off grovepi.digitalWrite(feedbackLEDPort, 0)
def switch_led(arg): global led try: # LED is against Vcc - so HIGH switches it off / LOW on if (arg == 0): grovepi.digitalWrite(led, 1) if (arg == 1): grovepi.digitalWrite(led, 0) except IOError: print("IOError communicating with HW - can and will continue though.")
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 on_message(id, value): if id.endswith(str(Led)) == True: value = value.lower() #make certain that the value is in lower case, for 'True' vs 'true' if value == "true": grovepi.digitalWrite(Led, 1) IOT.send("true", Led) #provide feedback to the cloud that the operation was succesful elif value == "false": grovepi.digitalWrite(Led, 0) IOT.send("false", Led) #provide feedback to the cloud that the operation was succesful else: print("unknown value: " + value)
def return_color(): global color_rgb # Turn LED off grovepi.digitalWrite(feedbackLEDPort, 0) # Turn RGB LED off grovepi.storeColor(color_rgb[0], color_rgb[1], color_rgb[2]) grovepi.chainableRgbLed_pattern(rgbLEDPort, thisLedOnly, 0) # Remove lock file. os.remove(lock_file3)
def handle(self, seconds): try: grovepi.pinMode(self.port, "OUTPUT") #time.sleep(1) grovepi.digitalWrite(self.port, 1) time.sleep(seconds) except IOError: print ("Error") grovepi.digitalWrite(self.port, 0)
def respond(): port = request.args["port"] value = request.args["value"] ioType = request.args["ioType"] print( 'port: ' + port ) print( 'value: ' + value ) print( 'ioType: ' + ioType ) grovepi.digitalWrite( int(port), int(value) ) return "Success\n"
def bt_process(): """Define bluetooth function that will be run as separate process.""" try: while(True): data = get_data() set_queue_data(data) broadcast(data[0]) # Diagnostic grovepi.digitalWrite(LED, data[0]) except IOError: if DEBUG: print 'IOError detected and excepted' pass
def on_message( id, value ): print id if id.endswith( str( LED ) ): value = value.lower() if value == "true": print "ON" grovepi.digitalWrite( LED, 1 ) if value == "false": print "OFF" grovepi.digitalWrite( LED, 0 )
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 on_message(id, value): if id.endswith(actuatorId1) == True: value = value.lower() #make certain that the value is in lower case, for 'True' vs 'true' if value == "true": grovepi.digitalWrite(actuatorPin1, 1) IOT.send("true", actuatorId1) #provide feedback to the cloud that the operation was succesful elif value == "false": grovepi.digitalWrite(actuatorPin1, 0) IOT.send("false", actuatorId1) #provide feedback to the cloud that the operation was succesful else: print("unknown value: " + value) elif id.endswith(actuatorId2) == True: value = value.lower() #make certain that the value is in lower case, for 'True' vs 'true' if value == "true": grovepi.digitalWrite(actuatorPin2, 1) IOT.send("true", actuatorId2) #provide feedback to the cloud that the operation was succesful elif value == "false": grovepi.digitalWrite(actuatorPin2, 0) IOT.send("false", actuatorId2) #provide feedback to the cloud that the operation was succesful else: print("unknown value: " + value) elif id.endswith(actuatorId3) == True: grovepi.analogWrite(actuatorPin3, int(value/100)) IOT.send(int(value), actuatorId3) #provide feedback to the cloud that the operation was succesful else: print("unknown actuator: " + id)
def deliver(): # Get the current uuid dic = dict(request.form) for each in dic: uuid = each break print uuid #Make sure it is in the table in DynamoDB orders=dynamodb.Table('Order') orders = orders.scan() for order in orders["Items"]: if order['ID']==uuid: if order_dict_1['status']==0: order_dict_1['status']=1 order_dict_1['ID']=uuid relay = order_dict_1['relay'] grovepi.pinMode(relay,"OUTPUT") grovepi.digitalWrite(relay,1) time.sleep(5) grovepi.digitalWrite(relay,0) apns_sns_send() print 'box 1 put in food' elif order_dict_2['status']==0: order_dict_2['status']=1 order_dict_2['ID']=uuid relay = order_dict_2['relay'] grovepi.pinMode(relay,"OUTPUT") grovepi.digitalWrite(relay,1) time.sleep(5) grovepi.digitalWrite(relay,0) print 'box 2 put in food' apns_sns_send() return 'delivery'
def actuate(client, attribute, value): if attribute == "timestamp": # Ignore the timestamp attribute, it's only for info. return print("Setting " + attribute + " to " + value + "...") if attribute == "led": # We actuate the LED for "on", "off" or "flash1". if value == "on": # Switch on LED. grovepi.digitalWrite(led, 1) send_reported_state(client, "led", "on") return elif value == "off": # Switch off LED. grovepi.digitalWrite(led, 0) send_reported_state(client, "led", "off") return elif value == "flash1": # Switch on LED, wait 1 second, switch it off. grovepi.digitalWrite(led, 1) send_reported_state(client, "led", "on") time.sleep(1) grovepi.digitalWrite(led, 0) send_reported_state(client, "led", "off") time.sleep(1) return # Show an error if attribute or value are incorrect. print("Error: Don't know how to set " + attribute + " to " + value)
def recvThread(sock): global threadFlag while threadFlag: try: cmd = sock.recv(1024) print cmd if cmd == "action": print 'action' grovepi.digitalWrite(speaker, 1) subprocess.Popen("mplayer /home/pi/Interactive_Bear/coming.mp3", shell=True) grovepi.digitalWrite(speaker, 0) except: (ErrorType, ErrorValue, ErrorTB) = sys.exc_info() print 'recv error: ', ErrorValue threadFlag = False
def respond(): port = request.args["port"] value = request.args["value"] ioType = request.args["ioType"] print( 'port: ' + port ) print( 'value: ' + value ) print( 'ioType: ' + ioType ) grovepi.digitalWrite( int(port), int(value) ) # ToDo: validate that this capability exists return "Success\n"
def detectRoad(resizedInputPhoto): print "DETECT ROAD START" croppedInputPhoto = resizedInputPhoto[len(resizedInputPhoto)/2:len(resizedInputPhoto), :] #croppedInputPhoto = croppedInputPhoto[0:len(croppedInputPhoto)/2, :] cv2.imshow('image', croppedInputPhoto) cv2.waitKey(3000) PIXEL_VARIANCE_THRESHOLD = 10.0 AREA_THRESHOLD_PERCENTAGE = 0.6 thresholdImage = cv2.cvtColor(croppedInputPhoto, cv2.COLOR_BGR2GRAY) for i in range(0,len(croppedInputPhoto)-1): for j in range(0,len(croppedInputPhoto[0])-1): #print np.var(croppedInputPhoto[i][j]) if np.var(croppedInputPhoto[i][j]) < PIXEL_VARIANCE_THRESHOLD: thresholdImage[i][j] = 255 else: thresholdImage[i][j] = 0 cv2.imshow('thresholded image', thresholdImage) cv2.waitKey(3000) #detect blobs img, contours, _ = cv2.findContours(thresholdImage, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) numberOfContours = len(contours) areaThreshold = len(croppedInputPhoto) * len(croppedInputPhoto[0]) * AREA_THRESHOLD_PERCENTAGE largestArea = 0 largestContour = 0 for i in range(0, numberOfContours): area = cv2.contourArea(contours[i], False) if area > largestArea: largestArea = area largestContour = i if numberOfContours > 0: #DEBUG cv2.drawContours(croppedInputPhoto, contours, largestContour, (0,255,0), 2) #DEBUG cv2.imshow('Road Contours', croppedInputPhoto) #DEBUG cv2.waitKey(3000) #DEBUG #make decision roadBlobDetected = False if largestArea > areaThreshold: print "ROAD DETECTED" #DEBUG grovepi.digitalWrite(vibration_motor,1) #spend 3 seconds making 3 beeps for i in range(1,3): grovepi.digitalWrite(buzzer_motor,1) time.sleep(0.2) grovepi.digitalWrite(buzzer_motor,0) time.sleep(0.2) #end vibration grovepi.digitalWrite(vibration_motor,0) else: print "NO ROAD DETECTED" #DEBUG #ret false print "ROAD DONE"
def led_write_green(value): retry = 3 while retry > 0: try: time.sleep(.2) grovepi.digitalWrite(led_green, value) break except: print 'can not write green led, retry again' retry = retry - 1 time.sleep(.2) if retry == 0: return -1 else: return 0
def led_write_blue(value): retry = 3 while retry > 0: try: grovepi.digitalWrite(led_blue, value) time.sleep(.01) break except: print 'can not write blue led, retry again' retry = retry - 1 time.sleep(.1) if retry == 0: return -1 else: return 0
import picamera import grovepi from time import sleep camera = picamera.PiCamera() counter = 0 led = 3 buzzer = 5 ultrasonic = 7 while True: try: if grovepi.ultrasonicRead(ultrasonic) < 100: print 'Intruder Detected' grovepi.analogWrite(buzzer, 100) grovepi.digitalWrite(led_status, 1) sleep(.5) grovepi.analogWrite(buzzer, 0) grovepi.digitalWrite(led_status, 0) camera.capture('image' + counter + '.jpg') print 'Image Captured' sleep(2) except IOError: print "Error"
def main(): global desired_temp_min global desired_temp_max global indoor_temp global outdoor_temp global temp global desired_temp global mode global hvac global wind_on global wind_off global i global flag read() while True: try: # Get indoor temp indoor_temp = int(get_indoor_temp()) # lcd sleep after 5 seonds time.sleep(.2) button_status = grovepi.digitalRead(button) i = i + 1 # if lcd is off turn on, if lcd is on change mode and sound buzzer # lcd sleep after 5 seconds if i < 6: if button_status: i = 0 lcd.setRGB(0,122,0) grovepi.digitalWrite(buzzer_pin, 1) time.sleep(.1) grovepi.digitalWrite(buzzer_pin, 0) if (mode <= 2): mode = mode + 1 else: mode = 0 else: lcd.setRGB(0,0,0) print("asleep") if button_status: i = 0 lcd.setRGB(0,122,0) # state machine for window if (indoor_temp > desired_temp): if (outdoor_temp < desired_temp): if hvac != "wind": # send open window client.publish("rpi-jaeishin/HVAC", str(wind_on)) print(wind_on) hvac = "wind" else: if hvac == "wind": # send close window client.publish("rpi-jaeishin/HVAC", str(wind_off)) print(wind_off) hvac = "AC" if (indoor_temp < desired_temp): if (outdoor_temp < desired_temp): if hvac == "wind": # send close window client.publish("rpi-jaeishin/HVAC", str(wind_off)) print(wind_off) hvac = "heat" else: if hvac != "wind": # send open window client.publish("rpi-jaeishin/HVAC", str(wind_on)) print(wind_on) hvac = "wind" if (indoor_temp == desired_temp): # send message close window if hvac == "wind": client.publish("rpi-jaeishin/HVAC", str(wind_off)) print(wind_off) hvac = "fan" # measure outdoor temp from API outdoor_temp = int(get_weather(DEFAULT_ZIP)) # Set LED to print in correct format #default if (mode == 1): print ("\nmode = 1 - Default") print("Temp: {:>3}F {:>4}".format(indoor_temp, hvac)) print("Desired: {:>3}F".format(desired_temp)) lcd.setText_norefresh("Temp: {:>3}F {:>4}\nDesired: {:>3}F".format(indoor_temp, hvac, desired_temp)) f=open('save.txt', 'w+') f.write(str(desired_temp)) f.close() #outdoor if (mode == 2): print("\nmode = 2 - Outdoor") print("Temp: {:>3}F {:>4}".format(indoor_temp, hvac)) print("Outdoor: {:>3}F".format(outdoor_temp)) lcd.setText_norefresh("Temp: {:>3}F {:>4}\nOutdoor: {:>3.2f}F".format(indoor_temp, hvac, outdoor_temp)) #edit if (mode == 0): print("\nmode = 0 - Edit") # get rotary angle set desired temp desired_temp = get_rotary_angle() print("Set Temp: {:>3}F".format(desired_temp)) lcd.setText_norefresh("Set Temp:{:>3}F".format(desired_temp)) except KeyboardInterrupt: lcd.setRGB(0,0,0) setText_norefresh("") break
setRGB(255, 128, 0) setText_norefresh('need water!') client.publish("project/humnotice", 1) elif hum <= 45 and hum > 30: setRGB(255, 255, 0) setText_norefresh('Not dry!') client.publish("project/humnotice", 0) elif hum <= 60 and hum > 45: setRGB(0, 255, 0) setText_norefresh('enought water!') client.publish("project/humnotice", 0) elif hum > 60: setRGB(0, 255, 255) setText_norefresh('too much water!') client.publish("project/humnotice", 0) if li <= 100: grovepi.digitalWrite( led, 1 ) #Turn on LED to supply light. In real application, it may be a larger LED or light source client.publish("project/lednotice", 1) else: grovepi.digitalWrite(led, 0) client.publish("project/lednotice", 0) time.sleep(20) except KeyboardInterrupt: # Gracefully shutdown on Ctrl-C setText('') setRGB(0, 0, 0) break
light_sensor = 0 led = 6 grovepi.pinMode(sensor, "INPUT") grovepi.pinMode(button, "INPUT") grovepi.pinMode(buzzer, "OUTPUT") grovepi.pinMode(light_sensor, "INPUT") grovepi.pinMode(led, "OUTPUT") filesveglia = open('/home/pi/sveglia.txt', 'r') onoffsveglia = open('/home/pi/onoff.txt', 'r') orasveglia = str(filesveglia.readline()) oraonoff = str(onoffsveglia.readline()) filesveglia.close() onoffsveglia.close() grovepi.digitalWrite(buzzer, 0) print orasveglia print oraonoff def restart_program(): python = sys.executable os.execl(python, python, *sys.argv) last_sound = 0 while True: try: [temp, humidity] = grovepi.dht(dht_sensor, 0)
def stop(self): grovepi.digitalWrite(self.led, 0) grovepi.digitalWrite(self.buzzer, 0)
def on_connect(self, padname): print("\nJoystick '{0}' connected".format(padname)) grovepi.digitalWrite(PIN_CONNECTLED, 0)
def play(self): grovepi.digitalWrite(self.pin, 1)
import time import grovepi # The electromagnet can hold a 1KG weight # Connect the Grove Electromagnet to digital port D4 # SIG,NC,VCC,GND electromagnet = 4 grovepi.pinMode(electromagnet, "OUTPUT") time.sleep(1) while True: try: # Switch on electromagnet grovepi.digitalWrite(electromagnet, 1) print("on") time.sleep(2) # Switch off electromagnet grovepi.digitalWrite(electromagnet, 0) print("off") time.sleep(2) except KeyboardInterrupt: grovepi.digitalWrite(electromagnet, 0) break except IOError: print("Error")
while debut != 0 : setText_norefresh("Debut de seance dans {}".format(str(debut))) debut=debut-1 time.sleep(1) textCommand(0x01) time.sleep(.1) setRGB(250,0,0) setText_norefresh("{} pompes restantes".format(str(nb))) time.sleep(.5) cpt = nb #nombre de pompe a faire au depart while cpt!=0: if grovepi.ultrasonicRead(ultrasonic_ranger)<15: cpt=cpt-1 setText_norefresh("{} pompes restantes".format(str(cpt))) time.sleep(.1) grovepi.digitalWrite(buzzer,1) time.sleep(.2) grovepi.digitalWrite(buzzer,0) time.sleep(.1) time.sleep(0.5) time.sleep(0.5) grovepi.digitalWrite(buzzer,1) time.sleep(.8) grovepi.digitalWrite(buzzer,0) //faire la messure avec le capteur de température après leffort apres = "temperature corporelle apres effort : str(tapres)" fichier = open("valeur.txt", "a") fichier.write(date + " ; " + nbe + "\n") time.sleep(.4) setText("Voulez-vous recommencez ?") time.sleep(2)
def close(relayNumber): grovepi.digitalWrite(relayNumber, 0) time.sleep(2) print(relayNumber, ".relay turned off ")
def open(relayNumber): grovepi.digitalWrite(relayNumber, 1) time.sleep(2) print(relayNumber, ".relay turned on ")
def activatePistol(): grovepi.digitalWrite(7, 1) time.sleep(3) grovepi.digitalWrite(7, 0)
# Connect the LED to digital port D4 # SIG,NC,VCC,GND led = 4 # Turn on LED once sensor exceeds threshold resistance threshold = 10 grovepi.pinMode(light_sensor,"INPUT") grovepi.pinMode(led,"OUTPUT") while True: try: # Get sensor value sensor_value = grovepi.analogRead(light_sensor) # Calculate resistance of sensor in K resistance = (float)(1023 - sensor_value) * 10 / sensor_value if resistance > threshold: # Send HIGH to switch on LED grovepi.digitalWrite(led,1) else: # Send LOW to switch off LED grovepi.digitalWrite(led,0) print("sensor_value = %d resistance =%.2f" %(sensor_value, resistance)) time.sleep(.5) except IOError: print ("Error")
# ############################################################ import time import grovepi import sys # Actuator settings buzzer = 5 # Buzzer connected to D2 port grovepi.pinMode(buzzer, "OUTPUT") while True: try: grovepi.digitalWrite(buzzer, 1) # buzzer on print "buzzer on" time.sleep(0.5) grovepi.digitalWrite(buzzer, 0) # buzzer off print "buzzer off" time.sleep(0.5) except KeyboardInterrupt: grovepi.digitalWrite(buzzer, 0) break except IOError: print "IOError" except: print "Unexpected error, continuing" print "sys.exc_info()[0]: ", sys.exc_info()[0]
import grovepi import time # digital write grovepi.digitalWrite(2, 1) grovepi.digitalWrite(2, 0) time.sleep(1) grovepi.digitalWrite(5, 0) grovepi.digitalWrite(6, 0) time.sleep(1) grovepi.digitalWrite(5, 1) grovepi.digitalWrite(6, 1) time.sleep(1) grovepi.digitalWrite(5, 0) grovepi.digitalWrite(6, 0) time.sleep(1) # read temp grovepi.temp(7) grovepi.dht(7, 0) # module_type: # DHT11 0 # DHT22 1 # DHT21 2 # DHT2301 3 # read ultrasonic grovepi.ultrasonicRead(4) import grove_rgb_lcd as lcd
def actuate(client, attribute, value, doorLocation): if attribute == "timestamp": # Ignore the timestamp attribute, it's only for info. return print("Setting " + attribute + " to " + value + "...") #From Lambda Function: g49_ActuateDoor will update G49Trace desired state. if attribute == "lockStatus": if value == "unlock": # Unlock Door. print("Authorised User") grovepi.digitalWrite(relay, 0) #open door, cut power to relay grovepi.digitalWrite(led, 0) #LED OFF - Simulate Door LED time.sleep(10) #Door left open number of seconds grovepi.digitalWrite(relay, 1) #lock door, resume power to relay grovepi.digitalWrite(led, 1) #LED ON - Simulate Door LED #Update G49Trace send_reported_state(client, attribute, value, doorLocation) return elif value == "lock": # Lock Door grovepi.digitalWrite(relay, 1) #lock door, resume power to relay grovepi.digitalWrite(led, 1) #LED ON - Simulate Door LED send_reported_state(client, attribute, value, doorLocation) return # Show an error if attribute or value are incorrect. print("Error: Don't know how to set " + attribute + " to " + value)
def stop(self): grovepi.digitalWrite(self.pin, 0)
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() # Create the beacon service for scanning beacons. beacon_service = ble.BeaconService() # Configure the Grove LED, Relay port for output. grovepi.pinMode(led, "OUTPUT") grovepi.pinMode(relay, "OUTPUT") #Supply Power to relay. Door Lock ON grovepi.digitalWrite(led, 1) 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 # Scan for beacons and add to the sensor data payload. beaconsDict = {} #For Payload beaconsArray = [] beacons_detected = beacon_service.scan(2) for beacon_address, beacon_info in list(beacons_detected.items()): # For each beacon found, add to the payload. Need to flip the bytes. beacon = { "uuid": beacon_info[0].replace('-', ''), "major": (beacon_info[1] % 256) * 256 + beacon_info[1] // 256, "minor": (beacon_info[2] % 256) * 256 + beacon_info[2] // 256, "power": beacon_info[3], "rssi": beacon_info[4], "address": beacon_address } uuid_temp = beacon_info[0].replace('-', '') address_temp = beacon_address major_temp = (beacon_info[1] % 256) * 256 + beacon_info[1] // 256 minor_temp = (beacon_info[2] % 256) * 256 + beacon_info[2] // 256 #Add each beacon to the Dictionary beaconsArray.append(beacon) # Prepare our sensor data in JSON format. # Send reported state to g49pi payload = { "state": { "reported": { "beacons": beaconsArray, "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 15 seconds before sending the next set of sensor data. i.e. Beacons detected time.sleep(15) except KeyboardInterrupt: # Stop the program when we press Ctrl-C. grovepi.digitalWrite(relay, 1) #lock door, resume power to relay grovepi.digitalWrite(led, 1) #LED ON - Simulate Door LED break except Exception as e: # For all other errors, we wait a while and resume. print("Exception: " + str(e)) time.sleep(10) continue
def on(self): """ Turns buzzer on. :return: None """ grovepi.digitalWrite(self.pin, 1) # Send high to switch on buzzer
def trigger_outputs(status): global io grovepi.digitalWrite(int(io['output']['buzzer']), int(status)) grovepi.digitalWrite(int(io['output']['rled']), int(status)) grovepi.digitalWrite(int(io['output']['gled']), int(status))
def start(self): grovepi.digitalWrite(self.led, 1) grovepi.digitalWrite(self.buzzer, 1)
def deactivate_heating(): print('thermostat off') grovepi.digitalWrite(RELAY_PIN, 0)
def activate_heating(): print('thermostat on') grovepi.digitalWrite(RELAY_PIN, 1)
# http://www.seeedstudio.com/wiki/Grove_-_2-Coil_Latching_Relay import time import grovepi # Contrast to the ordinary relay, this latching relay does not need continuous power to keep the state, which makes it especially low power consumption # Connect the Grove 2-Coil Latching Relay to digital port D4 # SIG,NC,VCC,GND relay = 4 grovepi.pinMode(relay,"OUTPUT") while True: try: # switch on for 5 seconds grovepi.digitalWrite(relay,1) print "on" time.sleep(5) # switch off for 5 seconds grovepi.digitalWrite(relay,0) print "off" time.sleep(5) except KeyboardInterrupt: grovepi.digitalWrite(relay,0) break except IOError: print "Error"
firebase = firebase.FirebaseApplication( 'https://iotwater-cc1f2.firebaseio.com/', None) initTime = time.time() while True: motor_state = firebase.get('/iot-garden-monitoring-system', 'motor_state') update = firebase.get('/iot-garden-monitoring-system', 'update') pi_state = firebase.get('/iot-garden-monitoring-system', 'pi_state') # print("update :",update,"momo",motor_state,"pi_state ",pi_state) # print("received data in ", int(time.time() - initTime), "seconds") initTime = time.time() if (pi_state == str("0")): grovepi.digitalWrite(motor, 0) # break [temp, humidity] = grovepi.dht(dht_sensor, 0) light = grovepi.analogRead(light_sensor) moisture = grovepi.analogRead(moisture_sensor) light = 100 * light / 1023 moisture = 100 - (100 * moisture / 1023) m = moisture if (m > 70.0 or m < 3.0): warning = "o" grovepi.digitalWrite(ledwarn, 1) if (m < 70.0 and m > 3.0): warning = "x" grovepi.digitalWrite(ledwarn, 0)
temp_humidity_sensor = 2 #Temp./Luftf.-Sensor: D2 water_relay = 7 #Wasserpumpe-Relais: D7 light_relay = 4 #Licht-Relais auf Port D4 servopin = 17 #Servomotor an GPIO17 (+ Stromquelle und Masse) ################################## SETUP ########################################################### ## die GrovePi Anschlüsse, Kamera werden vorbereitet und eingestellt. ############################## ## Es wird ein Objekt mit den Anmeldedaten für Tweepy erstellt###################################### #GrovePi-Ports als Output festlegen grovepi.pinMode(water_relay,"OUTPUT") grovepi.pinMode(light_relay, "OUTPUT") #GrovePi-Outputs auf "0" setzen grovepi.digitalWrite(water_relay,0) grovepi.digitalWrite(light_relay,1) #Servomotor: Anschlüsse definieren gpio.setmode(gpio.BCM) gpio.setup(servopin, gpio.OUT) servo = gpio.PWM(servopin, 50) #Kamera-Vorbereitung camera = picamera.PiCamera() #Twitter-Anmeldung (Tweepy) auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) apitweepy = tweepy.API(auth)
try: # setRGB(255,255,255) # white # strg = "Greenhouse Data" # print strg # for i in range(0,16): # setText(strg[:i]) # time.sleep(.2) time.sleep(1) # Get temperature and humidity sensor value. First read might give previous residual value light_sensor_value = grovepi.analogRead(light_sensor) if light_sensor_value==0: light_sensor_value=1 resistance = (float)(1023 - light_sensor_value) * 10 / light_sensor_value now=datetime.datetime.now() # Vcc Timing first 5 minutes of every hour if now.minute<15:# and now.minute<46: grovepi.digitalWrite(Vcc,1) else: grovepi.digitalWrite(Vcc,0) # Read sensor value from moisture sensor moisture = grovepi.analogRead(moisture_sensor) time.sleep(1) moisture = grovepi.analogRead(moisture_sensor) if moisture<100: moisture=0 else: moisture=int(((1023-moisture)/10.23)) time.sleep(1) #2 second delay for sensor stability. Total delay is capture_interval + 2 [temp,humidity] = grovepi.dht(temp_humidity,1) # gas = grovepi.analogRead(gas_sensor) time.sleep(1) #second read done to get fresh value
def shutdown_board(): """Turns off LEDs and clears LCD screen""" grovepi.digitalWrite(RED_LED, OFF) grovepi.digitalWrite(GREEN_LED, OFF) grove_rgb_lcd.setRGB(0, 0, 0) grove_rgb_lcd.setText_norefresh("")
import time import grovepi analogInDatPin = 0 heaterSelPin = 15 sensorValue = 0 RS_air = 0 #grovepi.pinMode(heaterSelPin,"OUTPUT") grovepi.digitalWrite(heaterSelPin, 0) #/*--- Get a average data by testing 100 times ---*/ for x in range(1,100): sensorValue = sensorValue + grovepi.analogRead(analogInDatPin) time.sleep(0.1) sensorValue = sensorValue/100.0 print("sensor value:") print(sensorValue) #/*-----------------------------------------------*/ sensor_volt = sensorValue/1024*5.0 RS_air = sensor_volt/(5.0-sensor_volt); #// omit *R16 print("sensor_volt = ") print(sensor_volt) print("V") print("RS_air = ") print(RS_air)
def action(location, deviceName, action): global heater_state, ac_state, ventilation_state, light_intensity status = False if location == '353': if deviceName == 'ac': if action == "on": setRGB(0, 0, 255) ac_state = on_state heater_state = off_state status = True if action == "off": setRGB(212, 235, 255) ac_state = off_state status = True if deviceName == 'heater': if action == "on": setRGB(255, 128, 0) heater_state = on_state ac_state = off_state status = True if action == "off": setRGB(212, 235, 255) heater_state = off_state status = True if deviceName == 'vent': if action == "on": ventilator_state = on_state status = True if action == "off": ventilator_state = off_state status = True if deviceName == 'iaqwarn': if action == "on": grovepi.digitalWrite(led_port, 1) status = True if action == "off": grovepi.digitalWrite(led_port, 0) status = True if deviceName == 'light': if action == "on": light_intensity = on_state status = True if action == "off": light_intensity = off_state status = True if location == 'meeting': if deviceName == 'projector': if action == "on": print("Projector ON") circleplus.switch_on() status = True if action == "off": print("Projector OFF") circleplus.switch_off() status = True if deviceName == 'blind': if action == "on": print("Blinds open") status = True if action == "off": print("Blinds Close") status = True if deviceName == 'light': if action == "on": circle.switch_on() status = True if action == "off": circle.switch_off() status = True updateDisplay() return {"status": status}