def open_door(self): logger.info("door is open") GPIO.output(self.pin, False) #time.sleep(self.openduration) time.sleep(10.0) logger.info("door is closed") GPIO.output(self.pin, True)
def add_event_detect(dio_number, callback): """ Wraps around the GPIO.add_event_detect function :param dio_number: DIO pin 0...5 :param callback: The function to call when the DIO triggers an IRQ. :return: None """ GPIO.add_event_detect(dio_number, GPIO.RISING, callback=callback)
def indicate_setup_failure(self): while True: for _ in range(0, 5): time.sleep(.1) GPIO.output(self.__pconfig['rec_light'], GPIO.HIGH) time.sleep(.1) GPIO.output(self.__pconfig['rec_light'], GPIO.LOW)
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 test_setup_expanded_gpio(self): GPIO.setup("XIO-P1", GPIO.OUT) base = GPIO.get_gpio_base() + 1 gfile = '/sys/class/gpio/gpio%d' % base assert os.path.exists(gfile) GPIO.cleanup() assert not os.path.exists(gfile)
def led_on(value=0): """ Switch the proto shields LED :param value: 0/1 for off/on. Default is 1. :return: value :rtype : int """ GPIO.output(BOARD.LED, value) return value
def add_events(cb_dio0, cb_dio1, cb_dio2, cb_dio3, cb_dio4, cb_dio5, switch_cb=None): BOARD.add_event_detect(BOARD.DIO0, callback=cb_dio0) BOARD.add_event_detect(BOARD.DIO1, callback=cb_dio1) BOARD.add_event_detect(BOARD.DIO2, callback=cb_dio2) BOARD.add_event_detect(BOARD.DIO3, callback=cb_dio3) # the modtronix inAir9B does not expose DIO4 and DIO5 if switch_cb is not None: GPIO.add_event_detect(BOARD.SWITCH, GPIO.RISING, callback=switch_cb, bouncetime=300)
def Setup_Interface(): GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) MGPIO.setup(PIC_MCLR,GPIO.OUT) MGPIO.output(PIC_MCLR,False) MGPIO.setup(PIC_CLK,GPIO.OUT) MGPIO.setup(PIC_DATA,GPIO.OUT) MGPIO.setup(PIC_PGM,GPIO.OUT)
def switches_setup(): ports=["U14_13","U14_14","U14_15","U14_16"] for port in ports: try: GPIO.setup(port, GPIO.IN) except RuntimeError: print("Couldn't set up port",port) pass
def switches_setup(): try: GPIO.setup("U14_13", GPIO.IN) GPIO.setup("U14_14", GPIO.IN) GPIO.setup("U14_15", GPIO.IN) GPIO.setup("U14_16", GPIO.IN) GPIO.setup("U14_17", GPIO.IN) except RuntimeError: pass
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 loopfunction(): print "LOOP FUNCTION" for i in xrange(20): if i % 2: print "SETTING CSID0 LOW" GPIO.output("CSID0",GPIO.LOW) else: print "SETTING CSID0 HIGH" GPIO.output("CSID0",GPIO.HIGH) print "SLEEPING" time.sleep(1)
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 setup(): """Setup GPIO ports""" print("Setting up SPI GPIO connections..."), #Setup GPIO pins GPIO.setup(PIN_SDI, GPIO.OUT) GPIO.setup(PIN_SDO, GPIO.IN) GPIO.setup(PIN_SCK, GPIO.OUT) #Initialize output pins GPIO.output(PIN_SDI, GPIO.LOW) GPIO.output(PIN_SCK, GPIO.LOW) print("[DONE]")
def sequence(): # run-start position print("Run-Start Position") GPIO.output(gpioRunStart, GPIO.HIGH) confirmation(gpioRunStart) time.sleep(sleepRunStart) # run position print("Run Position") GPIO.output(gpioRun, GPIO.HIGH) confirmation(gpioRun) time.sleep(sleepRun) # Start it! print("Start position") if Am_I_Serious(): print("Cranking!!!") GPIO.output(gpioIgnitionStart, GPIO.HIGH) confirmation(gpioIgnitionStart) time.sleep(sleepIgnitionStart) GPIO.output(gpioIgnitionStart, GPIO.LOW) confirmation(gpioIgnitionStart) else: print("no balls, get some and try again later") # Press enter to stop car gotinput("Started! Press enter to stop the jeep....") clear()
def act(self, client_address, state, name): print "State", state, "from client @", client_address GPIO.setmode(GPIO.BOARD) ## Use board pin numbering GPIO.setup(str(sys.argv[3]), GPIO.OUT) ## Setup GPIO Pin to OUTPUT GPIO.output(str(sys.argv[3]), not state) ## State is true/false GPIO.cleanup(str(sys.argv[3])) return True
def loopfunction(): print("LOOP FUNCTION START") for i in xrange(4): if loopfunction_exit: break if i % 2: mystr = "SETTING CSID0 LOW (i=%d)" % i print(mystr) GPIO.output("CSID0", GPIO.LOW) else: mystr = "SETTING CSID0 HIGH (i=%d)" % i print(mystr) GPIO.output("CSID0", GPIO.HIGH) print(" LOOP FUNCTION SLEEPING") time.sleep(1)
def switchOFF(self, device): app.logger.info("GPIO OFF" + str(device)) if not app.brewapp_gpio: app.logger.warning("GPIO TEST MODE ACTIVE. GPIO is not switched off" + str(device)) return switch_name = self.getConfigValue(device, "switch", None) if switch_name is None: app.logger.warning("SWITCH NOT FOUND IN CONFIG") if self.getConfigValue(device, "inverted", False): app.logger.warning("SWITCH OFF - Inverted") GPIO.output(switch_name, GPIO.HIGH) else: app.logger.warning("SWITCH OFF - Not Inverted") GPIO.output(switch_name, GPIO.LOW)
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 blinkLed(blinks): GPIO.setup("XIO-P0", GPIO.OUT) for j in range(1, blinks): GPIO.output("XIO-P0", GPIO.LOW) time.sleep(0.05) GPIO.output("XIO-P0", GPIO.HIGH) time.sleep(0.05) GPIO.cleanup() return
def setup_gpio(self): GPIO.setwarnings(False) try: GPIO.setmode(GPIO.BOARD) except AttributeError: pass GPIO.setup(self.pin, GPIO.OUT) GPIO.output(self.pin, True)
def test_start_pwm(self): PWM.start("XIO-P7", 50, 10) base = GPIO.get_gpio_base() + 7 gfile = '/sys/class/gpio/gpio%d' % base assert os.path.exists(gfile) direction = open(gfile + '/direction').read() assert(direction == 'out\n') PWM.cleanup()
def playSound(melodie): socketio.emit('beep', {"melodie": melodie}, namespace='/brew') try: buzzer_gpio = app.brewapp_config.get("BUZZER_GPIO", None) if (buzzer_gpio == None): return for i in melodie: if (isinstance(i, str)): if i == "H": GPIO.output(int(buzzer_gpio), GPIO.HIGH) else: GPIO.output(int(buzzer_gpio), GPIO.LOW) else: time.sleep(i) except Exception as e: app.logger.error("BUZZER ERROR " + str(e))
def switchOFF(self, device): app.logger.info("GPIO OFF" + str(device)) if not app.brewapp_gpio: app.logger.warning( "GPIO TEST MODE ACTIVE. GPIO is not switched off" + str(device)) return switch_name = self.getConfigValue(device, "switch", None) if switch_name is None: app.logger.warning("SWITCH NOT FOUND IN CONFIG") if self.getConfigValue(device, "inverted", False): app.logger.warning("SWITCH OFF - Inverted") GPIO.output(switch_name, GPIO.HIGH) else: app.logger.warning("SWITCH OFF - Not Inverted") GPIO.output(switch_name, GPIO.LOW)
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 chip(): import CHIP_IO.GPIO as GPIO trigger = i.cfg['chip']['trigger_pin'] light = i.cfg['chip']['relay_pin'] GPIO.setup(trigger, GPIO.OUT) GPIO.setup(light, GPIO.OUT) GPIO.output(light, GPIO.HIGH) f.playAudio(i.intro) f.playAudio(i.alarm) f.playAudio(i.voice) GPIO.output(light, GPIO.LOW) 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 setup(self): if not self.initialized: # reset gpio GPIO.cleanup(self.red) GPIO.cleanup(self.yellow) # init gpio pwm.start(self.red, 0, self.freq) pwm.start(self.yellow, 0, self.freq) self.initialized = True # init variables self.red_sweeping = False self.red_sweep_increment = 0 self.red_duty = 0 self.red_target = 0 self.yellow_ud_percent = 0 self.yellow_cooldown = 0
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 main(): GPIO.setup("CSID0", GPIO.OUT) GPIO.setup("CSID1", GPIO.OUT) GPIO.setup("CSID2", GPIO.OUT) GPIO.setup("CSID3", GPIO.OUT) cmd = "" while cmd!="q": cmd = raw_input("q,wasd,x? :") if cmd=="w": forward() if cmd=="a": steer_left() if cmd=="d": steer_right() if cmd=="s": reverse() if cmd=="x": stop() stop() GPIO.cleanup()
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 __init__(self, sensor_ctl, pud=gpio.PUD_UP, cooldown=None): self.callbacks_high = [] self.callbacks_low = [] self.sensor = sensor_ctl gpio.cleanup(sensor_ctl) gpio.setup(sensor_ctl, gpio.IN, pull_up_down=pud) self.state = None self.enabled = True try: tcool = float(cooldown) except: tcool = -1 if tcool > 0: self.cooldown = Sensor.Cooldown(self, tcool) self.cooldown.start() else: self.cooldown = None
def init(self): app.logger.info("INIT GPIO") try: app.logger.info(app.brewapp_hardware_config) for h, hw in app.brewapp_hardware_config.items(): app.logger.info(hw) g = hw["config"]["switch"] app.logger.info(g) if not g: continue app.logger.info("SETUP HARDWARE: " + str(h) + " GPIO: " + str(g)) GPIO.setup(g, GPIO.OUT) if self.getConfigValue(h, "inverted", False): app.logger.warning("SETUP INVERTED") GPIO.output(g, GPIO.HIGH) else: app.logger.warning("SETUP NOT INVERTED") GPIO.output(g, GPIO.LOW) app.brewapp_gpio = True self.state = True app.logger.info("ALL GPIO INITIALIZED") except Exception as e: app.logger.error("SETUP GPIO FAILD " + str(e)) app.brewapp_gpio = False self.state = False
def configGPIO(pin): if not settings['triggerActive']: if not settings['SIMULATE']: import CHIP_IO.GPIO as GPIO # Config GPIO pin for pull down # and detection of rising edge GPIO.cleanup(pin) GPIO.setup(pin, GPIO.IN, GPIO.PUD_DOWN) GPIO.add_event_detect(pin, GPIO.RISING) GPIO.add_event_callback(pin, S0Trigger) settings['triggerActive'] = True logMsg("Setting up S0-Logger on " + pin) else: logMsg("Trigger already active on " + pin)
def setup(): """ Configure the CHIP GPIOs :rtype : None """ # LED GPIO.setup(BOARD.LED, GPIO.OUT) GPIO.output(BOARD.LED, 1) # switch GPIO.setup(BOARD.SWITCH, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # DIOx for gpio_pin in [BOARD.DIO0, BOARD.DIO1, BOARD.DIO2, BOARD.DIO3]: GPIO.setup(gpio_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # blink 2 times to signal the board is set up BOARD.blink(.1, 2)
def stop(self): GPIO.direction(self.dio, GPIO.OUT) self.bit_delay() GPIO.direction(self.clk, GPIO.IN) self.bit_delay() GPIO.direction(self.dio, GPIO.IN) self.bit_delay()
def __init__(self, dout, pd_sck, gain_channel_A=128, select_channel='A'): self.CSID1 = pd_sck self.CSID0 = dout self._gain_channel_A = 0 # init to 0 self._offset_A_128 = 0 # init offset for channel A and gain 128 self._offset_A_64 = 0 # init offset for channel A and gain 64 self._offset_B = 0 # init offset for channel B self._last_raw_data_A_128 = 0 # init last data to 0 for channel A and gain 128 self._last_raw_data_A_64 = 0 # init last data to 0 for channelA and gain 64 self._last_raw_data_B = 0 # init last data to 0 for channel B self._wanted_channel = '' # init to empty string self._current_channel = '' # init to empty string self._scale_ratio_A_128 = 1 # init to 1 self._scale_ratio_A_64 = 1 # init to 1 self._scale_ratio_B = 1 # init to 1 self._debug_mode = False # init debug mode to False self._pstdev_filter = True # pstdev filter is by default ON GPIO.setup(self.CSID1, GPIO.OUT) # pin _pd_sck is output only GPIO.setup(self.CSID0, GPIO.IN) # pin _dout is input only self.select_channel(select_channel) # call select channel function self.set_gain_A(gain_channel_A) # init gain for channel A
def __init__(self): self.nom = '' # Pin configuration. self.LS = "XIO-P2" #left side self.RS = "XIO-P3" #right side self.TL = "XIO-P4" #top left self.MD = "XIO-P5" #top mid self.TR = "XIO-P6" #top right self.lookup = { "XIO-P2": "leftside", "XIO-P3": "rightside", "XIO-P4": "topleft", "XIO-P5": "mid", "XIO-P6": "topright" } # array makes setup a bit easier: self.buttons = [self.RS, self.LS, self.TL, self.MD, self.TR] for b in self.buttons: # Setup input for pin GPIO.setup(b, GPIO.IN) # Setup edge detects for pins. Rising and Both have different values for de-bounce time, for testing. GPIO.add_event_detect(b, GPIO.FALLING, self.fallcall, 300)
def testFreq(): GPIO.setup("CSID1", GPIO.OUT) while True: # do 24 times # Pulse the ADC once GPIO.output("CSID1", GPIO.HIGH) # push to high to get the value GPIO.output("CSID1", GPIO.LOW) # end low
def main(): logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') GPIO.cleanup(pin) GPIO.setup(pin, GPIO.IN) # Add Callback for Both Edges using the add_event_detect() method GPIO.add_event_detect(pin, GPIO.FALLING, doorbell_handler) try: while (not time.sleep(5)): print("watching " + pin) except: GPIO.cleanup(pin)
def blink(n, f): t = (1.0/f) / 2.0 GPIO.output("CSID0", 0) for x in range(n+1): GPIO.output("CSID0", 1) time.sleep(t) GPIO.output("CSID0", 0) time.sleep(t)
def update_clock_leds(): binary_time = get_binary_time() print_time(binary_time) #load values into pins for index in range(0,6): GPIO.output(hour_leds[index], binary_time["hour"][index]) GPIO.output(minute_leds[index], binary_time["minute"][index]) GPIO.output(second_leds[index], binary_time["second"][index])
def __init__(self, addresses, invert=False, factor=1): atexit.register(GPIO.cleanup) self.factor = factor if invert: self.factor *= -1 self.encoders = {} for address in addresses: self.encoders[address] = I2C.get_i2c_device(address, busnum=1) try: with open("/sys/class/gpio/unexport", "w") as unexport: unexport.write("205\n") except IOError: pass self.intr = "PWM1" GPIO.setup(self.intr, GPIO.IN, pull_up_down=GPIO.PUD_OFF) self.residual = 0 self.turn_cb = None self.press_cb = None
def read_commands(self): commandList = [] while self.running: command = self.bluetooth.read() if command == self.startflag: command = self.bluetooth.read() aux = b'' while command != self.endflag: if command != self.splitflag: aux += command else: commandList.append(int(aux.decode('utf-8'))) aux = b'' command = self.bluetooth.read() time.sleep(0.5) print("------------------------------------------") print("Commands: ", commandList) print("------------------------------------------") return commandList elif command == self.stopflag: GPIO.output("XIO-P0", GPIO.HIGH) time.sleep(0.1) GPIO.output("XIO-P0", GPIO.LOW) time.sleep(0.5)
def __init__(self, color, inputPin, outputPin): self.__color = color self.__outputPin = outputPin self.__inputPin = inputPin self._isOn = False GPIO.setup(outputPin, GPIO.OUT) GPIO.setup(inputPin, GPIO.IN) GPIO.output(outputPin, GPIO.HIGH) # turn LED off (active low common cathode form)
def begin(self, s): self._size = s if self._size == RA8875sizes.RA8875_480x272: self._width = 480 self._height = 272 elif self._size == RA8875sizes.RA8875_800x480: self._width = 800 self._height = 480 else: return False # GPIO.setup('CSIPCK',GPIO.IN, pull_up_down=GPIO.PUD_UP) # pinMode(_cs, OUTPUT); GPIO.setup(self._cs, GPIO.OUT, initial=1) # digitalWrite(_cs, HIGH); # GPIO.output(self._cs, GPIO.HIGH) # pinMode(_rst, OUTPUT); GPIO.setup(self._rst, GPIO.OUT) # digitalWrite(_rst, LOW); GPIO.output(self._rst, GPIO.LOW) # delay(100); time.sleep(0.1) # digitalWrite(_rst, HIGH); GPIO.output(self._rst, GPIO.HIGH) # delay(100); time.sleep(0.1) self.spi = spidev.SpiDev() self.spi.open(32766, 0) # self.spi.max_speed_hz = 125000 self.spi.max_speed_hz = 2000000 self.spi.mode = 0b00 # self.spi.cshigh = False # self.spi.lsbfirst = False # self.spi.no_cs = True x = self.readReg(0x00) # print hex(x) if x != 0x75: return False self.initialize() return True
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 enable_rx(self): """Enable RX, set up GPIO and add event detection.""" if self.tx_enabled: _LOGGER.error("TX is enabled, not enabling RX") return False if not self.rx_enabled: self.rx_enabled = True GPIO.setup(self.gpio, GPIO.IN) GPIO.add_event_detect(self.gpio, GPIO.BOTH) GPIO.add_event_callback(self.gpio, self.rx_callback) _LOGGER.debug("RX enabled") return True
def output_setup(device): # If the device is set to 'Output' if pass_data['devices'][device]['input_output'] == 'Output': GPIO.setup(pass_data['devices'][device]['pin'], GPIO.OUT) # Set the pin to output # If the device is set to 'Output' and the default state is 'High' elif (pass_data['devices'][device]['defaultstate'] == 'High' and pass_data['devices'][device]['input_output'] == 'Output'): GPIO.output(pass_data['devices'][device]['pin'], GPIO.HIGH) # Set the pin state High # If the device is set to 'Output' and the default state is 'Low' elif (pass_data['devices'][device]['defaultstate'] == 'Low' and pass_data['devices'][device]['input_output'] == 'Output'): GPIO.output(pass_data['devices'][device]['pin'], GPIO.LOW) # Set the pin state to Low
def buttoncallback(button): global flashing if flashing: return flashing = True if button == BTN1: printlog("TEAM 1 GOAL!") GPIO.output(LED1, ON) if updateScore(0): blink(FLASH_TIME, FLASH_COUNT, LED1) else: GPIO.output(LED1, OFF) else: printlog("TEAM 2 GOAL!") GPIO.output(LED2, ON) if updateScore(1): blink(FLASH_TIME, FLASH_COUNT, LED2) else: GPIO.output(LED2, OFF) flashing = False
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 _state(): # Get the current state of the button state = request.args.get('state') # Get the current pin device = request.args.get('device') pin = pass_data['devices'][device]['pin'] if pass_data['devices'][device]['reverse_logic'] == 'No': # for reverse high/low logic if state=="Power On": # If the current state of the button is 'Power On' GPIO.output(pin, GPIO.HIGH) # Set that pin state to High pass_data['devices'][device]['state'] = 'On' # Set the device state in the live dictionary else: GPIO.output(pin, GPIO.LOW) # Set the pin state to Low pass_data['devices'][device]['state'] = 'Off' # Set the device state in the live dictionary else: # for reverse high/low logic if state=="Power On": # If the current state of the button is 'Power On' GPIO.output(pin, GPIO.LOW) # Set that pin state to Low pass_data['devices'][device]['state'] = 'On' # Set the device state in the live dictionary else: GPIO.output(pin, GPIO.HIGH) # Set the pin state to High pass_data['devices'][device]['state'] = 'Off' # Set the device state in the live dictionary return ""
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 __init__(self, spi_bus, spi_device, reset_pin): self.spi = spidev.SpiDev() self.spi.open(spi_bus, spi_device) self.reset_pin = reset_pin if hasattr(GPIO, "setmode"): GPIO.setmode(GPIO.BOARD) try: GPIO.setup(self.reset_pin, GPIO.OUT) except: pass GPIO.output(self.reset_pin, GPIO.HIGH) self.RC522_Init()
def __init__(self): self.MATRIX = [[1,2,3,'A'], [4,5,6,'B'], [7,8,9,'C'], ['*',0,'#','D']] self.ROW = ["XIO-P0","XIO-P2","XIO-P4","XIO-P6"] self.COL = ["XIO-P1","XIO-P3","XIO-P5","XIO-P7"] for j in range(4): GPIO.setup(self.COL[j], GPIO.OUT) GPIO.output(self.COL[j], 1) for i in range(4): GPIO.setup(self.ROW[i], GPIO.IN)
#!/usr/bin/python import time import argparse import CHIP_IO.GPIO as GPIO def blink(n, f): t = (1.0/f) / 2.0 GPIO.output("CSID0", 0) for x in range(n+1): GPIO.output("CSID0", 1) time.sleep(t) GPIO.output("CSID0", 0) time.sleep(t) if __name__ == "__main__": ''' parseDIFLog.py -i file_to_parse ''' parser = argparse.ArgumentParser(description='open process log file, parse it according to parse function') parser.add_argument('-n', dest='num_cycles', type=int, help='number of cycles') parser.add_argument('-f', dest='freq', type=int, help='frequency in Hz') args = parser.parse_args() GPIO.setup("CSID0", GPIO.OUT) blink(100, 0.1)
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)
def configure_pins(): GPIO.cleanup() for index in range(0,6): GPIO.setup(hour_leds[index], GPIO.OUT) GPIO.setup(minute_leds[index], GPIO.OUT) GPIO.setup(second_leds[index], GPIO.OUT)