def getValOut(pinnum): "This prints a passed string into this function" gpio_in = GPIO(pinnum, "out") value = gpio_in.read() gpio_in.close() return value
def setUp(self): super().setUp() base.SetInitialGPIOState() with GPIO.write_context(): GPIO.output(REED_LOWER, REED_CLOSED) # Kontakt oben offen GPIO.output(REED_UPPER, REED_OPENED) # Kontakt unten geschlossen self.controller = controlserver.Controller(start_jobs=False)
class Robot: def __init__(self): self.udp_server = UDPServer() self.gpio = GPIO() self.camera = Camera() self.logger = Logger() self.drives = [0, 0] self.model = None self.auto = False print('Started') def update(self): message = self.udp_server.read() image = self.camera.capture() if message: left_drive, right_drive, auto = message.split(',') self.auto = auto != '0' self.drives = (float(left_drive), float(right_drive)) if self.auto: if not self.model: print('Loading model') self.model = Operation.restore('./model') print('Model loaded') self.drives = self.model( down_sample(to_gray(image), config.sampling))[0] else: if self.drives[0] or self.drives[1]: self.logger.log(image, *self.drives) self.gpio.update(max(self.drives[0], 0), max(-self.drives[0], 0), max(self.drives[1], 0), max(-self.drives[1], 0)) return message
class Application: def __init__(self, **kwargs): self.verbose = kwargs.get('verbose', DEFAULT_VERBOSE) self.webcam = Webcam(**kwargs) self.gpio = GPIO(inputs = INPUT_PINS, outputs = OUTPUT_PINS) def main_loop(self): i = 0 try: self.gpio.export() while True: button_state = self.gpio[SNAP_BUTTON_PIN] self.gpio[SNAP_LED_PIN] = button_state if button_state: dt = datetime.datetime.now() filename_prefix = dt.strftime("%Y-%m-%d_%H_%M_%S") filename_suffix = "_img%03d" % i self.webcam.take_photo(filename_prefix = filename_prefix, filename_suffix = filename_suffix, blocking = True, ) self.gpio[SNAP_LED_PIN] = button_state time.sleep(SLEEP_TIME) except KeyboardInterrupt: if self.verbose: print "user aborted capture...goodbye" finally: self.gpio.unexport()
def setInterruptHandler(self): #~ return with self.lock: self.unsetInterruptHandler() GPIO.add_event_detect(self.irq_gpio, GPIO.RISING, callback=self.interruptHandler)
def __init__(self): self.udp_server = UDPServer() self.gpio = GPIO() self.camera = Camera() self.logger = Logger() self.drives = [0, 0] self.model = None self.auto = False print('Started')
def runningDark(count, period): i = 0 j = 0 while j < count: for i in range(8): GPIO.output(i, 0) time.sleep(period) GPIO.output(i, 1) time.sleep(period) j = j + 1
def init_writer(self): """Overwrites the init_writer() method of the BayEOSGatewayClient class.""" # gpio pins ADDR_PINS = [11, 12, 13, 15, 16, 18] # GPIO 17, 18, 27, 22, 23, 24 DATA_PIN = 24 # GPIO 8 EN_PIN = 26 # GPIO 7 self.gpio = GPIO(ADDR_PINS, EN_PIN, DATA_PIN) self.init_sensors() self.addr = 1 # current address
def test_CloseDoorByContact(self): ftr = self.CloseDoorTest() with GPIO.write_context(): GPIO.output(REED_LOWER, REED_CLOSED) # Kontakt oben offen GPIO.output(REED_UPPER, REED_OPENED) # Kontakt unten geschlossen self.assertTrue(ftr.WaitForResult(), "Door is closed.") self.assertLess( ftr.GetRuntime(), DOOR_MOVE_UP_TIME, "Door close duration has not been reached due to contact.")
def StopMotor(self, end_state:int = DOOR_NOT_MOVING): """ Schaltet die Releais zur Motorsteuerung so, dass der Motor ausgeht und die Drehrichtung zurückgesetzt wird. :param int end_state: der damit erreichte Status der Tür, in der Regel also :data:`config.DOOR_OPEN` oder :data:`config.DOOR_CLOSED`. """ self.info("Stopping motor.") GPIO.output(MOTOR_ON, RELAIS_OFF) GPIO.output(MOVE_DIR, MOVE_UP) self._SetDoorState(end_state)
def SwitchIndoorLight(self, swon:bool): """ Schaltet die Innenbeleuchtung ein, wenn ``swon`` True ist. (sonst aus). .. seealso:: :meth:`SwitchOutdoorLight` :meth:`IsIndoorLightOn` """ self.light_state_indoor = swon GPIO.output(LIGHT_INDOOR, RELAIS_ON if swon else RELAIS_OFF) self.info("Switched indoor light %s", "on" if swon else "off") self._CallStateChangeHandler()
def ws_on_data(ws, msg, op_code, last): if op_code == websocket.ABNF.OPCODE_TEXT: pass else: data = msg dataLen = len(msg) if dataLen == 4: # 4 bytes of 0000 means the last packet (b0,b1,b2,b3) = struct.unpack_from('BBBB',msg) if b0 == 0xff and b1 == 0 and b2 == 0 and b3 == 0: print "Receive Finished" GPIO.ptt_off() return elif b0 == 0xff and b1 == 1 and b2 == 0 and b3 == 0: print "Receive Started" GPIO.ptt_on() return # handle the command protorol #i = (struct.unpack_from('>I',msg))[0] #if i == 0: # print "Receive Finished" # return packetLen = (struct.unpack_from('>I',msg))[0] if packetLen == 0: # invalid packet length, should be the last packet return if packetLen != (dataLen - 4): print "Invalid packet length %d, actual data length: %d" % (packetLen,dataLen) return # #Test code # (a,b,c,d) = struct.unpack_from('BBBB',msg,4) # print "%s,%s,%s,%s" % (hex(a),hex(b),hex(c),hex(d)) # #print "Frame length %d" % frameLen # #print binascii.hexlify(msg) offset = 4 count = 0; pcm_frames = [] while offset < packetLen: t = struct.unpack_from('B',msg,offset) frameLen = t[0] frameData = msg[offset + 1:offset + frameLen + 1] #print "frame %d, %d bytes" % (count,frameLen) # how to read the bytes here ? pcm_frames.append(audio.decode(frameData)) #audio.play(audio.decode(frameData)) count+=1 offset += (frameLen + 1) print "Received %d bytes of data, decoded into %d frames, %d ms" %(dataLen, count,count * 20) audio.play(b''.join(pcm_frames))
def brake(self, current_delay, direction): self._stop = False accel_index = min(range(len(self._bra_curve)), key=lambda i: abs(self._bra_curve[i]-current_delay)) logging.debug("braking down within %d steps", accel_index) for step in xrange(accel_index): step_delay = self._bra_curve[accel_index-step] GPIO.output(self.PUL, True) GPIO.output(self.PUL, False) self._steps += 2*(direction-.5)*self._positive if self._steps_per_rev > 0: self._angle += (direction-.5)*(self._positive*720./self._steps_per_rev) self._angle %= 360 time.sleep(step_delay) self.step(accel_index, not direction) self._stop = True
def test_OpenDoorByContact(self): #ctrl.board.door_state = DOOR_CLOSED #with GPIO.write_context(): # GPIO.output(REED_LOWER, REED_CLOSED) ftr = self.OpenDoorTest() with GPIO.write_context(): GPIO.output(REED_LOWER, REED_OPENED) # Kontakt unten offen GPIO.output(REED_UPPER, REED_CLOSED) # Kontakt oben geschlossen self.assertTrue(ftr.WaitForResult(), "Door is open.") self.assertLess( ftr.GetRuntime(), DOOR_MOVE_UP_TIME, "Door open duration has not been reached due to contact.")
def SetInitialGPIOState(): """ Setzt den initialen GPIO-Status für die Tests. """ if not hasattr(GPIO, 'allow_write'): raise RuntimeError("Need GPIO dummy for setting initial board state!") with GPIO.write_context(): GPIO.setmode(GPIO.BOARD) GPIO.output(REED_UPPER, REED_OPENED) GPIO.output(REED_LOWER, REED_CLOSED) # Tür geschlossen GPIO.output(SHUTDOWN_BUTTON, 1)
def sendFrame(self, payload): with self.lock: self.unsetInterruptHandler() self.setMode( RF69_MODE_STANDBY ) #; //turn off receiver to prevent reception while filling fifo while ((self.readReg(REG_IRQFLAGS1) & RF_IRQFLAGS1_MODEREADY) == 0x00): print "not ready" pass # // Wait for ModeReady self.writeReg(REG_DIOMAPPING1, RF_DIOMAPPING1_DIO0_00) #; // DIO0 is "Packet Sent" #~ bufferSize = len(payload) self.spi.write_then_read( [REG_FIFO | 0x80, len(payload)] + payload, 0) # /* no need to wait for transmit mode to be ready since its handled by the radio */ self.setMode(RF69_MODE_TX) #~ print "sendFrame: waiting for irq" status = GPIO.wait_for_edge(self.irq_gpio, GPIO.RISING, timeout=0.6) if status: #~ print "sendFrame: got irq RISING edge" pass else: print "error: no irq detected. going back to standby mode" self.setStandby()
def IsReedClosed(self, reed_pin:int)->bool: """ Gibt an, ob der Magnetkontakt am entsprechenden Pin geschlossen ist. Da es immer wieder Probleme durch Interferenzen mit dem Weidezaun gab, werden hier 15 Messungen in 0,7 Sekunden durchgeführt. Wenn mindestens 5x der Kontakt als geschlossen ermittelt wurde, wird der gehen wir hier von einem echten Schließen aus. :param int reed_pin: Pin des Magnetkontakts, also entweder :data:`config.REED_UPPER` oder :data:`config.REED_LOWER` :returns: Ob der angegebene Magentkontakt geschlossen ist. .. seealso:: :meth:`IsDoorOpen` :meth:`IsDoorClosed` :meth:`SyncMoveDoor` """ triggered = i = 0 for i in range(15): if GPIO.input(reed_pin) == REED_CLOSED: if triggered > 4: # der Magnetkontakt war jetzt 4x # geschlossen, damit ist die Bedingung erfüllt self.info("Reed trigger: %d of %d", triggered, i) return True triggered += 1 if i < 14: # nach dem letzten Messen warten wir nicht time.sleep(0.05) self.info("Reed trigger: %d of %d", triggered, i) return False
def sendFrame(self, payload): with self.lock: self.unsetInterruptHandler() self.setMode(RF69_MODE_STANDBY)#; //turn off receiver to prevent reception while filling fifo while ((self.readReg(REG_IRQFLAGS1) & RF_IRQFLAGS1_MODEREADY) == 0x00): print "not ready" pass # // Wait for ModeReady self.writeReg(REG_DIOMAPPING1, RF_DIOMAPPING1_DIO0_00) #; // DIO0 is "Packet Sent" #~ bufferSize = len(payload) self.spi.write_then_read([REG_FIFO | 0x80, len(payload)] + payload, 0); # /* no need to wait for transmit mode to be ready since its handled by the radio */ self.setMode(RF69_MODE_TX); #~ print "sendFrame: waiting for irq" status = GPIO.wait_for_edge(self.irq_gpio, GPIO.RISING, timeout = 0.6) if status: #~ print "sendFrame: got irq RISING edge" pass else: print "error: no irq detected. going back to standby mode" self.setStandby()
def __init__(self, spi_major = 0, spi_minor = 5, spi_speed = 500000, irq_gpio = 36): self._mode = None self.__payloadlen = 0 self.spi = spidev.SPI() self.spi.open(spi_major, spi_minor) self.spi.msh = spi_speed self.irq_gpio = irq_gpio GPIO.setup(self.irq_gpio, GPIO.IN) self.data_event = Event() self.lock = threading.RLock()
def __init__(self, pwm_args, dir_args, enable_args): """ :param pwm_args: e.g. {'gpio_name': 'GPIO7A1', 'mux': 1, 'name': 'PWM1', 'freq': 'xx', 'duty': 'xx'} :param dir_args: e.g. {'name': 'GPIO8A4', 'write': 0} :param enable_args: e.g. {'name': 'GPIO8A7', 'write': 1} """ self._pwm = SmartPwm(pwm_args['name']) self._pwm.set_config(pwm_args['freq'], pwm_args['freq'] / 2) self._dir = GPIO(dir_args['name']) self._dir.set_output() self._dir.write(dir_args['write']) self._enable = GPIO(enable_args['name']) self._enable.set_output() self._enable.write(enable_args['write'])
def elaborate(self, platform: Platform) -> Module: m = Module() imem = Memory(width=32, depth=128, init=self.imem_init) dmem = Memory(width=32, depth=128) m.submodules.cpu = cpu = Misato(xlen=XLEN.RV32, with_RVFI=False) m.submodules.gpio = gpio = GPIO() m.submodules.imem_r = imem_r = imem.read_port() m.submodules.dmem_r = dmem_r = dmem.read_port() m.submodules.dmem_w = dmem_w = dmem.write_port() # Connect cpu and instruction memory m.d.comb += cpu.i_instr.eq(imem_r.data) m.d.comb += imem_r.addr.eq(cpu.o_i_addr[2:]) # Connect cpu write to data bus arbiter with m.If(cpu.o_d_addr == 0x80): m.d.comb += gpio.i_w_en.eq(cpu.o_d_Wr) m.d.comb += dmem_w.en.eq(0) with m.Else(): m.d.comb += gpio.i_w_en.eq(0) m.d.comb += dmem_w.en.eq(cpu.o_d_Wr) # Connect cpu to data bus m.d.comb += gpio.i_data.eq(cpu.o_d_data) m.d.comb += dmem_r.addr.eq(cpu.o_d_addr) m.d.comb += cpu.i_data.eq(dmem_r.data) m.d.comb += dmem_w.addr.eq(cpu.o_d_addr) m.d.comb += dmem_w.data.eq(cpu.o_d_data) m.d.comb += self.o_gpio.eq(gpio.o_data) m.d.comb += self.o_trap.eq(cpu.o_trap) return m
def clockinit(args): POL = GPIO("480", "out") CLK = GPIO("481", "out") clock = Clock(CLK, POL) statestore = StateStore(clock) statestore.restore() nvramstore = NVRAMStore(clock) if args.require_nvram and not nvramstore.restore(): print "Cannot read clock state from the NVRAM. Exiting..." sys.exit(1) if args.invert: clock.inverse = True if args.uninvert: clock.inverse = False if args.state: clock.setState(args.state) return (clock, statestore, nvramstore)
def StartMotor(self, direction:int): """ Schaltet die Motorsteuerungsrelais so, dass sich der Motor in die entsprechende Richtung dreht. :param direction: Drehrichung. Der Einfachheit halber wird hier :data:`config.MOVE_UP` bzw. :data:`config.MOVE_DOWN` für die Richtung erwartet und entspricht damit der Bewegungsrichtung der Tür. .. seealso:: :meth:`SyncMoveDoor` :meth:`StopMotor` :meth:`_SetDoorState` """ self.info("Starting motor (%s).", "up" if direction == MOVE_UP else "down") GPIO.output(MOVE_DIR, direction) GPIO.output(MOTOR_ON, RELAIS_ON) self._SetDoorState(DOOR_MOVING_UP if direction == MOVE_UP else DOOR_MOVING_DOWN)
def OnShutdownButtonPressed(self, *_args): """ Interrupt-Methode für den Taster am Pin :data:`config.SHUTDOWN_BUTTON`. Wird mit einer Bouncetime von 200ms an beiden Flanken gerufen, also sowohl wenn der Taster gedrückt also auch losgelassen wurde. Da der Taster über einen 10K - Pullup den Pin auf LOW zieht, wird bei einem LOW Signal davon ausgegangen, dass der Taster gedrückt und bei einem HIGH Signal losgelassen wurde. Zur Vermeidung der Interpretation von Fehlsignalen, wird auch genau diese Reihenfolge (erst drücken, dann loslassen) erwartet und in allen andere Fällen keine Verarbeitung durchgeführt. Hierzu wird der Zeitpunkt des Drückens in :attr:`shutdown_btn_time` verwendet. Bei einem LOW-Signal (gedrückt) muss dieser 0 sein und wird dann auf die aktuelle Zeit gesetzt, bei HIGH (losgelassen) darf er nicht 0 sein und wird nach Auswertung wieder auf 0 gesetzt. Die so ermittelt Zeit führt dann zu jeweiligen Aktion: - länger als :data:`config.BTN_DURATION_SHUTDOWN` Sekunden: Shutdown - länger als :data:`config.BTN_DURATION_REBOOT` Sekunden: Reboot - weniger als :data:`config.BTN_DURATION_REBOOT` Sekunden: keine Aktion Die Aktionen werden über ``os.system`` ausgeführt, der Prozess muss also entsprechende Rechte verfügen. """ # der Button zieht das permanente HIGH-Signal auf LOW, wenn # er gedrückt wird (PULL_UP) if GPIO.input(SHUTDOWN_BUTTON) == GPIO.LOW: # der Knopf ist gedrückt. if self.shutdown_btn_time != 0: # da stimmt was nicht, wir ignorieren lieber alles, # setzen den Wert aber zurück self.shutdown_btn_time = 0 return self.shutdown_btn_time = time.time() else: # der Knopf wurde losgelassen if self.shutdown_btn_time == 0: # auch hier wäre jetzt was verkehrt, also # ignorieren return # jetzt prüfen, wie lange er gedrückt war. pressed_duration = time.time() - self.shutdown_btn_time # und setzen den Wert wieder zurück self.shutdown_btn_time = 0 self.info("Shutdown button has been pressed for %.2f seconds.", pressed_duration) if pressed_duration > BTN_DURATION_SHUTDOWN: # shutdown self.info("Shutting system down.") os.system("sudo shutdown -h now") elif pressed_duration > BTN_DURATION_REBOOT: # reboot self.info("Rebooting system.") os.system("sudo reboot -h now")
def __init__(self, spi_major=0, spi_minor=5, spi_speed=500000, irq_gpio=36): self._mode = None self.__payloadlen = 0 self.spi = spidev.SPI() self.spi.open(spi_major, spi_minor) self.spi.msh = spi_speed self.irq_gpio = irq_gpio GPIO.setup(self.irq_gpio, GPIO.IN) self.data_event = Event() self.lock = threading.RLock()
def OpenDoorTest(self): ctrl = self.controller ftr = base.Future(ctrl.OpenDoor) self.assertTrue(ftr.WaitForExectionStart(0.5), "Door open command is running.") with self.assertRaises(TimeoutError): ftr.WaitForResult(0.5) with GPIO.write_context(): motor_on = GPIO.input(MOTOR_ON) move_dir = GPIO.input(MOVE_DIR) self.assertEqual(ctrl.automatic, DOOR_AUTO_OFF, "Door automatic is temporary disabled.") self.assertEqual(motor_on, RELAIS_ON, "Motor is running.") self.assertEqual(move_dir, MOVE_UP, "Door is moving up.") self.assertTrue(ctrl.board.IsDoorMoving(), "Door state is 'moving'.") return ftr
def __init__(self): self.pins = [GPIO(12), GPIO(13), GPIO(182)] self.process = None self.colors_dict = { "off": [0, 0, 0], "red": [1, 0, 0], "green": [0, 1, 0], "blue": [0, 0, 1], "white": [1, 1, 1], "yellow": [1, 1, 0], "cyan": [0, 1, 1], "magenta": [1, 0, 1], "orange": [1, 0.4, 0], "weakred": [0.1, 0, 0] } self.pwm_channels = [0, 1, 2] #red, green, blue
def __init__(self, name, pins, min_angle=-5, max_angle=365, positive=1, vend=4500, vstart=20, skewness=.75, accel_steps=4000, skewnessbra=.9, bra_steps=500): def _accel_velocity(x): """ calculate the acceleration/deceleration velocity in the interval [0,1] """ return (.5-.5*cos(x*pi))*(vend-vstart)+vstart def _accel_skewing(x): """ skew the velocity cosine by a parabolic function """ return pow(x, skewness)/pow(accel_steps, skewness) def _bra_skewing(x): """ skew the velocity cosine by a parabolic function """ return pow(x, skewnessbra)/pow(bra_steps, skewnessbra) self.name = name self.PUL, self.DIR, self.ENBL = pins self._steps_per_rev = 0 self._enabled = True self._angle = 0 self._min_angle = min_angle self._max_angle = max_angle self._steps = 0 self._stop = True self._delay = 1./vend self._positive = positive self._brake_steps = accel_steps for p in pins: GPIO.setup(p, GPIO.OUT) GPIO.output(p, False) self._accel_curve = [ 1./_accel_velocity(_accel_skewing(x)) \ for x in xrange(accel_steps) ] self._bra_curve = [ 1./_accel_velocity(_bra_skewing(x)) \ for x in xrange(bra_steps) ]
def __init__(self, logger): LoggableClass.__init__(self, logger=logger) self.door_state = DOOR_NOT_MOVING self.shutdown = False self._needs_update = True self.last_input = time.time() self.condition = Condition() self.tft_state = True self.light_state_indoor = False self.light_state_outdoor = False self.slots = { (250, 40, 310, 85): self.doorUp, (250, 105, 310, 165): self.doorStop, (250, 185, 310, 230): self.doorDown, (0, 150, 115, 240): self.switchOutdoorLight, (116, 150, 230, 240): self.switchIndoorLight, (0, 50, 230, 100): self.switchDoorAutomatic, } self.setState({}) GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) self.tft = lib_tft24t.TFT24T(spidev.SpiDev(), GPIO, landscape=True) self.tft.initLCD(self.DC, self.RST, self.LED, switch_on=self.tft_state) self.tft.initTOUCH(self.TOUCH_IRQ) # TOUCH_IRQ = Pen! GPIO.add_event_detect(self.TOUCH_IRQ, GPIO.BOTH, callback=self.onTouchEvent, bouncetime=250) InstallStateChangeHandler(self, self.onStateChanged, self.shouldShutdown)
def step(self, steps, direction): if steps: delay = 0 logging.debug("INPUT -- %s: actual_step/steps/direction: %d / %d / %d", self.name, self._steps, steps, direction) self._stop = False GPIO.output(self.DIR, direction) for step in xrange(steps): try: step_delay = self._accel_curve[min(step, abs(step-(steps-1)))] except: step_delay = self._delay if self._stop or \ (self._angle <= self._minimum and not direction) or \ (self._angle >= self._maximum and direction): logging.debug("BREAK -- %s: actual_step/steps/direction: %d / %d / %d", self.name, self._steps, steps, direction) self.brake(step_delay, direction) break GPIO.output(self.PUL, True) GPIO.output(self.PUL, False) self._steps += 2*(direction-.5)*self._positive if self._steps_per_rev > 0: self._angle += (direction-.5)*(self._positive*720./self._steps_per_rev) self._angle %= 360 time.sleep(step_delay) logging.debug("END -- %s: actual_step/steps/direction: %d / %d / %d", self.name, self._steps, steps, direction)
def printme(pinnum, boolval): "This prints a passed string into this function" gpio_out = GPIO(pinnum, "out") value = boolval gpio_out.write(value) gpio_out.close() return str(True)
def main(): if __name__ == "__main__": #GPIO part GPIO.init(radio_on_cb=radio_cor_on_callback,radio_off_cb=radio_cor_off_callback) #Audio part global audio player = config_get_audio_player() #Could be None/aplay/sox audio = Audio(player=player,record_callback=recorder_callback) audio.open() global WS_DEBUG, ws if WS_DEBUG: websocket.enableTrace(True) else: websocket.enableTrace(False) callsign = config_get_callsign() print "CALLSIGN: %s" % callsign url = "ws://aprs.hamclub.net:20880/mtracker/talkbox0?type=sub&udid=" + callsign ws = websocket.WebSocketApp(url, #ws = websocket.WebSocketApp("ws://localhost:8080/mclub/talk0?type=sub&udid=bg5hxe", #on_message = ws_on_message, on_data = ws_on_data, on_error = ws_on_error, on_close = ws_on_close) ws.on_open = ws_on_open stopFlag = Event() timer = KeepAliveThread(stopFlag,ws) timer.start() ws.run_forever() stopFlag.set() #stop the timer audio.close() GPIO.cleanup()
def test_OutdoorLight(self): # --- Aussenbeleuchtung --- self.assertFalse(self.board.IsOutdoorLightOn(), "Outdoor light should be initially off.") with GPIO.write_context(): self.assertEqual(GPIO.input(LIGHT_OUTDOOR), RELAIS_OFF, "Outdoor light pin is not off.") self.board.SwitchOutdoorLight(False) self.assertFalse(self.board.IsOutdoorLightOn(), "Outdoor light should be off.") with GPIO.write_context(): self.assertEqual(GPIO.input(LIGHT_OUTDOOR), RELAIS_OFF, "Outdoor light pin is not off.") self.board.SwitchOutdoorLight(True) self.assertTrue(self.board.IsOutdoorLightOn(), "Outdoor light should be on.") with GPIO.write_context(): self.assertEqual(GPIO.input(LIGHT_OUTDOOR), RELAIS_ON, "Outdoor light pin is not on.") self.board.SwitchOutdoorLight(False) self.assertFalse(self.board.IsOutdoorLightOn(), "Outdoor light should be off.") with GPIO.write_context(): self.assertEqual(GPIO.input(LIGHT_OUTDOOR), RELAIS_OFF, "Outdoor light pin is not off.")
def __init__(self, master=None): #ensure environment is set up and ready to go. self.a = assets() self.g = GPIO() self.l = light_ctrl() Frame.__init__(self, master) self.configure(background='#333', cursor='none') master.bind("<Button-1>", self.init_capture) master.bind("<Button-3>", self.quit_me) self.focus_set() self.pack() self.webcam = True self.capture = False self.createWidgets() self.populateWidgets()
class Fan(): def __init__(self): self.pin = 18 self.mode = 1 #open is 1 close is 0 self.mgpio = GPIO() self.mgpio.setPinMode(pin=self.pin, mode=1) #OUTPUT 1 INPUT 0 def on(self): '' self.mgpio.setV(self.pin, self.mode) def off(self): '' self.mgpio.setV(self.pin, self.mode & 0) def status(self): #0 is off 1 is on return self.mgpio.getV(self.pin)
def init_chip(): """Before we can measure temperature and pressure, the chip needs to be initialized and reset. The process is relatively straight forward. First, pull the PS low to activate the SPI protocol Second, issue the reset command Third, pull the PS high Short waits are issued between each action to allow the chip to activate the proper routine :return: a reference to the chip that can be used to actually measure temperature and pressure """ chip = GPIO() chip.pin_mode(CHIP_SELECT, chip.OUTPUT) chip.write_pin(CHIP_SELECT, 1) time.sleep(LONG_WAIT) with spi_mode(chip): chip.send_data([RESET_COMMAND]) time.sleep(LONG_WAIT) return chip
def __init__(self, **kwargs): self.verbose = kwargs.get('verbose', DEFAULT_VERBOSE) self.webcam = Webcam(**kwargs) self.gpio = GPIO(inputs = INPUT_PINS, outputs = OUTPUT_PINS)
def unsetInterruptHandler(self): #~ return with self.lock: GPIO.remove_event_detect(self.irq_gpio)
# gpio pins ADDR_PINS = [11, 12, 13, 15, 16, 18] # GPIO 17, 18, 27, 22, 23, 24 DATA_PIN = 24 # GPIO 8 EN_PIN = 26 # GPIO 7 # configuration for BayEOSWriter and BayEOSSender PATH = '/tmp/raspberrypi/' NAME = 'RaspberryPi' URL = 'http://bayconf.bayceer.uni-bayreuth.de/gateway/frame/saveFlat' # instantiate objects of BayEOSWriter and BayEOSSender writer = BayEOSWriter(PATH) sender = BayEOSSender(PATH, NAME, URL) # initialize GPIO Board on Raspberry Pi gpio = GPIO(ADDR_PINS, EN_PIN, DATA_PIN) # initialize I2C Bus with sensors try: i2c = I2C() sht21 = SHT21(1) mcp3424 = MCP3424(i2c.get_smbus()) except IOError as err: sys.stderr.write('I2C Connection Error: ' + str(err) + '. This must be run as root. Did you use the right device number?') # measurement method def measure(seconds=10): """Measures temperature, humidity and CO2 concentration. @param seconds: how long should be measured @return statistically calculated parameters """
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #blink RPI gpio0 (BCM17) from time import sleep from gpio import GPIO p = input("gpio n : ") t = input("sleep time : ") m = input("max loop range : ") gp = GPIO(int(p),0,"out") for i in range(0,int(m)): print("write 1") gp.writeValue(1) print(gp.readValue()) sleep(float(t)) print("write 0") gp.writeValue(0) print(gp.readValue()) sleep(float(t)) print("Cleanup ...") #gp.unexport()
def __init__(self, pin): GPIO.export(pin) GPIO.direction(pin, GPIO.DIR_OUT) self._pin = pin self._value = GPIO.VAL_LOW
def on(self): GPIO.value(self._pin, GPIO.VAL_HIGH) self._value = GPIO.VAL_HIGH
def off(self): GPIO.value(self._pin, GPIO.VAL_LOW) self._value = GPIO.VAL_LOW