def switch_event(self, switch): if GPIO.input(self.pinA): self.rotary_a = 1 else: self.rotary_a = 0 if GPIO.input(self.pinB): self.rotary_b = 1 else: self.rotary_b = 0 self.rotary_c = self.rotary_a ^ self.rotary_b new_state = self.rotary_a * 4 + self.rotary_b * 2 + self.rotary_c * 1 delta = (new_state - self.last_state) % 4 self.last_state = new_state event = 0 if delta == 1: if self.direction == self.CLOCKWISE: event = self.direction else: self.direction = self.CLOCKWISE elif delta == 3: if self.direction == self.ANTICLOCKWISE: event = self.direction else: self.direction = self.ANTICLOCKWISE if event > 0: self.callback(event)
def switches_read(): value = 0 if GPIO.input("U14_13"): value = value + 1 if GPIO.input("U14_14"): value = value + 2 if GPIO.input("U14_15"): value = value + 4 if GPIO.input("U14_16"): value = value + 8 return value
def switches_read(): value = 0 if GPIO.input("U14_13"): value = value + 1 if GPIO.input("U14_14"): value = value + 2 if GPIO.input("U14_15"): value = value + 4 if GPIO.input("U14_16"): value = value + 8 return value
def getKey(self): for j in range(4): GPIO.output(self.COL[j],0) for i in range(4): if GPIO.input(self.ROW[i]) == 0: #print (self.MATRIX[i][j]) return self.MATRIX[i][j] sleep(0.2) while(GPIO.input(self.ROW[i]) == 0): pass GPIO.output(self.COL[j],1)
def _cb(self, ch): self._readings = (self._readings << 2 | GPIO.input(self.pin_clk) << 1 | GPIO.input(self.pin_dt)) & 0x0f self._state = ENC_STATES[self._readings] * self.reverse if self._state: self.cur_accel = min(self.max_accel, self.cur_accel + self.accel) self._value = min( self.max_val, max( self.min_val, self._value + (1 + (self.cur_accel >> ACCEL_THRESHOLD)) * self._state))
def main(): #initialize beam falls beam1Rise = datetime.datetime.min beam2Rise = datetime.datetime.min beam1LastRise = datetime.datetime.min beam2LastRise = datetime.datetime.min firebase = firebase_setup() global db db = firebase.database() print("Firebase is setup") global mac mac = hex(get_mac()) print("MAC Address obtained") pull_data_config() gpio_setup() print("GPIO is setup") #send now as start of first interval asyncSendData(datetime.datetime.now()) print("Will output/send every " + str(SENDFREQ) + " seconds") while True: if GPIO.event_detected(BEAM_2): #poll to see if this is a rise if not GPIO.input(BEAM_2): beam2LastRise = beam2Rise beam2Rise = datetime.datetime.utcnow() print("-----Beam 2 Rise: " + str(beam2Rise)) if (beam2Rise - beam2LastRise).total_seconds() < RISETHRESH: continue #if other beam is not tripped then don't do anything if not GPIO.input(BEAM_1): analyze_event(beam1Rise, beam2Rise) if GPIO.event_detected(BEAM_1): #poll to see if this is a fall if not GPIO.input(BEAM_1): beam1LastRise = beam1Rise beam1Rise = datetime.datetime.utcnow() print("-----Beam 1 Rise: " + str(beam1Rise)) if (beam1Rise - beam1LastRise).total_seconds() < RISETHRESH: continue #if other beam is not tripped then don't do anything if not GPIO.input(BEAM_2): analyze_event(beam1Rise, beam2Rise)
def button(): while True: #If button pressed if GPIO.input("CSID0"): wav = random.choice(wavs) wav = wav.strip('\n') subprocess.call(['play', wav])
def Get(): global flag global keycomp1 global keycomp2 global key global doubler key = 0 for y in range(4): GPIO.output(output[y], GPIO.LOW) for x in range(4): if GPIO.input(input[x]) == 0: # print ("key", x, y) key = ((x+1) + (y*4)) # print ("key ",key) GPIO.output(output[y],GPIO.HIGH) if flag == False: keycomp1 = key flag = True elif flag == True: keycomp2 = key flag = False if keycomp1 != keycomp2 and key != 0: return key
def xfer2(byte_list): """Transfer a list of bytes and store the returned values""" stored_bytes = [] for byte in byte_list: temp_byte = byte store_byte = 0x00 for i in np.arange(8): store_byte *= 2 if temp_byte & 0b10000000 > 0: GPIO.output(PIN_SDI, GPIO.HIGH) else: GPIO.output(PIN_SDI, GPIO.LOW) temp_byte*=2 #time.sleep(0.001) GPIO.output(PIN_SCK, GPIO.HIGH) #time.sleep(0.001) if GPIO.input(PIN_SDO): store_byte += 1 GPIO.output(PIN_SCK, GPIO.LOW) GPIO.output(PIN_SDI, GPIO.LOW) stored_bytes.append(store_byte) return stored_bytes
def detect_button(self, channel): # pylint: disable=unused-argument buttonPress = time.time() self.button_pressed = True if self.__config['debug']: print("{}Button Pressed! Recording...{}".format(bcolors.OKBLUE, bcolors.ENDC)) time.sleep(.5) # time for the button input to settle down while GPIO.input(self.__pconfig['button']) == 0: time.sleep(.1) if (self.long_press_setup) and (time.time() - buttonPress > self.__pconfig['long_press']['duration']): if ('audio_file' in self.__pconfig['long_press']) and (len(self.__pconfig['long_press']['audio_file']) > 0): pass # play_audio(self.__pconfig['long_press']['audio_file'].replace('{resources_path}', resources_path)) if self.__config['debug']: print(("{} -- " + str(self.__pconfig['long_press']['duration']) + " second button press detected. Running specified command. -- {}").format(bcolors.WARNING, bcolors.ENDC)) os.system(self.__pconfig['long_press']['command']) if self.__config['debug']: print("{}Recording Finished.{}".format(bcolors.OKBLUE, bcolors.ENDC)) self.button_pressed = False time.sleep(.5) # more time for the button to settle down
def readADC(dout,pd_sck,gain_select): if not isReady(dout): # If data pin is low, ADC is ready data = [] for i in range(0,24): # do 24 times # Pulse the ADC once GPIO.output(pd_sck,GPIO.HIGH) # push to high to get the value data.append(GPIO.input(dout)) # read value from ADC and append to data GPIO.output(pd_sck,GPIO.LOW) # end low if gain_select == 128: # if you want 128 gain pulse one more time. 25 times total GPIO.output(pd_sck,GPIO.HIGH) # Pulse GPIO.output(pd_sck,GPIO.LOW) if gain_select == 64: # if you want 32 gain, channel B pulse two more times. 26 times total for i in range(0,2): # do 2 times GPIO.output(pd_sck,GPIO.HIGH) # Pulse GPIO.output(pd_sck,GPIO.LOW) if gain_select == 32: # if you want 64 gain pulse three more times. 27 times total for i in range(0,3): # do 3 times GPIO.output(pd_sck,GPIO.HIGH) # Pulse GPIO.output(pd_sck,GPIO.LOW) print(data) data = 0 # Clear data for next read else: print('ADC is not ready!') # If data pin is high, ADC is not ready
def status(): # 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 = {'pins': pins} return render_template('index.html', **templateData)
def test_input(self): GPIO.setup("CSID6", GPIO.IN) #returned as an int type input_value = GPIO.input("CSID6") #value read from the file will have a \n new line value = open('/sys/class/gpio/gpio138/value').read() assert int(value) == input_value # time.sleep(30) - what is this for? GPIO.cleanup()
def button(button): __button_init() if button == "one": button = "XIO-P6" elif button == "two": button = "XIO-P7" else: return False return GPIO.input(button)
def test_input(self): GPIO.setup("CSID6", GPIO.IN) #returned as an int type input_value = GPIO.input("CSID6") #value read from the file will have a \n new line value = open('/sys/class/gpio/gpio138/value').read() assert int(value) == input_value time.sleep(30) GPIO.cleanup()
def _state(): state = request.args.get('state') # state of the on/off button pin = request.args.get('pin') if state == "Power ON": GPIO.output(pin, GPIO.LOW) else: GPIO.output(pin, GPIO.HIGH) for pin in pins: # state in the dictionary pins[pin]['state'] = GPIO.input(pin) return ""
def manual_release(self, connection): GPIO.setup(buttonPin,GPIO.IN, pull_up_down = GPIO.PUD_UP) self.connection = True while True: if(GPIO.input(buttonPin) == False): time.sleep(.1) if(GPIO.input(buttonPin) == False): logger.info("******** Start Message ********") self.solenoid.open_door() logger.info("********* End Message *********") count = 0 while(GPIO.input(buttonPin) == False): time.sleep(.1) count += 1 if count == 40: self.solenoid.blink_door() sp.call(update_script) self.solenoid.blink_door() else: logger.info("******* Missed Debounce *******")
def rotary_engaged(self, channel): if GPIO.input(channel): # high = disengaged number = self.pulseCount if number >= 10: # anything past 0 becomes 0 (must be error) number = 0 logging.debug('number dialed: ' + str(number)) self.client.send_message("/dialed", number) else: # low = engaged self.pulseCount = 0;
def read(self, numRdg, force): # read from ADC FIFO. Waits for conversion complete unless force is true if (int(numRdg) > 16): numRdg = 16 if (int(numRdg) < 1): numRdg = 1 if (not GPIO.input("AP-EINT1") or bool(force)): # conversion complete or forced read pass else: # waiting for conversion complete for i in range(0,10): if (not GPIO.input("AP-EINT1")): break else: time.sleep(0.0001) # Interrupts are not working reliably. # I think the interrupt is being fired before the code to wait for it runs. # The ADC runs at 300K samples per second. #GPIO.wait_for_edge("AP-EINT1", GPIO.FALLING) return self.spi.read(int(numRdg)*2)
def run(self, handleInterrupt=False, handleUpdate=False): while True: try: if handleInterrupt: if GPIO.input(self._intPin) == 0: self.handleInterrupt() if handleUpdate: self.handleUpdate() except KeyboardInterrupt: self._tft.displayOn(False) GPIO.cleanup() raise
def api_digital_read(self, pin): resp = copy.deepcopy(self.CHIP_INFO) resp["connected"] = True pin = pin.upper() # Setup pin if it isn't already and then add it if pin not in self.PINS_IN_USE: GPIO.setup(pin, GPIO.IN) self.PINS_IN_USE.append(pin) # Read the pin resp["message"] = GPIO.input(pin) return jsonify(resp)
def readSwitchState2(): state = [0] * 6 s0.low() s1.low() s2.low() if (GPIO.input(pin(3)) == 1 and GPIO.input(pin(4)) == 1): return state s0.low() s1.high() s2.high() state[5] = 1 - GPIO.input(pin(3)) state[2] = 1 - GPIO.input(pin(4)) s0.high() s1.low() state[0] = 1 - GPIO.input(pin(3)) state[3] = 1 - GPIO.input(pin(4)) s1.high() s2.low() state[1] = 1 - GPIO.input(pin(3)) state[4] = 1 - GPIO.input(pin(4)) return state
def readdata(data): indata = 0 GPIO.output("CSID0",0) for i in range(8): GPIO.output("CSID3",0) if (data<<i) & 0x80: GPIO.output("CSID1",1) else: GPIO.output("CSID1",0) GPIO.output("CSID3",1) for i in range(8): GPIO.output("CSID3",0) indata = indata + (GPIO.input("CSID2") << (7-i)) GPIO.output("CSID3",1) GPIO.output("CSID0",1) return indata
def detect_button(self, channel): # pylint: disable=unused-argument buttonPress = time.time() self.button_pressed = True if self.__config['debug']: print("{}Button Pressed! Recording...{}".format( bcolors.OKBLUE, bcolors.ENDC)) time.sleep(.5) # time for the button input to settle down while GPIO.input(self.__pconfig['button']) == 0: time.sleep(.1) if (self.long_press_setup) and ( time.time() - buttonPress > self.__pconfig['long_press']['duration']): if ('audio_file' in self.__pconfig['long_press']) and (len( self.__pconfig['long_press']['audio_file']) > 0): pass # play_audio(self.__pconfig['long_press']['audio_file'].replace('{resources_path}', resources_path)) if self.__config['debug']: print(( "{} -- " + str(self.__pconfig['long_press']['duration']) + " second button press detected. Running specified command. -- {}" ).format(bcolors.WARNING, bcolors.ENDC)) os.system(self.__pconfig['long_press']['command']) if self.__config['debug']: print("{}Recording Finished.{}".format(bcolors.OKBLUE, bcolors.ENDC)) self.button_pressed = False time.sleep(.5) # more time for the button to settle down
last_time = -1 ser = serial.Serial('/dev/ttyS0') sleep(1) # wait for channel to open # hunger = calc_hunger() # initialize as dreaming send_serial('d') startup() # setting up code to initialize the board/uploads while True: # continually in this state, check if channel HI # print(GPIO.input(record_channel)) # record ing if GPIO.event_detected(record_channel) and not GPIO.input(record_channel): trigger_record() # on button press, trigger callback sleep(10) # wait 10 secs for debouncing, bad but works. # THIS MEANS RECORD FOR AT LEAST 10 seconds please: # start sing if not recording: if not singing and not GPIO.input(sing_channel): if last_time is -1: last_time = datetime.datetime.now() else: if datetime.datetime.now() - last_time > timedelta(0, 0, 250): last_time = -1 print "singing..." start_singing() sleep(3) # wait 3 secs for debouncing, bad but works.
def read(self): val = gpio.input(self.sensor) if val != self.state: self.state = val self.perform(val) return val
# the following assums a normally-open pushbutton is connected between to xio-p1 # if its other lead is connected to vcc this program always outputs 1's. If it is # connected to ground it outputs 1 when not pressed, and 0 when pressed. this tells # us that the pin has a pull-up resistor which means we need to pull it low to signal # some outside event like pushing a button. import time import CHIP_IO.GPIO as GPIO GPIO.setup("XIO-P1", GPIO.IN) isPressed = False changed = False while True: print(GPIO.input('XIO-P1')) time.sleep(1)
def play_music(): subprocess.Popen(['mplayer', '-slave', '-input', 'file=/tmp/mplayer-control', MUSIC_FILE]) def stop_music(): f = open('/tmp/mplayer-control', 'w') f.write('quit\n') f.close() # application loop is_playing = False while True: time.sleep(1) # photoresistor thinks it's dark if GPIO.input(PIN): print("HIGH") if is_playing: is_playing = False stop_music() # photoresistor thinks it's light else: print("LOW") if not is_playing: is_playing = True play_music()
#!/usr/bin/python # encoding:utf-8 import CHIP_IO.GPIO as GPIO from time import sleep probe = "CSID0" set = "CSID2" reset = "CSID4" GPIO.cleanup() GPIO.setup(probe, GPIO.IN) if GPIO.input(probe): print("relay probe is HIGH") else: print("relay probe is LOW") GPIO.setup(set, GPIO.OUT) GPIO.output(set, 0) GPIO.setup(reset, GPIO.OUT) GPIO.output(reset, 0) sleep(5) GPIO.output(reset, 1) # while True: # pass sleep(0.02) GPIO.output(reset, 0) if GPIO.input(probe): print("relay probe is HIGH")
import CHIP_IO.GPIO as GPIO import time from wiki_api import CalangoWiki wiki = CalangoWiki() def status_atual(): """Verifica no site o status atual (aberto ou fechado)""" return wiki.conteudo_pagina("status") def muda_status(status): """Atualiza a wiki com o status selecionado""" wiki.atualiza_pagina('status', status) #opções = 'Aberto Fechado'.split() if __name__ == '__main__': GPIO.setup("CSID0", GPIO.IN) while 1: if GPIO.input("CSID0"): muda_status("Fechado") print("HIGH") else: muda_status("Aberto") print("LOW") time.sleep(300)
#clientMongo = MongoClient('localhost:27017') #db = clientMongo.SmartGreen # Pin configuration. pin = "XIO-P0" # Rain Sensor GPIO.setup(pin, GPIO.IN) # Pool in a loop print("aguardando deteccao") try: while True: # read the pin every 5 seconds #GPIO.wait_for_edge("XIO-P0", GPIO.BOTH) sensor_read = GPIO.input("XIO-P0") # print("evento detectado") print(time.asctime()) print(sensor_read) time.sleep(60) except KeyboardInterrupt: GPIO.cleanup("XIO-P0") GPIO.cleanup("XIO-P0") #if GPIO.event_detected("XIO-P0"): # print("evento detectado") # sensor_read = GPIO.input("XIO-P0") # print(sensor_read)
def highlow(inGPIO): if GPIO.input(inGPIO): return "HIGH" else: return "LOW"
font=font1, fill="white") def poweronoff(onoff): if onoff == 0: subprocess.Popen(['mpc', 'stop', "-q"]) subprocess.Popen(['mpc', 'clear', "-q"]) else: change_channel(channel_num) change_volume(vol) while True: if GPIO.input(_up) == 0: vol += 10 if vol > 100: vol = 100 change_volume(vol) if GPIO.input(_down) == 0: vol -= 10 if vol < 0: vol = 0 change_volume(vol) if GPIO.input(_prev) == 0: channel_num -= 1 if channel_num < 0: channel_num = channel_count - 1
log.warning(service_name+" is (re)starting !") time.sleep(wait_at_startup) # brings an error! :( # GPIO.cleanup() probe = "CSID0" set = "CSID2" reset = "CSID4" GPIO.setup(set, GPIO.OUT) GPIO.output(set, 0) GPIO.setup(reset, GPIO.OUT) GPIO.output(reset, 0) GPIO.setup(probe, GPIO.IN) if GPIO.input(probe): log.info("lights are ON") current_state = 1 else: log.info("lights are OFF") current_state = 0 # send a restart info to logbook send_to_logbook("WARNING", "Restarting...") while True: # process/evaluate the last light outdoor value every 5mn try: payload = {'db': "basecamp", 'q': "SELECT LAST(\"Lit\") FROM \"muta\" WHERE unit='"+unit+"'"} r = requests.get(influxdb_query_url, params=payload) except requests.exceptions.RequestException as e:
def P0_control(value): GPIO.output('XIO-P0', value) return GPIO.input('XIO-P0')
def off_hook(self, channel): # handset off hook == 0 (closed) state = GPIO.input(channel) GPIO.output(LED, GPIO.LOW if state else GPIO.HIGH) logging.debug('handset is: ' + str(state)) self.client.send_message("/handset", state)
def value(self): if self.direction != "in": self.direction = "in" GPIO.setup(self.pin, GPIO.IN) return GPIO.input(self.pin)
last = 0 number = 0 def play(number): try: player.kill() except NameError: pass #player = subprocess.Popen(["mpg123", "/media/" + str(number) + ".mp3", "-q"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while True: input_value = GPIO.input("XIO-P0") #try: # player.kill() #except NameError: # pass if (input_value == 1) and (input_value != last): last = 1 prnt = 1 num += 1 time.sleep(0.05) continue if (input_value == 0) and (input_value != last): last = 0 time.sleep(0.05) continue
def getSwitchState(self, switch): return GPIO.input(switch)
GPIO.output("CSID0",GPIO.HIGH) print "SLEEPING" time.sleep(1) print "SETUP XIO-P0" GPIO.setup("XIO-P0", GPIO.IN) print "SETUP CSID0" GPIO.setup("CSID0", GPIO.OUT) # VERIFY SIMPLE FUNCTIONALITY print "VERIFY SIMPLE FUNCTIONALITY" print "READING XIO-PI" GPIO.output("CSID0", GPIO.HIGH) print "HIGH", GPIO.input("XIO-P0") GPIO.output("CSID0", GPIO.LOW) print "LOW", GPIO.input("XIO-P0") # ============================================== # EDGE DETECTION - AP-EINT1 print "SETTING UP EDGE DETECTION ON AP-EINT1" GPIO.setup("AP-EINT1", GPIO.IN) GPIO.add_event_detect("AP-EINT1",GPIO.FALLING) print "VERIFYING EDGE DETECT" f = open("/sys/class/gpio/gpio193/edge","r") edge = f.read() f.close() print "EDGE: %s" % edge
def button_event(self, button): if GPIO.input(button): event = self.BUTTONUP else: event = self.BUTTONDOWN self.callback(event)
print(" LOOP FUNCTION SLEEPING") time.sleep(1) num_errs = 0 print("GETTING CHIP_IO VERSION") mystr = "CHIP_IO VERSION: %s" % GPIO.VERSION print(mystr) print("\nRUNNING GPIO SELF TEST") GPIO.selftest(0) print("\nVERIFYING SIMPLE FUNCTIONALITY") GPIO.setup("GPIO1", GPIO.IN) GPIO.setup("CSID0", GPIO.OUT, initial=GPIO.HIGH) if (GPIO.input("GPIO1") != GPIO.HIGH): print(" A high output on CSI0 does not lead to a high input on XIO-P2.") print(" Perhaps you forgot to connect them?") num_errs += 1 else: print(" Able to use alternate names for GPIO") GPIO.cleanup() GPIO.setup("U14_15", GPIO.IN) # XIO-P2 GPIO.setup("CSID0", GPIO.OUT, initial=GPIO.LOW) if (GPIO.input("XIO-P2") != GPIO.LOW): print(" A low output on CSI0 does not lead to a low input on XIO-P2.") print(" Perhaps you forgot to connect them?") num_errs += 1 else: print(" Able to use Pin Header+Number for GPIO")
from wiki_api import CalangoWiki wiki = CalangoWiki() def status_atual(): """Verifica no site o status atual (aberto ou fechado)""" return wiki.conteudo_pagina("status") def muda_status(status): """Atualiza a wiki com o status selecionado""" wiki.atualiza_pagina('status', status) #opções = 'Aberto Fechado'.split() if __name__ == '__main__': GPIO.setup("CSID0",GPIO.IN) while 1: if GPIO.input("CSID0"): muda_status("Fechado") print("HIGH") else: muda_status("Aberto") print("LOW") time.sleep(300)
"fields": {} } ] # OS: highest priority os.nice(-20) # GPIO probe = "CSID7" GPIO.setup(probe, GPIO.IN) # ======================================================= # main loop while True: while not GPIO.input(probe): time.sleep(0.01) while GPIO.input(probe): time.sleep(0.01) # an impulse has been detected log.info("1l impulse detected.") influx_json_body[0]['time'] = datetime.datetime.utcnow().isoformat() influx_json_body[0]['fields'] = {'water': 1} log.info("writing to influxdb: "+str(influx_json_body)) try: client.write_points(influx_json_body) except Exception as e: log.error(e.__str__()) log.error("Error reaching infludb on "+str(influxdb_host)+":"+str(influxdb_port)) send_to_logbook("ERROR", "Cannot write to InfluxDB!")