def Buttons(triggers): buttons = triggers.sections() GPIO.init() pins = [] gpioType = [] i = 0 for button in buttons: gpioType.append(button[0]) pins.append(h3pin[int(button[1:])]) if gpioType[i] == "B": GPIO.setcfg(pins[i], GPIO.INPUT) GPIO.pullup(pins[i], GPIO.PULLUP) if gpioType[i] == "M": GPIO.setcfg(pins[i], GPIO.INPUT) i = i + 1 global buttonPressed while True: i = 0 for pin in pins: if gpioType[i] == "B": if not GPIO.input(pin): buttonPressed = "B" + str(pipin[pin]) if gpioType[i] == "M": if GPIO.input(pin): buttonPressed = "M" + str(pipin[pin]) i = i + 1 time.sleep(0.020)
def shutdowner(): rospy.init_node('shutdown_node') rate = rospy.Rate(10) # 10hz if not os.getegid() == 0: sys.exit('Script must be run as root') delay = 5 portToListen = port.PE5 portToWrite = port.PE4 gpio.init() gpio.setcfg(portToListen, gpio.INPUT) gpio.setcfg(portToWrite, gpio.OUTPUT) while not rospy.is_shutdown(): try: print("Press CTRL+C to exit") while True: v = gpio.input(portToListen) if (v == 1): sleep(2) v = gpio.input(portToListen) if (v == 1): print("shutdown of the Olimex") gpio.output(portToWrite, 1) os.system("sudo halt -p") break sleep(delay) except KeyboardInterrupt: print("Goodbye.")
def shutdowner(): if not os.getegid() == 0: sys.exit('Script must be run as root') delay = 5 portToListen = port.PI2 #13 portToWrite = port.PI1 #11 gpio.init() gpio.setcfg(portToListen, gpio.INPUT) gpio.setcfg(portToWrite, gpio.OUTPUT) gpio.output(portToWrite, 1) #this tells EPS that shutdown script is running fine while 1: v = gpio.input(portToListen) print v if (v == 1): sleep(delay) v = gpio.input(portToListen) if (v == 1): print("shutdown of the Olimex") gpio.output(portToWrite, 1) os.system("sudo halt -p") break sleep(delay)
def shutdowner(): rospy.init_node('shutdown_node') rate = rospy.Rate(10) # 10hz if not os.getegid() == 0: sys.exit('Script must be run as root') delay=5 portToListen = port.PE5 portToWrite = port.PE4 gpio.init() gpio.setcfg(portToListen, gpio.INPUT) gpio.setcfg(portToWrite, gpio.OUTPUT) while not rospy.is_shutdown(): try: print ("Press CTRL+C to exit") while True: v=gpio.input(portToListen) if(v==1): sleep(2) v=gpio.input(portToListen) if(v==1): print("shutdown of the Olimex") gpio.output(portToWrite, 1) os.system("sudo halt -p") break sleep(delay) except KeyboardInterrupt: print ("Goodbye.")
def all_lights_status(): result = gpio.input(living_room) status_living_room = "on" if result else "off" result = gpio.input(kitchen) status_kitchen = "on" if result else "off" ret1_value = "Living room light is %s\n" % status_living_room ret2_value = "Kitchen light is %s\n" % status_kitchen return ret1_value + ret2_value
def readLineSensors(): """ Function reads line sensors Returns: A tuple containing booleans """ return gpio.input(leftLineSensorPin), gpio.input(rightLineSensorPin)
def sedot_plastik_maju(self): if gpio.input(self.LS_SEDOT_PLASTIK_MAJU) == 0: return gpio.output(self.ARAH_MOTOR, gpio.LOW) time.sleep(0.5) gpio.output(self.MOTOR_SEDOT_PLASTIK, gpio.HIGH) time.sleep(0.05) while gpio.input(self.LS_SEDOT_PLASTIK_MAJU) == 1: pass gpio.output(self.MOTOR_SEDOT_PLASTIK, gpio.LOW)
def buka_katup_bawah(self): if gpio.input(self.LS_KATUP_BAWAH_BUKA) == 0: return gpio.output(self.ARAH_MOTOR, gpio.LOW) time.sleep(0.5) gpio.output(self.MOTOR_KATUP_BAWAH, gpio.HIGH) time.sleep(0.05) while gpio.input(self.LS_KATUP_BAWAH_BUKA) == 1: pass gpio.output(self.MOTOR_KATUP_BAWAH, gpio.LOW)
def buka_katup_atas(self): if gpio.input(self.LS_KATUP_ATAS_BUKA) == 0: return gpio.output(self.ARAH_MOTOR_KATUP_ATAS, gpio.LOW) time.sleep(0.5) gpio.output(self.MOTOR_KATUP_ATAS, gpio.HIGH) time.sleep(0.05) while gpio.input(self.LS_KATUP_ATAS_BUKA) == 1: pass gpio.output(self.MOTOR_KATUP_ATAS, gpio.LOW)
def initiatePin(): #Initialiser les GPIO gpio.init() pin = port.PG6 gpio.setcfg(pin, gpio.OUTPUT) gpio.input(pin) gpio.setcfg(pin, 0) gpio.pullup(pin, 0) gpio.pullup(pin, gpio.PULLDOWN) gpio.pullup(pin, gpio.PULLUP)
def tutup_katup_atas(self): if gpio.input(self.LS_KATUP_ATAS_TUTUP) == 1: return gpio.output(self.ARAH_MOTOR, gpio.HIGH) time.sleep(0.5) gpio.output(self.MOTOR_KATUP_ATAS, gpio.HIGH) time.sleep(0.05) while gpio.input(self.LS_KATUP_ATAS_TUTUP) == 1: pass gpio.output(self.MOTOR_KATUP_ATAS, gpio.LOW) gpio.output(self.ARAH_MOTOR, gpio.LOW)
def get_state(self): if gpio.input(self.state_close) == self.state_pin_closed_value: return 'closed' elif gpio.input(self.state_open) == self.state_pin_closed_value: return 'open' elif self.last_action == 'open': return 'opening' elif self.last_action == 'close': return 'closing' else: return 'unknown'
def initiatePin(): #Enable a pin gpio.init() pin = port.PG7 gpio.setcfg(pin, gpio.OUTPUT) gpio.input(pin) gpio.setcfg(pin, 0) gpio.pullup(pin, 0) gpio.pullup(pin, gpio.PULLDOWN) gpio.pullup(pin, gpio.PULLUP)
def main(): data = datetime.now().strftime("%d/%m/%Y") hora = datetime.now().strftime("%H:%M") if gpio.input(port.PA8) or gpio.input(port.PD14): if gpio.input(port.PA8): geladeira = {"sensor": "Geladeira", "hora": hora, "data": data} db.child("pacientes/oZuB8VfohicfwT5unXiV7H8Mkpy2/sensores").push(geladeira) print geladeira if gpio.input(port.PD14): quarto = {"sensor": "Quarto", "hora": hora, "data": data} db.child("pacientes/oZuB8VfohicfwT5unXiV7H8Mkpy2/sensores").push(quarto) print quarto # gpio.output(port.PA7, gpio.HIGH) sleep(2)
def getEncoderState(prc_encUp, prc_encDown, prc_ShortClick, prc_longClick): global clkLastState global counter global click_flag global click_time try: if gpio.input(btn_pin) and click_flag == 0: click_flag = 1 time.sleep(0.05) if gpio.input(btn_pin): click_time = time.time() elif gpio.input(btn_pin) == 0 and click_flag == 1: click_flag = 0 if time.time() - click_time > 0.6: if prc_longClick != None: prc_longClick() else: print("long_click") elif time.time() - click_time > 0.09: if prc_ShortClick != None: prc_ShortClick() else: print("short_click") clkState = gpio.input(clk_pin) if clkState != clkLastState: dtState = gpio.input(dt_pin) if dtState != clkState: counter += 1 time.sleep(0.1) if prc_encUp != None: prc_encUp(counter) else: print(counter) else: counter -= 1 time.sleep(0.1) if prc_encDown != None: prc_encDown(counter) else: print(counter) clkState = clkLastState finally: pass
def remedio(): tomar = "" while True: horanow = datetime.now().strftime("%H:%M") remedios = db.child("pacientes/oZuB8VfohicfwT5unXiV7H8Mkpy2/remedios/").get() if(remedios.val()!=0): for lista in remedios.each(): pathH = ("pacientes/oZuB8VfohicfwT5unXiV7H8Mkpy2/remedios/") + str(lista.key()) + ("/horario") pathD = ("pacientes/oZuB8VfohicfwT5unXiV7H8Mkpy2/remedios/") + str(lista.key()) + ("/doses") pathI = ("pacientes/oZuB8VfohicfwT5unXiV7H8Mkpy2/remedios/") + str(lista.key()) + ("/intervalo") hora = db.child(pathH).get() doses = db.child(pathD).get() intervalo = db.child(pathI).get() print hora.val() if(hora.val()==horanow): print "tomar remedio" db.child("Alarme").set(1) tomar = str(lista.key()) gpio.output(port.PA7, gpio.HIGH) if gpio.input(port.PA1): print "botao apertado" gpio.output(port.PA7, gpio.LOW) pathHtomar = ("pacientes/oZuB8VfohicfwT5unXiV7H8Mkpy2/remedios/") + tomar + ("/horario") pathDtomar = ("pacientes/oZuB8VfohicfwT5unXiV7H8Mkpy2/remedios/") + tomar + ("/doses") hora = db.child(pathHtomar).get() doses = db.child(pathDtomar).get() db.child("Alarme").set(0) db.child(pathHtomar).set("13:00") # db.child(pathDtomar).update(doses.val() - 1) else: print "Nao ha remedios!" sleep(1)
def wait_for_button(self): while True: if GPIO.input(self.__pconfig['button']) == 0: if self.__config['debug']: print("button detected") self.detect_button() # pylint: disable=no-value-for-parameter time.sleep(.1)
def read_cfg(): global rfid_lst if os.path.exists(rfid_nrs): statinfo = os.stat(rfid_nrs) if statinfo.st_size > 0: f = open(rfid_nrs, 'r') for line in f: rfid_lst.append(line[0:10]) print(line) f.close() else: # no file or empty -> learning mode f = open(rfid_nrs, 'w') ser = serial.Serial('/dev/ttyS1', 9600, timeout=1) while True: sr = ser.read(12) s = sr.decode('utf8') if len(s) != 0: sl = s[1:11] #exclude start x0A and stop x0D bytes if sl not in rfid_lst and len( sl) > 2: # hardcode, just longer than a new line f.write(sl + '\n') rfid_lst.append(sl) blink(green_led, 2) # but check if not the end of learning -> button press input_state = gpio.input(switch_io) if input_state == 0: # pressed; pullup resistor config blink(red_led, 2) break blink(green_led, 0.5) time.sleep(0.5) blink(red_led, 0.5) time.sleep(0.2) f.close()
def buttonState(): #Get the state of the button. Is it high or low? buttonStateValue = gpio.input(port.PG7) if buttonStateValue == 0: buttonStateString = 'Low' elif buttonStateValue == 1: buttonStateString = "High" return buttonStateValue, buttonStateString
def start(): global audioplaying, p while True: print("{}Ready to Record.{}".format(bcolors.OKBLUE, bcolors.ENDC)) # GPIO.wait_for_edge(button, GPIO.FALLING) # we wait for the button to be pressed if audioplaying: p.stop() print("{}Recording...{}".format(bcolors.OKBLUE, bcolors.ENDC)) # GPIO.output(rec_light, GPIO.HIGH) # gpio.output(rec_light, 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 = "" # while(GPIO.input(button)==0): # we keep recording while the button is pressed while (gpio.input(button) == 0 ): # we keep recording while the button is pressed gpio.output(rec_light, gpio.HIGH) l, data = inp.read() if l: audio += data print("{}Recording Finished.{}".format(bcolors.OKBLUE, bcolors.ENDC)) rf = open(path + 'recording.wav', 'w') rf.write(audio) rf.close() inp = None alexa_speech_recognizer()
def aInput(self, pin): if EMU: res = self.state[pin]['val'] return res if pin > self.expin: return self.expander.aread(pin) return G.input(pin)
def on_message_start(self, client, userdata, msg): payload_string = msg.payload.decode('utf-8') print("Topic1111111: {}. Payload: {}".format(msg.topic, payload_string)) # wiringpi.digitalWrite(PORT,not data['status']) status = gpio.input(port.PA13) gpio.output(port.PA10, not status)
def main(argv): initial_button_state = 0 gpio.init() gpio.setcfg(POWER_BUTTON, gpio.INPUT) gpio.pullup(POWER_BUTTON, gpio.PULLUP) gpio.setcfg(LED, gpio.OUTPUT) while True: # Returns a 1 if open and a 0 if pressed/closed current_button_state = gpio.input(POWER_BUTTON) #print(initial_button_state, current_button_state) #sys.stdout.flush() # Check if button state has changed if current_button_state != initial_button_state: #print('Button pressed') gpio.output(LED, 1) subprocess.call(CMD, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) time.sleep(0.1)
def pir(loud=False): sleep(2) #make sure sensor is ready if loud: print "looking for motion" while True: if gpio.input(sensor): now = datetime.datetime.now() event = "motion detected at: %s" % (now.strftime("%Y-%m-%d %H:%M")) if loud: print event #create the email headers and body msg = MIMEText(event) msg['From'] = gmailuser msg['To'] = phone msg['Subject'] = event text = msg.as_string() #send the mail server = smtplib.SMTP_SSL("smtp.gmail.com", 465) server.login(gmailuser, gmailpass) server.sendmail(gmailuser, phone, text) server.quit() sleep(45) #don't SMS multiple times for the same motion event else: if loud: print "no motion detected" sleep( 1 ) #rate limiting for when there is no motion to not overwork the pi
def run(): ErrorMessage = "ERROR : arguments is not true! " gpio.init() try: #print ("Press CTRL+C to exit") if len(sys.argv) != 3: print(ErrorMessage) return ErrorMessage else: pin = pinName(sys.argv[1]) if int(sys.argv[2]) == 2: gpio.setcfg(pin, GPIO.INPUT) status = gpio.input(pin) print("status => ", status) return status elif int(sys.argv[2]) == 1 or int(sys.argv[2]) == 0: gpio.setcfg(pin, gpio.OUTPUT) gpio.output(pin, int(sys.argv[2])) print("output => OK") return "OK" else: return ErrorMessage except KeyboardInterrupt: #print ("Goodbye.") return ErrorMessage
def start(): global audioplaying, p while True: print("{}Ready to Record.{}".format(bcolors.OKBLUE, bcolors.ENDC)) # GPIO.wait_for_edge(button, GPIO.FALLING) # we wait for the button to be pressed if audioplaying: p.stop() print("{}Recording...{}".format(bcolors.OKBLUE, bcolors.ENDC)) # GPIO.output(rec_light, GPIO.HIGH) # gpio.output(rec_light, 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 = "" # while(GPIO.input(button)==0): # we keep recording while the button is pressed while(gpio.input(button)==0): # we keep recording while the button is pressed gpio.output(rec_light, gpio.HIGH) l, data = inp.read() if l: audio += data print("{}Recording Finished.{}".format(bcolors.OKBLUE, bcolors.ENDC)) rf = open(path+'recording.wav', 'w') rf.write(audio) rf.close() inp = None alexa_speech_recognizer()
def readadc(adcnum, CLK, MOSI, MISO, CS): if ((adcnum > 7) or (adcnum < 0)): return -1 gpio.output(CS, 1) gpio.output(CLK, 0) # start clock low gpio.output(CS, 0) # bring CS low commandout = adcnum commandout |= 0x18 # start bit + single-ended bit commandout <<= 3 # we only need to send 5 bits here for i in range(5): if (commandout & 0x80): gpio.output(MOSI, 1) else: gpio.output(MOSI, 0) commandout <<= 1 gpio.output(CLK, 1) gpio.output(CLK, 0) adcout = 0 for i in range(14): gpio.output(CLK, 1) gpio.output(CLK, 0) adcout <<= 1 if (gpio.input(MISO)): adcout |= 0x1 gpio.output(CS, 1) adcout >>= 1 # first bit is 'null' so drop it return adcout
def check_inputs(self): for key in self.__HK_PIN_LIST: values = self.__HK_PIN_LIST[key] was_pressed = values[hkButtonEnum.HK_STATE_PRESSED] got_pressed = gpio.input(key) == self.__HK_BUTTON_PRESSED # button is not pressed but was pressed if (not got_pressed) and was_pressed: was_long_press = values[ hkButtonEnum. HK_PRESSED_SINCE] >= self.__HK_BUTTON_DIM_THRESHOLD # if longpress and value was not 100, set to hundred # else turn to 0 if (not was_long_press) and (values[hkButtonEnum.HK_OUTPUT_SET] < 100): values[hkButtonEnum.HK_OUTPUT_SET] = 100 elif not was_long_press: values[hkButtonEnum.HK_OUTPUT_SET] = 0 if values[hkButtonEnum.HK_OUTPUT_SET] <= ( 0 + self.__HK_DIM_RATE_PER_CYCLE): values[hkButtonEnum.HK_DIM_DOWN] = False else: values[hkButtonEnum.HK_DIM_DOWN] = True # send callback self.__hk_call_back(key) # call function and reset states values[hkButtonEnum.HK_PRESSED_SINCE] = 0 values[hkButtonEnum.HK_STATE_PRESSED] = False # button is pressed and was pressed -> stage 2 dim elif got_pressed and was_pressed: # if dim is allowed and dim threshold has been reached, reduce output by rate and callback # pressed_since = values[hkButtonEnum.HK_PRESSED_SINCE] if values[hkButtonEnum.HK_DIM] and \ pressed_since > self.__HK_BUTTON_DIM_THRESHOLD and \ ((pressed_since - self.__HK_BUTTON_DIM_THRESHOLD) % self.__HK_DIM_RATE_CYCLES) == 0: if values[hkButtonEnum.HK_DIM_DOWN] and \ values[hkButtonEnum.HK_OUTPUT_SET] > 0 + self.__HK_DIM_RATE_PER_CYCLE: values[hkButtonEnum. HK_OUTPUT_SET] -= self.__HK_DIM_RATE_PER_CYCLE elif (not values[hkButtonEnum.HK_DIM_DOWN] ) and values[hkButtonEnum.HK_OUTPUT_SET] < 100: values[hkButtonEnum. HK_OUTPUT_SET] += self.__HK_DIM_RATE_PER_CYCLE self.__hk_call_back(key) values[hkButtonEnum.HK_PRESSED_SINCE] += 1 # button is pressed but was not pressed -> call function elif got_pressed and (not was_pressed): values[hkButtonEnum.HK_STATE_PRESSED] = True
def update(self): reading = gpio.input(self.pin) log.debug("Reading PIR : {}".format(reading)) if reading: self.motion = 1 else: self.motion = 0 self.last_update = datetime.now()
def get_button_state(): try: global button global button_state button_state = gpio.input(button) return button_state except Exception: save_err('button')
def readUltrasonicSensor(): """ Function reads ultrasonic sensor Returns: Distance in meters """ gpio.output(triggerPin, gpio.HIGH) tm.sleep(0.01) gpio.output(triggerPin, gpio.LOW) while gpio.input(echoPin) == gpio.LOW: pass oldTime = tm.time() while gpio.input(echoPin) == gpio.HIGH: pass deltaTime = tm.time() - oldTime return deltaTime/2 * 343
def button_pushed(with_delay=False) -> bool: global last_pressed btn_pressed = gpio.input(PIN_BUTTON) if with_delay and btn_pressed: last_pressed = datetime.now() return btn_pressed if (datetime.now() - last_pressed).seconds < 1: return False return btn_pressed
def button5action(): ''' state2 = gpio.input(Configuration.Button2) if state2 == button_pressed: pourCoffee(Configuration.Coffee2) ''' state4 = gpio.input(Configuration.Button4) if state4 == button_pressed: pourCoffee(Configuration.Coffee4)
def __init__( self, id, params ): self.id = id self.name = params['name'] self.pin = getPin( params['pin'] ) self.type = params['type'] devices['id'] = self if self.type == 'switch' or self.type == 'pulse': gpio.setcfg( self.pin, gpio.OUTPUT ) if self.type == 'pulse': self.interval = params['interval'] gpio.output( self.pin, 0) elif self.type == 'switch': self.state = gpio.input( self.pin ) == 1
def start_old(): global audioplaying, p inp = None # last = GPIO.input(button) last = gpio.input(button) print("{}Ready to Record.{}".format(bcolors.OKBLUE, bcolors.ENDC)) while True: # val = GPIO.input(button) val = gpio.input(button) if val != last: last = val if val == 1 and recorded == True: print("{}Recording Finished.{}".format(bcolors.OKBLUE, bcolors.ENDC)) rf = open(path+'recording.wav', 'w') rf.write(audio) rf.close() inp = None alexa_speech_recognizer() elif val == 0: # GPIO.output(rec_light, GPIO.HIGH) gpio.output(rec_light, gpio.HIGH) print("{}Recording...{}".format(bcolors.OKBLUE, bcolors.ENDC)) 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 = "" if audioplaying: p.stop() l, data = inp.read() if l: audio += data recorded = True elif val == 0: l, data = inp.read() if l: audio += data
def start(): print ("starting") while True: if isOrangePi: while(gpio.input(button)==0): print("button pressed") capture() break else: getch() if getch() == 'q': break elif getch() == 'd': capture()
def getKey(self): key_found = None for column in self.columns: gpio.output(column, gpio.HIGH) for row in self.rows: tmp = gpio.input(row) if tmp: for key in self.mapping.keys(): if self.mapping[key][0] == column and self.mapping[key][1] == row: key_found = key break gpio.output(column, gpio.LOW) if key_found: break return key_found
def goBottom(self): self.setDirectionDown() self.endSleep() self.doRamp() debounce = 0 for i in range(0, self.height-50): if gpio.input(self.sensorPin) == 0: debounce += 1 else: debounce = 0 if debounce > 5: self.goUp(steps=50) #Move the sledge out of the sensor self.startSleep() break gpio.output(self.stepPin, 1) time.sleep(0.001) gpio.output(self.stepPin, 0) time.sleep(0.001) self.startSleep()
def gather(self, port): return gpio.input(port)
def wait_for_button(self): while True: if GPIO.input(self._pconfig['button']) == 0: self.detect_button() time.sleep(.1)
def value (self): if self._direction == 0: #input self._value = gpio.input(self._pinid) return self._value
def wait_data(): while gpio.input(irq): pass
__credits__ = ["Stefan Mavrodiev"] __license__ = "GPL" __version__ = "2.0" __maintainer__ = __author__ __email__ = "*****@*****.**" led = connector.gpio0p0 # This is the same as port.PH2 button = connector.gpio3p40 """Init gpio module""" gpio.init() """Set directions""" gpio.setcfg(led, gpio.OUTPUT) gpio.setcfg(button, gpio.INPUT) """Enable pullup resistor""" gpio.pullup(button, gpio.PULLUP) #gpio.pullup(button, gpio.PULLDOWN) # Optionally you can use pull-down resistor try: print ("Press CTRL+C to exit") while True: state = gpio.input(button) # Read button state """Since we use pull-up the logic will be inverted""" gpio.output(led, not state) except KeyboardInterrupt: print ("Goodbye.")