def action(changePin, action): # Convert the pin from the URL into an integer: changePin = int(changePin) # Get the device name for the pin being changed: deviceName = gpioPins[changePin]['nom'] # If the action part of the URL is "high," execute the code indented below: if action == "high": # Set the pin high: gpio.output(changePin, gpio.HIGH) # Save the status message to be passed into the template: message = "Turned " + deviceName + " high." if action == "low": gpio.output(changePin, gpio.LOW) message = "Turned " + deviceName + " low." if action == "toggle": # Read the pin and set it to whatever it isn't (that is, toggle it): gpio.output(changePin, not gpio.input(changePin)) message = "Toggled " + deviceName + "." # For each pin, read the pin state and store it in the pins dictionary: for pin in gpioPins: gpioPins[pin]['etat'] = gpio.input(pin) # Along with the pin dictionary, put the message into the template data dictionary: templateData = { 'message' : message, 'gpioPins' : gpioPins } return redirect('/debogage')
def distance(measure): gpio.setmode(gpio.BOARD) gpio.setup(TRIG, gpio.OUT) gpio.setup(ECHO, gpio.IN) gpio.output(TRIG, False) gpio.output(TRIG, True) time.sleep(0.00001) gpio.output(TRIG, False) sig = 0 nosig = 0 while gpio.input(ECHO) == 0: nosig = time.time() while gpio.input(ECHO) == 1: sig = time.time() if nosig != None and sig != None: tl = sig - nosig distance = tl * 17150 distance = round(distance, 2) gpio.cleanup() return distance
def run(location, poll_interval=60): """The application loop for the Fermonitor service. Runs infinitely until terminated, Ctrl+C on the Pi.""" db = DbRepo() while True: try: # Get the next reading n, c, f, h = read() except Exception: print('oops') continue # Get the current state of the PST switch; 1 = on, 0 = off pst = GPIO.input(pst_pin) # Save it to the database log db.add_measurement(n, location, c, f, h, pst) print(c, f, h, pst) # Read the current target temperature from config in the DB target_c = db.get_target_temp() if target_c: # If configured, maintain the target temperature if pst: # Heater is on if c >= target_c + 1: # heat to +1C to prevent frequent cycling GPIO.output(pst_pin, False) else: # heater is off if c < target_c: # turn heater on when we drop below target temp GPIO.output(pst_pin, True) else: # no target temp is configured, ensure heater is off if GPIO.input(pst_pin): GPIO.output(pst_pin, False) # Sleep until the next interval sleep(poll_interval)
def run(self): while not self.terminate: failed = False time.sleep(.1) GPIO.output(self.trigger_pin, True) time.sleep(0.00001) GPIO.output(self.trigger_pin, False) timeout = time.time() while GPIO.input(self.echo_pin) == 0: start = time.time() if time.time() - timeout > .5: failed = True break timeout = time.time() while GPIO.input(self.echo_pin) == 1: stop = time.time() if time.time() - timeout > .5: failed = True break if not failed: self.out[0] = int(10 * self.size / (stop - start)) self.finish_terminated = True
def main(): #Set up pins for GPIO output GPIO.setmode(GPIO.BCM) #Use BCM GPIO numbers GPIO.setup(LCD_E,GPIO.OUT) GPIO.setup(LCD_RS,GPIO.OUT) GPIO.setup(LCD_D4,GPIO.OUT) GPIO.setup(LCD_D5,GPIO.OUT) GPIO.setup(LCD_D6,GPIO.OUT) GPIO.setup(LCD_D7,GPIO.OUT) #Set up buttons for GPIO input GPIO.setup(BTN1, GPIO.IN) GPIO.setup(BTN2, GPIO.IN) #Initialize LCD Display lcd_init() #Display introductory message to_write = [LCD_FILLER, str_format_left("Raspberry Pi"), str_format_left("GPIO Test"), LCD_FILLER] lcd_write_lines(to_write) time.sleep(5) #run infinite loop that displays different messages for different button presses while True: if (GPIO.input(BTN1) == True): to_write = [LCD_FILLER, str_format_left("You hit"), str_format_left("Button 1"), LCD_FILLER] lcd_write_lines(to_write) time.sleep(1) if (GPIO.input(BTN2) == True): to_write = [LCD_FILLER, str_format_left("You hit"), str_format_left("Button 2"), LCD_FILLER] lcd_write_lines(to_write) time.sleep(1)
def read_data(): base=0 data=[] # reset GPIO.setmode(GPIO.BCM) GPIO.setup( DHT11_DATA_PIN , GPIO.OUT) GPIO.output( DHT11_DATA_PIN , GPIO.LOW) time.sleep(0.03) # 必须大于18ms GPIO.setup( DHT11_DATA_PIN , GPIO.IN) while GPIO.input( DHT11_DATA_PIN ) == GPIO.HIGH: continue while GPIO.input( DHT11_DATA_PIN ) == GPIO.LOW: continue # 固定拉高80us,可用来做基准 while GPIO.input( DHT11_DATA_PIN ) == GPIO.HIGH: base += 1 continue base = base / 2 # Get data while len(data)< DHT11_DATA_LEN*8: i = 0 # 检测50us以上的低位 while GPIO.input( DHT11_DATA_PIN ) == GPIO.LOW: continue # 此时电平为高,持续26-28us表示0,否则持续70us表示1 while GPIO.input( DHT11_DATA_PIN ) == GPIO.HIGH: i += 1 if i > 100: #最后一个数据也许不会拉低,手动判断 break if i < base: data.append(0) else: data.append(1) print("DHT11 get data: ", data) return data
def action(changePin, action): # Convert the pin from the URL into an integer: changePin = int(changePin) # Get the device name for the pin being changed: deviceName = pins[changePin]['name'] # If the action part of the URL is "on," execute the code indented below: if action == "on": # Set the pin high: GPIO.output(changePin, GPIO.HIGH) # Save the status message to be passed into the template: message = "Turned " + deviceName + " on." if action == "off": GPIO.output(changePin, GPIO.LOW) message = "Turned " + deviceName + " off." if action == "toggle": # Read the pin and set it to whatever it isn't (that is, toggle it): GPIO.output(changePin, not GPIO.input(changePin)) message = "Toggled " + deviceName + "." # For each pin, read the pin state and store it in the pins dictionary: for pin in pins: pins[pin]['state'] = GPIO.input(pin) # Along with the pin dictionary, put the message into the template data dictionary: templateData = {'message' : message, 'pins' : pins } return render_template('main.html', **templateData)
def main(): a=random.randint(1,10) preguntas() res=respuestas() while True: if(GPIO.input(7)): if(res==1): print "\nCorrecto! :)" if(res!=1): print "\nError :o" main() if(GPIO.input(8)): if(res==2): print "\nCorrecto! :)" if(res!=2) print "\nError :o" main() if(GPIO.input(9)): if(res==3): print "\nCorrecto! :)" if(res!=3) print "\nError :o" time.sleep(5) clear_output() main()
def safety_callback(channel): try: code="" type="" if(GPIO.input(2) == GPIO.LOW): #todo type="emergency" serial.flushInput() serial.write("M730\r\n") reply=serial.readline() try: code=float(reply.split("ERROR : ")[1].rstrip()) except: code=100 if(GPIO.input(2) == GPIO.HIGH): #to do type="" code="" message = {'type': str(type), 'code': str(code)} ws.send(json.dumps(message)) write_emergency(json.dumps(message)) except Exception, e: logging.info(str(e))
def writeByte(self, data): for i in range(0, 8): IO.output(self.__Clkpin, LOW) if (data & 0x01): IO.output(self.__Datapin, HIGH) else: IO.output(self.__Datapin, LOW) data = data >> 1 IO.output(self.__Clkpin, HIGH) # endfor # wait for ACK IO.output(self.__Clkpin, LOW) IO.output(self.__Datapin, HIGH) IO.output(self.__Clkpin, HIGH) IO.setup(self.__Datapin, INPUT) while (IO.input(self.__Datapin)): time.sleep(0.001) if (IO.input(self.__Datapin)): IO.setup(self.__Datapin, OUTPUT) IO.output(self.__Datapin, LOW) IO.setup(self.__Datapin, INPUT) # endif # endwhile IO.setup(self.__Datapin, OUTPUT)
def main(): # tell the GPIO module that we want to use the # chip's pin numbering scheme GPIO.setmode(GPIO.BCM) # setup pin 25 as an output GPIO.setup(17,GPIO.IN) GPIO.setup(18,GPIO.IN) while True: if GPIO.input(17): print "Vision Api activated" try: rc = subprocess.call("cd /home/pi/unblind && sh /home/pi/unblind/visionapi.sh && cd -", shell=True) except OSError as e: print( e ) print "button17 true" if GPIO.input(18): print "OCR Api activated" try: rc = subprocess.call("cd /home/pi/unblind && sh /home/pi/unblind/ocr.sh && cd -", shell=True) except OSError as e: print( e ) print "button18 true" time.sleep(0.1) GPIO.cleanup()
def sonar(): while finished != True: global globalstop GPIO_TRIGGER = 8 GPIO_ECHO = 8 GPIO.setup(8, GPIO.OUT) # Send 10us pulse to trigger GPIO.output(GPIO_TRIGGER, True) time.sleep(0.00001) GPIO.output(GPIO_TRIGGER, False) start = time.time() count = time.time() GPIO.setup(8, GPIO.IN) while GPIO.input(GPIO_ECHO) == 0 and time.time() - count < 0.1: start = time.time() stop = time.time() while GPIO.input(GPIO_ECHO) == 1: stop = time.time() # Calculate pulse length elapsed = stop - start # Distance pulse travelled in that time is time # multiplied by the speed of sound (cm/s) distance = elapsed * 34000 # That was the distance there and back so halve the value distance = distance / 2 if distance < 20: globalstop = 1 print("Too close") else: globalstop = 0 print("Far") time.sleep(1)
def manageInputs(): print "Setting the switches to inputs" GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) #Set pull-ups to pins GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(6, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Read inputs just one time input_state_5 = GPIO.input(5) input_state_26 = GPIO.input(26) input_state_19 = GPIO.input(19) input_state_13 = GPIO.input(13) input_state_6 = GPIO.input(6) GPIO.setmode(GPIO.BCM) GPIO.setup(LED1, GPIO.OUT) GPIO.setup(LED2, GPIO.OUT) GPIO.setup(LED3, GPIO.OUT) GPIO.setup(LED4, GPIO.OUT) GPIO.setup(LED5, GPIO.OUT) GPIO.setup(LED6, GPIO.OUT) GPIO.setup(LED7, GPIO.OUT) GPIO.setup(LED8, GPIO.OUT) GPIO.setup(LED9, GPIO.OUT)
def func_publish(): counter = 0 ir_flag = 0; occ_flag = 0; global led global occ global lock global ir print '(Thread 2) Working...' while 1: if doorservo.locked: lock = 1 else: lock = 0 def callback1(m): print 'Object Detected. (IR)' def callback2(m): print 'No Object Detected. (IR)' if(occ_flag == 0): if motion_detector.occ: print "OCCUPIED" occ = 1 update_data() occ_flag = 1 pubnub.publish(channel, data, callback=callback1, error=callback1) else: if motion_detector.occ == False : print "NOT OCCUPIED" occ = 0 update_data() occ_flag = 0 pubnub.publish(channel, data, callback=callback1, error=callback1) if(ir_flag == 0): if(GPIO.input(IR_PIN) == 0): counter = 0 ir = 0 update_data() pubnub.publish(channel, data, callback=callback1, error=callback1) ir_flag = 1 else: if(GPIO.input(IR_PIN) == 1): if counter >= 60: # notify_by_mail('*****@*****.**', 'The door is open.') counter = 0 ir = 1 update_data() pubnub.publish(channel, data, callback=callback2, error=callback1) ir_flag = 0 counter = 0 time.sleep(0.2) if ir_flag: if counter < 100: counter = counter + 1 if counter == 60: print 'Mail mode activated'
def read_data(n,read_interval): total = 0 start_time = time.time() previous_state = 0 current_state = 0 for i in range(n): total = total + 1 print total time.sleep(read_interval) while current_state != previous_state: if current_state == 0: time.sleep(read_interval) if GPIO.input(4) == 1: current_state = 1; if current_state == 1: time.sleep(read_interval) if GPIO.input(4) == 0: current_state = 0; while previous_state == current_state: time.sleep(read_interval) if GPIO.input(4) != current_state: current_state = GPIO.input(4) return time.time() - start_time
def handleLightChange(data): roomId = data['roomId'] state = data['state'] pinNumber = pins['light'][roomId][0][0]['pinNumber'] if state == 1: GPIO.output(pinNumber, GPIO.HIGH) if state == 0: GPIO.output(pinNumber, GPIO.LOW) for states in pins['light'].itervalues(): for pinState in states[0]: pinState['state'] = GPIO.input(pinState['pinNumber']) states[1]['overallState'] = GPIO.input(states[0][0]['pinNumber']) emit('serverResponse', { 'type': 'light', 'roomId': roomId, 'state': pins['light'][roomId][1]['overallState'] }, broadcast=True) print "Light change!" return
def suppressFire_callback(channel,flag=0): # print GPIO.input(channel), channel # print GPIO.input(24), 24 # print 'callback' if not flag: print 'UVTron just told me about a fire!', GPIO.input(channel) x,y = nan, nan while isnan(x) or isnan(y): print 'no fire in frame yet' # Need to do some sort of check to filter out random spikes here ti = time.time() while GPIO.input(channel): print 'signal went high for some reason' if time.time() - ti >= 0.01: print "Something may be wrong with the UVTron signal" return # FireImage = abs(average(ImQueue[-1],-1) - average(ImQueue[0],-1)) print 'grabbing an image' FireImage = average(ImQueue[0],-1) x,y = findFire(FireImage) # print x,y # fo = '-'.join(map(str, datetime.now().timetuple()[:6])) # imwrite('fire'+fo+'.bmp',FireImage) xdivtmp, ydivtmp = xdivs[:], ydivs[:] bisect.insort(xdivtmp,x) # Insert the fire coordinates into the protection grid bisect.insort(ydivtmp,y) xzone = xdivtmp.index(x) - 1 # Find the grid coordinates yzone = ydivtmp.index(y) - 1 # print 'fire seen in %d,%d' % (xzone,yzone) del xdivtmp, ydivtmp print 'putting out fire' firePorts((xzone,yzone)) print 'Fire at (%.2f,%.2f) in zone %d,%d\nFiring ports %d & %d' % ((x,y,xzone,yzone,) + fireDict[(xzone,yzone)])
def sonar(n): # Send 10us pulse to trigger GPIO.output(GPIO_TRIGGER, True) time.sleep(0.00001) GPIO.output(GPIO_TRIGGER, False) start = time.time() # this doesn't allow for timeouts ! while GPIO.input(GPIO_ECHO)==0: start = time.time() while GPIO.input(GPIO_ECHO)==1: stop = time.time() # Calculate pulse length elapsed = stop-start # Distance pulse travelled in that time is time # multiplied by the speed of sound (cm/s) distance = elapsed * 34000 # That was the distance there and back so halve the value distance = distance / 2 return distance
def on_pedal_change(self, channel): time.sleep(0.02) if not GPIO.input(channel): return if self.last_pedal_press is not None and time.time() - self.last_pedal_press < 0.2: return logging.info("pedal change: %d", channel) t0 = time.time() while GPIO.input(channel): self.last_pedal_press = time.time() if self.last_pedal_press - t0 > hold_time: break time.sleep(0.01) if time.time() - t0 > hold_time: self.toggle_rec() elif self.recording: self.set_mark(pedal_id=0) self.last_pedal_press = time.time()
def start(): last = GPIO.input(button) while True: val = GPIO.input(button) if val != last: last = val if val == 1 and recorded == True: print 'Push button...' rf = open(path+'recording.wav', 'w') rf.write(audio) rf.close() inp = None alexa() elif val == 0: GPIO.output(25, GPIO.HIGH) inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device) inp.setchannels(1) inp.setrate(16000) inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) inp.setperiodsize(500) audio = "" l, data = inp.read() if l: audio += data recorded = True print 'Recording...' elif val == 0: l, data = inp.read() if l: audio += data
def sensor_get_value(self): GPIO.setup(self.read_pin_1, GPIO.IN) GPIO.setup(self.read_pin_2, GPIO.IN) read_val_1 = GPIO.input(self.read_pin_1) read_val_2 = GPIO.input(self.read_pin_2) # Invert the values, so that True means something is close return [not read_val_1, not read_val_2]
def activation_main2(): GPIO.setup(right_button, GPIO.IN, GPIO.PUD_UP) GPIO.setup(left_button, GPIO.IN, GPIO.PUD_UP) try: while True: alarmstatus = getAlarm() if alarmstatus == 1: GPIO.output(RedLed, 1) GPIO.output(GreenLed, 0) else: GPIO.output(GreenLed, 1) GPIO.output(RedLed, 0) if GPIO.input(right_button) == False: setAlarm2(1) sendNotification(getToken(getUsername())) if GPIO.input(left_button) == False: setAlarm2(0) except KeyboardInterrupt: GPIO.cleanup()
def main(): GPIO_INIT() #Sets up the GPIO Pins print "system on" try: while True: if (GPIO.input(23)==False): #WHILE the door is closed the progran will check the temperature if GPIO.input(14): print "ir sensor tripped" check_temp_state() ir_sensor_callback() sleep(1) else: print "sensor not tripped" #function call to check temperature sleep(3) else: print "door open" sleep(10) except KeyboardInterrupt: print "" print "Goodbye, have a nice day" finally: GPIO.cleanup()
def __init__(self, pin_a, pin_b, pin_sw=None, **opts): """Connect A/B to digital pins and common to the GND. Options ~~~~~~~ min_pos - minimal rotary position (default=unlimited) max_pos - maximal rotary position (default=unlimited) position - initial rotary position debounce - debounce time (default=10)""" HilgaObject.__init__(self, **opts) # self.hm = HilgaMixer() self.min_pos = opts.get('min_pos', None) self.max_pos = opts.get('max_pos', None) self.position = opts.get('position', 0) self.pqueue = eventlet.Queue() self.pin_a = pin_a self.pin_b = pin_b self.pin_sw = pin_sw # Setup rotary pins GPIO.setup(self.pin_a, GPIO.IN, GPIO.PUD_UP) GPIO.setup(self.pin_b, GPIO.IN, GPIO.PUD_UP) self._levels = {pin_a: GPIO.input(self.pin_a), pin_b: GPIO.input(self.pin_b)} GPIO.add_event_detect(self.pin_a, GPIO.BOTH, callback=self.pin_pulse, bouncetime=self.opts.get('debounce', 10)) GPIO.add_event_detect(self.pin_b, GPIO.BOTH, callback=self.pin_pulse, bouncetime=self.opts.get('debounce', 10)) # Setup switch pin if self.pin_sw: GPIO.setup(self.pin_sw, GPIO.IN)#, GPIO.PUD_UP) GPIO.add_event_detect(self.pin_sw, GPIO.BOTH, callback=self.pin_switch, bouncetime=120)
def posibilidad(): GPIO.setwarnings(False) cuenta=0 while True: if(GPIO.input(2)): cuenta=cuenta+1 print"boton 1" if(GPIO.input(3)): cuenta=0 print"boton 2" if(GPIO.input(4)): cuenta=cuenta-1 print"boton 3" if(cuenta>6): GPIO.output(17,True) GPIO.output(27,False) GPIO.output(22,False) if(cuenta>4): GPIO.output(27,True) GPIO.output(17,False) GPIO.output(22,False) if(cuenta>1): GPIO.output(22,True) GPIO.output(17,False) GPIO.output(27,False)
def doorLockInput(): #키패드 입력값 확인 함수 #print "doorLock Input" global rows global cols matrix=[[1,2,3], #어떤 버튼인지 확인하기 위한 매트릭스 [4,5,6], [7,8,9], ['*',0,'#']] try: for j in xrange(0,3,1): gpio.output(cols[j],False) for i in xrange(0,4,1): if gpio.input(rows[i])==0: print matrix[i][j] while gpio.input(rows[i])==0: pass return matrix[i][j] #키패드값 리턴 gpio.output(cols[j],True) return None except KeyboardInterrupt: gpio.cleanup() exit()
def hello(): if not DEBUG: GPIO.setup(4, GPIO.IN) womens_occupied = not (GPIO.input(4)) GPIO.setup(22, GPIO.IN) mens_occupied = not (GPIO.input(22)) else: mens_occupied = DEBUG_MENS womens_occupied = DEBUG_WOMENS if mens_occupied: if womens_occupied: favicon = "both_occupied" else: favicon = "men_occupied_women_empty" else: if womens_occupied: favicon = "men_empty_women_occupied" else: favicon = "both_empty" templateData = { "favicon": favicon, "title": "ToiletPi", "womens_occupied": womens_occupied, "mens_occupied": mens_occupied, } return render_template("main.html", **templateData)
def getDistance(sonarTrigger, sonarEcho): #using BCM GPIO reference GPIO.setmode(GPIO.BCM) GPIO.setup(sonarTrigger, GPIO.OUT) GPIO.setup(sonarEcho, GPIO.IN) GPIO.output(sonarTrigger, True) time.sleep(0.00001) GPIO.output(sonarTrigger, False) sent = time.time() time.sleep(0.5) while GPIO.input(sonarEcho)==0: sent = time.time() while GPIO.input(sonarEcho)==1: returned = time.time() #Calculate time elapsed = returned-sent distance = elapsed * 34300 / 2 return distance
def runSonar(self): #Move the servo if self.ServoDirection == "UP": self.ServoPosition = self.ServoPosition + self.ServoStep if self.ServoPosition >= self.ServoMax: self.ServoPosition= self.ServoMax self.ServoDirection = "DOWN" if self.ServoDirection == "DOWN": self.ServoPosition = self.ServoPosition - self.ServoStep if self.ServoPosition <= self.ServoMin: self.ServoPosition= self.ServoMin self.ServoDirection = "UP" self.MoveServo(self.ServoPosition) time.sleep(0.05) GPIO.output(self.TRIG,1) time.sleep(0.00001) GPIO.output(self.TRIG,0) while GPIO.input(self.ECHO) == 0: pass start = time.time() while GPIO.input(self.ECHO) == 1: pass stop = time.time() self.Label_Distance["text"] = "%.2fcm" % round((float(stop-start) * 17000), 2)
def IRread(one, two, three): # Read sensor input and print some diagnostics #read left sensor GPIO.setup(one, GPIO.OUT) GPIO.output(one, True) one_start = time.time() GPIO.setup(one, GPIO.IN) while GPIO.input(one) == 1: one_end = time.time() #read middle sensor GPIO.setup(two, GPIO.OUT) GPIO.output(two, True) two_start = time.time() GPIO.setup(two, GPIO.IN) while GPIO.input(two) == 1: two_end = time.time() #read right sensor GPIO.setup(three, GPIO.OUT) GPIO.output(three, True) three_start = time.time() GPIO.setup(three, GPIO.IN) while GPIO.input(three) == 1: three_end = time.time() one_pulse = (one_end-one_start)*1000 two_pulse = (two_end-two_start)*1000 three_pulse = (three_end-three_start)*1000 return (one_pulse,two_pulse,three_pulse)
from time import sleep from datetime import datetime import os GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN) GPIO.setup(27, GPIO.OUT) i = 1 filename = "Test-" + str(datetime.now()) + "Log.csv" def write_time(i, Time1): with open(filename, "a") as log: log.write("{0},{1}\n".format(i, str(Time1))) try: while True: if GPIO.input(17) == GPIO.LOW: dt = datetime.now() print i, dt write_time(i, dt) i = i + 1 sleep(0.3) except KeyboardInterrupt: print "Exception: KeyboardInterrupt" finally: GPIO.cleanup()
def is_on(self): return GPIO.input(self.pin) == 1
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) PIN = 15 GPIO.setup(PIN, GPIO.IN) def Motion(Pin): print "Motion Detected" time.sleep(2) print "Ready" while 1: if GPIO.input(PIN): print "motion detected" time.sleep(1)
elif char == ord('z'): while True: GPIO.output(10,True) GPIO.output(16,True) GPIO.output(18,True) GPIO.output(8,False) GPIO.output(3,False) GPIO.output(5,False) while True: GPIO.output(11,True) time.sleep(0.0001) GPIO.output(11,False) while GPIO.input(13) == False: start = time.time() while GPIO.input(13) == True: end = time.time() sig_time = end-start #cm: distance = sig_time / 0.000058 print('Distance: {} cm'.format(distance)) if distance < 20: break GPIO.output(8,True) GPIO.output(16,True)
TRIG = 16 GPIO.setup(TRIG, GPIO.OUT) GPIO.setup(ECHO, GPIO.IN) try: while True: GPIO.output(TRIG, 0) time.sleep(0.00001) GPIO.output(TRIG, 1) time.sleep(0.00001) GPIO.output(TRIG, 0) start = time.time() # print("1") while GPIO.input(ECHO) == 0: start = time.time() # print("2") while GPIO.input(ECHO) == 1: stop = time.time() # print("3") distance = (stop - start) * 34000 / 2 print distance except KeyboardInterrupt: GPIO.cleanup()
from timeit import default_timer as timer import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) pins = [3, 5, 3] GPIO.setup(pins, GPIO.IN) while 1: if GPIO.input(3): start = timer() if GPIO.input(5): end = timer() time.sleep(0.3) print(end - start)
import os import time import RPi.GPIO as GPIO PIN_READ = 23 GPIO.setmode(GPIO.BCM) # Button to GPIO23 GPIO.setup(PIN_READ, GPIO.IN, pull_up_down=GPIO.PUD_UP) command_sound = "/home/sam/source/vader/play-random-sound.sh &" #command = "sudo python /home/sam/source/vader/servo-one-cycle.py" command = "python /home/sam/source/vader/servo-one-cycle-pigpio.py" try: while True: button_state = GPIO.input(23) if not button_state: # print "%s\tButton pressed..." % datetime.datetime.now() os.system(command_sound) os.system(command) time.sleep(0.2) except Exception as exception: print exception finally: GPIO.cleanup()
def isJmp1(): if not GPIO.input(JMP1): return True else: return False
url = '' # Activate GPIO pins GPIO.setmode(GPIO.BOARD) for pin in pins: GPIO.setup(pin,GPIO.IN,pull_up_down=GPIO.PUD_UP) def notify_slack(data): print "Sending Slack message" req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_page = response.read() while(1): try: if GPIO.input(zone1) == 0 and GPIO.input(zone2) == 0 and GPIO.input(zone4) == 0: print "Roboguard not connected" sleep(5) continue if GPIO.input(zone1) == 0: zone = "1" zone_info = "Zone 1" zone_data["text"] = zone_info + " - Zone" + zone json_data = (json.dumps(zone_data, ensure_ascii=False)) print (zone_info + " - Zone" + zone) notify_slack(json_data) if GPIO.input(zone2) == 0: zone = "2"
def isJmp2(): if not GPIO.input(COVER): return True else: return False
GPIO.output(4, GPIO.LOW) time.sleep(0.0031) while True: temp = ReadInput(0) move = ReadInput(1) dust = ReadInput(2) PI = ReadInput(4) print('Temp = ' + str(ConvertVolts(temp, 4) * 100)) print('Dust = ' + str(ConvertVolts(dust, 4))) ########LIGHT######## cnt1 = 0 while cnt1 == 0: if GPIO.input(18) == 0: while GPIO.input(18) == 0: d = 2 t = time.time() while GPIO.input(18) == 1: d = 2 while GPIO.input(18) == 0: d = 2 durata_perioada = time.time() - t cnt1 = cnt1 + 1 f = 1 / durata_perioada print('Lumina = ' + str(math.trunc(f))) ############################## if (move < 512): print("fara miscare")
GPIO.setmode(GPIO.BOARD) GPIO.setup(sensorPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) prevState = False currState = False cam = picamera.PiCamera() cam.resolution = (1296, 730) cam.framerate = 25 #cam.exposure_mode = 'off' while True: time.sleep(.1) prevState = currState currState = GPIO.input(sensorPin) if currState != prevState: #logging.info("GPIO pin {0} is {1}".format(sensorPin, "HIGH" if currState else "LOW")) if currState: fileName = getFileName() #annotate video with text timestamp #cam.annotate_text = fileName #start recording cam.start_recording(fileName, format='h264', quality=23) else: #stop recording cam.stop_recording() #get filesize and if too small (short clip) or too large delete fileSize = os.path.getsize('%s' % fileName) if (fileSize < 5000000): #logging.info("Deleting %s because fileSize of %s less than 2MB or greater 15MB" % (fileName, fileSize))
def button_event(self, button): if GPIO.input(button): event = self.BUTTONUP else: event = self.BUTTONDOWN self.callback(event)
with open(cardMappingsFile, "a") as f: f.write(cardId + ",\n") print("LANABox controller is running") print("Press Ctrl-C to stop.") signal.signal(signal.SIGINT, shutdown) MIFAREReader = mfrc522.MFRC522() GPIO.setmode(GPIO.BOARD) GPIO.setup(stopButtonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(nextButtonState, GPIO.IN, pull_up_down=GPIO.PUD_UP) lastCardId = "" lastStopButtonState = GPIO.input(stopButtonPin) lastNextButtonState = GPIO.input(nextButtonState) while continueReading: time.sleep(0.5) current_state = GPIO.input(stopButtonPin) if current_state != lastStopButtonState: print("Stop Playback button pressed") lastStopButtonState = current_state subp = Popen(baseDir + "/toggle_playpause.sh", shell=True) subp.communicate() current_state = GPIO.input(nextButtonState) if current_state != lastNextButtonState:
GPIO.setmode(GPIO.BCM) #Camera click control GPIO.setup(17, GPIO.IN, GPIO.PUD_UP) #Camera click timer for selfies GPIO.setup(18, GPIO.IN, GPIO.PUD_UP) #Camera mode control - default(still/image), video recording GPIO.setup(19, GPIO.IN, GPIO.PUD_UP) while 1: delay = 0 with picamera.PiCamera() as camera: camera.start_preview() if (GPIO.input(19) == 0): GPIO.wait_for_edge(17, GPIO.FALLING) camera.start_recording('/home/pi/test_video.h264') time.sleep(1) GPIO.wait_for_edge(17, GPIO.FALLING) camera.stop_recording() else: GPIO.wait_for_edge(17, GPIO.FALLING) print "Taking snap... Say Cheese!" today = datetime.date.today() string = "PIC_" + str(today.day)+"_" + str(today.month)+"_" + str(today.year)+"_" + str(int(time.time())) + ".jpg" path = "/var/www/img/" filename = path + string print filename if(GPIO.input(18) == 0): delay = 5
import RPi.GPIO as GPIO import time import os # Setup the Shinyei input channel = 11 GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(channel, GPIO.IN) GPIO.input(channel) duration = 0 sampletime_ms = 3 lowpulseoccupancy = 0 ratio = 0 concentration = 0 # Get the current time starttime = time.time() moment = time.strftime("%Y-%b-%d__%H_%M_%S", time.localtime()) path = "Dustdata/" if not os.path.exists(path): print("1") os.mkdir("Dustdata/") os.chdir("Dustdata/") file1 = open('output' + moment + '.log', 'a') while True: # Get the low pulse duration on the input signal try: GPIO.wait_for_edge(channel, GPIO.FALLING)
import RPi.GPIO as GPIO import time import os GPIO.setmode(GPIO.BCM) pin = 24 GPIO.setup(pin, GPIO.IN) loppu = time.time() + 40 while time.time() < loppu: i=GPIO.input(pin) if i==1: print "Liiketta havaittu. Otetaan kuva" os.system("raspistill -o kuva.jpg") time.sleep(0.1) GPIO.cleanup()
# # Check if loop count exceeds 1000000 # if loop_count > 1000000: # loop_count = 1 # avg_count = 0 # # Calculate the moving average # avg_count += chan0.voltage # moving_avg = avg_count / loop_count # loop_count += 1 # Append the 16 bit voltage value samples.append(ReadChannel(0)) count += 1 # check if the escape button is pressed if GPIO.input(12) == GPIO.HIGH: print("\n\nDrumTime is now exiting") break # End of Loop time.sleep(interval) endDate = datetime.now() # check if output exists and delete if it does if os.path.exists("output.txt"): os.remove("output.txt") # Write output to file f = open("output.txt", "a") deltaDate = endDate - startDate
import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BCM) PIR_PIN = 19 GPIO.setup(PIR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #sleep(30) inputNum = 0 try: while 1: if GPIO.input(PIR_PIN) != inputNum: print(str(GPIO.input(PIR_PIN))) inputNum = GPIO.input(PIR_PIN) sleep(0.5) except KeyboardInterrupt: print("Exiting...") GPIO.cleanup()
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(24, GPIO.IN) count = 0 while True: inputValue = GPIO.input(24) if (inputValue == True): count = count + 1 print("Number of times the button has been pressed: " + int(count)) time.sleep(.3) time.sleep(.01)
import RPi.GPIO as GPIO import time from os import system as speak GPIO.setmode(GPIO.BCM) GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP) x = 0 while True: input_state = GPIO.input(21) x += 1 print(x) if input_state == False: print("Button Pressed") print('>>>>>') time.sleep(0.2)
def isButtonDown(self): return not GPIO.input(AUDIO_BUTTON_GPIO)
#!/usr/bin/env python #coding: utf8 # Python 2 import RPi.GPIO as GPIO # Zählweise der Pins festlegen GPIO.setmode(GPIO.BOARD) # Pin 18 (GPIO 24) als Eingang festlegen GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Schleifenzähler i = 0 # Endlosschleife while 1: # Eingang lesen if GPIO.input(18) == GPIO.HIGH: # Wenn Eingang HIGH ist, Ausgabe im Terminal erzeugen print "Eingang HIGH " + str(i) + " \r", else: print "Eingang LOW " + str(i) + " \r", # Schleifenzähler erhöhen i = i + 1
def handle(msg): sensor = 7 GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(18, GPIO.OUT) GPIO.setup(23, GPIO.OUT) GPIO.setup(sensor, GPIO.IN) chat_id = msg['chat']['id'] str_UserID = str(chat_id) command = msg['text'].lower() print 'Comando Recebido: %s' % command logging.info("Usuario ID:{1} enviou comando {0}".format(command, str_UserID)) def movimento(msg): bot.sendMessage(chat_id, text="Movimento Detectado") time.sleep(3) camera.start_preview() camera.capture('movimento.jpg') bot.sendPhoto(chat_id, photo=open('movimento.jpg', 'rb')) time.sleep(20) try: GPIO.add_event_detect(7, GPIO.RISING, movimento) except: GPIO.cleanup() try: if command == '/start' or command == '/start@' + MyBotName.lower(): mensagem = "Ola usuario ID: {1}, eu sou o {0} do Telegram. ".format(MyBotName, str_UserID) mensagem = mensagem + "Vc pode me controlar usando os seguintes " \ "comandos:\n\n" \ "/tirar_foto Tira a foto e envia \n" \ "/time Retorna a hora atual \n" \ "/ligar_led Liga o led vermelho \n " \ bot.sendMessage(chat_id, mensagem) elif command == '/tirar_foto': camera.start_preview() camera.capture('tirar_foto.jpg') bot.sendPhoto(chat_id, photo=open('tirar_foto.jpg', 'rb')) mensagem = 'Imagem capiturado com sucesso na data :' bot.sendMessage(chat_id, mensagem + str(datetime.datetime.now())) time.sleep(2) GPIO.cleanup(sensor, 7) elif command == '/roll': bot.sendMessage(chat_id, random.randint(1,6)) elif command == '/time': bot.sendMessage(chat_id, str(datetime.datetime.now())) elif command == '/ligar_led1': if not GPIO.input(18): GPIO.output(18, 1) mensagem = 'Led ligado' bot.sendMessage(chat_id, mensagem) #led_status = True elif command == '/desligar_led1': GPIO.output(18, 0) mensagem = 'Led Desligado' bot.sendMessage(chat_id, mensagem) #led_status = False GPIO.cleanup(18) elif command == '/ligar_led0': GPIO.output(23, 1) mensagem = 'Led ligado' bot.sendMessage(chat_id, mensagem) #led_status = True elif command == '/desligar_led0': GPIO.output(23, 0) mensagem = 'Led Desligado' bot.sendMessage(chat_id, mensagem) #led_status = False GPIO.cleanup(23) else: mensagem = "Nao reconheco o comando {0}. Envie o comando /start para solicitar ajuda...".format(command) bot.sendMessage(chat_id, mensagem) finally: pass
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) gas_leakage = 27 intruder = 22 GPIO.setup(gas_leakage, GPIO.IN) GPIO.setup(intruder, GPIO.IN) def convert(x): """converts 0 to 1 and 1 to 0""" if x == 0: return 1 if x == 1: return 0 while True: try: if convert(GPIO.input(gas_leakage)): print('There is fire') sleep(1) if convert(GPIO.input(intruder)): print('Intruder Alert') sleep(1) except Exception as e: print(str(e)) GPIO.cleanup()
lidar.stop() lidar.stop_motor() #lidar.disconnect() time.sleep(2) lidar.stop() lidar.stop_motor() kit.servo[0].angle = restAngle # BUtton Code while True: #time.sleep(1) btn1 = GPIO.input(19) btn2 = GPIO.input(26) btn3 = GPIO.input(6) btn4 = GPIO.input(13) #Scan front side in high resolution if btn1 == False: print("Button 1 pressed, scanning") scan(45, True, True) # Scan front side low resolution elif btn2 == False: print('Button 2 Pressed') scan(45, True, False) # Scan entire area, low res. NOTE: max deltaTilt is 80 (restAngle + deltaTile >= 180)
def main(): GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN) GPIO.setup(27, GPIO.OUT) GPIO.setup(23, GPIO.OUT) GPIO.setup(22, GPIO.OUT) freq = 50 gr = GPIO.PWM(27, freq) gg = GPIO.PWM(22, freq) gb = GPIO.PWM(23, freq) prev_input = 0 # Create the in-memory stream stream = io.BytesIO() faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml") camera = picamera.PiCamera() camera.resolution = (320, 240) camera.framerate = 26 rawCapture = PiRGBArray(camera, size=(320, 240)) time.sleep(0.5) i = 0 cv2.namedWindow('face', cv2.WINDOW_NORMAL) #Train svm #Get samples nmoods = [[ 'normal/img_0.jpg', 'normal/img_1.jpg', 'normal/img_2.jpg', 'normal/img_3.jpg', 'normal/img_4.jpg', 'normal/img_5.jpg', 'normal/img_6.jpg', 'normal/img_7.jpg', 'normal/img_8.jpg', 'normal/img_9.jpg', 'normal/img_10.jpg', 'normal/img_11.jpg', 'normal/img_12.jpg' ], [ 'smile/img_0.jpg', 'smile/img_1.jpg', 'smile/img_2.jpg', 'smile/img_3.jpg', 'smile/img_4.jpg', 'smile/img_5.jpg', 'smile/img_6.jpg', 'smile/img_7.jpg', 'smile/img_8.jpg', 'smile/img_9.jpg', 'smile/img_10.jpg', 'smile/img_11.jpg', 'smile/img_12.jpg', 'smile/img_13.jpg', 'smile/img_14.jpg', 'smile/img_15.jpg', 'smile/img_16.jpg', 'smile/img_17.jpg', 'smile/img_18.jpg', 'smile/img_19.jpg' ], [ 'angry/img_0.jpg', 'angry/img_1.jpg', 'angry/img_2.jpg', 'angry/img_3.jpg', 'angry/img_4.jpg', 'angry/img_5.jpg', 'angry/img_6.jpg', 'angry/img_7.jpg', 'angry/img_8.jpg', 'angry/img_9.jpg', 'angry/img_10.jpg', 'angry/img_11.jpg', 'angry/img_12.jpg', 'angry/img_13.jpg' ]] n_normal = [0] * len(nmoods[0]) n_happy = [1] * len(nmoods[1]) n_angry = [2] * len(nmoods[2]) #Grayscale, (160, 120) moods = [cv2.imread(m, 0) for mood in nmoods for m in mood] moods = np.array(moods) for i in range(len(moods)): moods[i] = cv2.resize(moods[i], (160, 120)) moods = np.array([[c for r in img for c in r] for img in moods], dtype=np.float32) #Samples #Labels #Let assume 0=normal, 1=happy, 2=angry labels = np.array(n_normal + n_happy + n_angry) svm = cv2.SVM() svmparams = dict(kernel_type=cv2.SVM_LINEAR, svm_type=cv2.SVM_C_SVC, C=2) svm.train(moods, labels, params=svmparams) #testresult = np.float32( [svm.predict(s) for s in moods]) #print(testresult) #print(labels) moods = None labels = None key = 0 for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): # grab the raw NumPy array representing the image, then initialize the timestamp # and occupied/unoccupied text image = frame.array # clear the stream in preparation for the next frame rawCapture.truncate() rawCapture.seek(0) # if the `q` key was pressed, break from the loop if key == ord("q"): break if key == ord("t"): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) faces = [ faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.cv.CV_HAAR_SCALE_IMAGE) ] for (x, y, w, h) in faces: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) if key == ord("r"): gray = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.cv.CV_HAAR_SCALE_IMAGE) for (x, y, w, h) in faces: cv2.imwrite("img_" + str(i) + ".jpg", image[y:y + h, x:x + w]) plt.title("img_" + str(i) + ".jpg") plt.imshow(image[y:y + h, x:x + w]) plt.show() i += 1 push = GPIO.input(17) if ((not prev_input) and push): print("Push") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.cv.CV_HAAR_SCALE_IMAGE) for (x, y, w, h) in faces: img = cv2.resize(gray[y:y + h, x:x + w], (160, 120)) img = np.array([c for r in img for c in r], dtype=np.float32) mood = svm.predict(img) setLed(mood, gr, gg, gb) if key == ord("m"): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.cv.CV_HAAR_SCALE_IMAGE) for (x, y, w, h) in faces: img = cv2.resize(gray[y:y + h, x:x + w], (160, 120)) img = np.array([c for r in img for c in r], dtype=np.float32) mood = svm.predict(img) plt.title("mood : " + getMood(mood)) plt.imshow(image[y:y + h, x:x + w]) plt.show() prev_input = push cv2.imshow('face', image) key = cv2.waitKey(20) & 0xFF cv2.destroyAllWindows() return 0
while (True): #Start the Trigger in Low GPIO.output(Trigger, False) time.sleep(1) #Send the pulse - 1us GPIO.output(Trigger, True) time.sleep(0.00001) #Desabilita o Trigger GPIO.output(Trigger, False) #Start the Time inicio = time.time() #While wait... while GPIO.input(Echo) == 0: inicio = time.time() #When receive... while GPIO.input(Echo) == 1: final = time.time() #Elapsed Time tempo_transcorrido = final - inicio #Distance distancia = (tempo_transcorrido * 34000) / 2 print "Distancia=%.1f cm" % distancia except KeyboardInterrupt:
anip=0 #initialise variable VWC=0 #set up channel 0 for x in range (0,5): GPIO.output(19, word1[x]) time.sleep(0.01) GPIO.output(23, True) time.sleep(0.01) GPIO.output(23, False) #read analogue voltage for x in range (0,12): GPIO.output(23,True) time.sleep(0.01) bit=GPIO.input(21) time.sleep(0.01) GPIO.output(23,False) value=bit*2**(12-x-1) anip=anip+value GPIO.output(24,True) volt = (anip*3.3/4096) print ("Volt: %.3f" % volt) #Abschnittsweise Linearisierung zur Anpassung an Messkurve if 0.1 <= volt < 1.1: VWC = 10*volt-1 elif 1.1 <= volt < 1.3:
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) capteur = 17 GPIO.setup(capteur, GPIO.IN) print "Demarrage du capteur" time.sleep(2) print "Capteur pret a detecte un mouvement" while True: if GPIO.input(capteur): print "Mouvement detecte" time.sleep(2) time.sleep(0.1)