def setGpioState(self, gpioConfiguration, setting): logger.debug("setGpioState %s", str(setting)) if setting.dir == 'RESERVED': if debug: logger.debug("gpio reserved, do not touch") gPull = RPIO.PUD_OFF if setting.pull == None or setting.pull == 'PUD_OFF': pass elif setting.pull == 'PUD_UP': gPull = RPIO.PUD_UP elif setting.pull == 'PUD_DOWN': gPull = RPIO.PUD_DOWN else: pass if setting.dir == 'OUT': if debug: print(gpioConfiguration.portNumber) RPIO.setup(gpioConfiguration.portNumber, RPIO.OUT) elif setting.dir == 'IN': RPIO.setup(gpioConfiguration.portNumber, RPIO.IN, gPull) else: pass if setting.dir == 'OUT': if setting.default == 'low': self.low(gpioConfiguration) elif setting.default == 'high': self.high(gpioConfiguration) else: pass
def _exit_handler_(self): if self.status == True: print('[EXIT] Turning OFF the fan.') RPIO.output(self.pin, False) print('[EXIT] Performing a RESET (cleanup) of the fan GPIO (pin: ' + str(self.PIN) + ')') RPIO.cleanup()
def pwm(pin, state): if state >= 0.5: GPIO.output(pin, 1) elif state < 0.5: GPIO.output(pin, 0) else: print("Error: value not recognised, please make sure it is between 0 and 1.")
def read_gpio(self, dt): self.ready_timer -= dt if int(self.ready_timer) > 0: return self.win_text = '' p1 = RPIO.input(PIN_P1) p2 = RPIO.input(PIN_P2) if p1 and self.p1_state == 0: self.p1_state = 1 self.p1 += 1 elif not p1 and self.p1_state == 1: self.p1_state = 0 if p2 and self.p2_state == 0: self.p2_state = 1 self.p2 += 1 elif not p2 and self.p2_state == 1: self.p2_state = 0 if self.p1 >= self.score: self.win_text = 'Player 1 win !' self.ready_timer = 5. self.p1 = self.p2 = 0 elif self.p2 >= self.score: self.win_text = 'Player 2 win !' self.ready_timer = 5. self.p1 = self.p2 = 0
def setGpioState(self, gpioConfiguration, setting): logger.debug("setGpioState %s", str(setting)) if setting.dir == 'RESERVED': if debug: logger.debug("gpio reserved, do not touch") gPull = RPIO.PUD_OFF if setting.pull == None or setting.pull == 'PUD_OFF': pass elif setting.pull == 'PUD_UP': gPull = RPIO.PUD_UP; elif setting.pull == 'PUD_DOWN': gPull = RPIO.PUD_DOWN; else: pass if setting.dir == 'OUT': if debug: print(gpioConfiguration.portNumber) RPIO.setup(gpioConfiguration.portNumber, RPIO.OUT) elif setting.dir == 'IN': RPIO.setup(gpioConfiguration.portNumber, RPIO.IN, gPull) else: pass if setting.dir == 'OUT': if setting.default == 'low': self.low( gpioConfiguration) elif setting.default == 'high': self.high( gpioConfiguration) else: pass
def closeProgram(signal, frame): """ Close fonction""" print("\nResseting GPIO...", end="") RPIO.cleanup() #Reset every channel that has been set up by this program, and unexport interrupt gpio interfaces print(" ok") print("exiting") sys.exit(0)
def __init__(self): self.version = sv.Version("0.0.1") self._logger = lager.Lager(os.path.join(config.DB_ROOT, "events.json")) # kegs and flow self._flowMeters = [] self._flowMeters.append(sf800.SF800(config.FLOW_1_PIN)) self._flowMeters.append(sf800.SF800(config.FLOW_2_PIN)) self._kegManager = keg.KegManager(flow_meters=self._flowMeters, logger=self._logger) # thermostat self.tempSensor = w1thermsensor.W1ThermSensor() self.compressorRelay = relay.Relay(config.RELAY_PIN) self._thermostat = thermostat.Thermostat( self.tempSensor.get_temperature, self.compressorRelay, on_adds_heat=0, logger=self._logger ) self._thermostat.start() # pressure self._adcManager = ads1x15.ADS1x15Manager( [ads1x15.Channel(id=0, gain=4096, sps=8), ads1x15.Channel(id=1, gain=4096, sps=8)] ) self._adcManager.start() self._kegPressure = ms.M7139_200PG(lambda: self._adcManager.read(0)) self._tankPressure = ms.M7139_03KPN(lambda: self._adcManager.read(1)) self._carbonationVolumes = lambda: carbonation.volumes( self.tempSensor.get_temperature(), self._kegPressure.read() ) RPIO.wait_for_interrupts(threaded=True)
def __init__(self): self.version = sv.Version('0.0.1') self._logger = lager.Lager(os.path.join(config.DB_ROOT, 'events.json')) #kegs and flow self._flowMeters = [] self._flowMeters.append(sf800.SF800(config.FLOW_1_PIN)) self._flowMeters.append(sf800.SF800(config.FLOW_2_PIN)) self._kegManager = keg.KegManager(flow_meters=self._flowMeters, logger=self._logger) #thermostat self.tempSensor = w1thermsensor.W1ThermSensor() self.compressorRelay = relay.Relay(config.RELAY_PIN) self._thermostat = thermostat.Thermostat( self.tempSensor.get_temperature, self.compressorRelay, on_adds_heat=0, logger=self._logger) self._thermostat.start() #pressure self._adcManager = ads1x15.ADS1x15Manager([ ads1x15.Channel(id=0, gain=4096, sps=8), ads1x15.Channel(id=1, gain=4096, sps=8) ]) self._adcManager.start() self._kegPressure = ms.M7139_200PG(lambda: self._adcManager.read(0)) self._tankPressure = ms.M7139_03KPN(lambda: self._adcManager.read(1)) self._carbonationVolumes = lambda: carbonation.volumes( self.tempSensor.get_temperature(), self._kegPressure.read()) RPIO.wait_for_interrupts(threaded=True)
def _set_function(self, value): if value != 'input': self._pull = 'floating' try: RPIO.setup(self._number, self.GPIO_FUNCTIONS[value], self.GPIO_PULL_UPS[self._pull]) except KeyError: raise PinInvalidFunction('invalid function "%s" for pin %r' % (value, self))
def __init__(self, pin, frequency=50): self.pin = pin self.period = 1.0 / frequency self.last_cycle = 0.0 self.duty_cycle = 0.0 self.on = True rpio.output(self.pin, True)
def __init__(self): # Initialize lock servo and button. self.servo = PWM.Servo() RPIO.setup(config.BUTTON_PIN, RPIO.IN) # Set initial box state. self.button_state = RPIO.input(config.BUTTON_PIN) self.is_locked = None
def setup(): global PWR GPIO.setmode( GPIO.BCM) # Say to RPI that we're using the BCM GPIO numeration. GPIO.setup(LED, GPIO.OUT) # Set the LED pin as an output. #pwm = GPIO.PWM(LED, 200) # Coment 1: See down. PWR.start(100) # Starting at a brightness of 100%
def pulse_tdo(tck, tdo): if(DELAY): sleep(0.000005) RPIO.output(tck, 0) tdo_read = RPIO.input(tdo) RPIO.output(tck, 1) return tdo_read
def gpio_callback_1(gpio_id, val): # global lastTime1, dMax1, dMin1, dSum1, dCount1, dFirst1 # now1 = datetime.datetime.now() # dstr1 = str(now1.strftime("%H:%M:%S.%f")) # nowTime1 = time.time() # if (dFirst1 == 1): # dFirst1 = 0; # lastTime1 = nowTime1; # else: # dTime1 = nowTime1 - lastTime1 # lastTime1 = nowTime1 # if (dTime1 > dMax1): # dMax1 = dTime1 # if (dTime1 < dMin1): # dMin1 = dTime1 # dCount1 += 1 # dSum1 += dTime1 #stampa ogni tic in uscita da (3) su 555 input_value_7 = RPIO.input(INTfirst) if input_value_7==True: print "ALTO--->1" RPIO.output(LedColored,True) else: print "BASSO--->0" RPIO.output(LedColored,False) print("INTfotores: ---------------> GPIO"), gpio_id#: %s at %s delta: %08.6f" % (gpio_id, val, dstr1, dTime1))
def gpio_callback_1(gpio_id, val): # global lastTime1, dMax1, dMin1, dSum1, dCount1, dFirst1 # now1 = datetime.datetime.now() # dstr1 = str(now1.strftime("%H:%M:%S.%f")) # nowTime1 = time.time() # if (dFirst1 == 1): # dFirst1 = 0; # lastTime1 = nowTime1; # else: # dTime1 = nowTime1 - lastTime1 # lastTime1 = nowTime1 # if (dTime1 > dMax1): # dMax1 = dTime1 # if (dTime1 < dMin1): # dMin1 = dTime1 # dCount1 += 1 # dSum1 += dTime1 #stampa ogni tic in uscita da (3) su 555 input_value_7 = RPIO.input(INTfirst) if input_value_7 == True: print "ALTO--->1" RPIO.output(LedColored, True) else: print "BASSO--->0" RPIO.output(LedColored, False) print( "INTfotores: ---------------> GPIO" ), gpio_id #: %s at %s delta: %08.6f" % (gpio_id, val, dstr1, dTime1))
def ignore_stop(self): if self.flag_ignore_stop: pass else: self.flag_ignore_stop = True logger.info('ignore_stop: setup {0} as OUTPUT'.format(self.gpio_heads_stop)) RPIO.setup(self.gpio_heads_stop, RPIO.OUT)
def _loop(self): self._wait_next_event(only=['set_source']) self.rotary_setup() self.button_setup() RPIO.wait_for_interrupts()
def __init__(self, camera_controller): RPIO.set_mode(RPIO.BCM) self.servo_channels = [] self.channel_cycles = [] self.servos = {} self.actuators = {} self.camera_controller = camera_controller
def _set_led(self, pin, pwm, val): LOG.debug('set LED on pin %d to %s', pin, val) if val == 0 or val == 1: PWM.clear_channel(pwm) GPIO.output(pin, 1 - int(val)) else: PWM.add_channel_pulse(pwm, pin, 0, 1999 - int(1999 * val))
def stop_run(self): if args.verbose: print "[%s] thread : stop_run called" % (self.name) #Tell function which globals to look for (need time values as globals so that callback #function sned_triggers can also see them) global bor_time_s #Check currently running if self.running==True: print 'Stopping run : Disabling triggers' #Record EOR time eor_time_s = time.time() - bor_time_s #If in real triggers mode, stop listening to pins if args.which == 'real': RPIO.stop_waiting_for_interrupts() #If in fake triggers mode, stop fake trigger thread elif args.which == 'fake': self.fake_trigger_thread.interrupt() #Update state self.running = False print 'Run stopped : t =', eor_time_s, 's' #Can't stop run if none underway else: if args.verbose: print "[%s] thread : Could not stop run, no runs underway" % (self.name)
def test(): # setup logging FORMAT = '%(asctime)s %(levelname)s %(message)s' logging.basicConfig(format=FORMAT) logger = logging.getLogger() logger.setLevel(logging.INFO) if not logger.handlers: logger.addHandler(logging.StreamHandler()) log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' logging.basicConfig(format=log_format, level=logging.INFO) zwrs = ZwReadState(logger=logger) zwrs.startReadingState() zwrs.printData() zwrs.analyzeData() #if (zwrs.isMachineOff()): # turn on machine err = zwrs.getError("John") if (err["isErr"]): logger.info( err) else: logger.info( "No error on getError()") logger.info("Done testing") sleep(10) RPIO.cleanup()
def read_temp(): lines = read_temp_raw() while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw() equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos+2:] temp_c = float(temp_string) / 1000.0 temp_f = temp_c * 9.0 / 5.0 + 32.0 #Accendi e spegni ritmicamente tutti i led in caso di allarme (superamento soglia di temperatura) if temp_c >= temperatura: for a in ledPinsTemp: RPIO.output(a, True) time.sleep(0.1) ledOnTemp=False RPIO.output(ledPWM, True) #Accende la ventola per raffreddare #time.sleep(0.3) for a in ledPinsTemp: RPIO.output(a, False) time.sleep(0.1) ledOnTemp=False #Spegne tutti i led ed accende la ventola per il raffreddamento else: for a in ledPinsTemp: RPIO.output(a, False) time.sleep(0.1) ledOnTemp=False RPIO.output(ledPWM, False) #Spegne la ventola perchè la temperatura è sotto soglia return temp_c#, temp_f
def __init__(self, spi_device="/dev/spidev0.0", width=16, height=16): """ Initialize display driver :param str spi_device: the SPI device instance to use, optional, defaults to ``/dev/spidev0.0`` :param int width: width of the framebuffer, defaults to 16 :param int height: height of the framebuffer, defaults to 16 """ self.width = width self.height = height self.spi = SPI('/dev/spidev0.0') self.spi.mode = SPI.MODE_0 self.spi.bits_per_word = 8 self.spi.speed = 500000 RPIO.setmode(RPIO.BOARD) RPIO.setup(11, RPIO.OUT) self.frame_buffer = np.zeros((self.width, self.height, 3), dtype=np.uint8) self.clear() self.reset() self.present() time.sleep(20.0 / 1000.0) # 20 ms
def __init__(self): self.pPanL = 18 self.pTiltL = 26 self.pPanR = 23 self.pTiltR = 24 self.pPanicBtn = 17 self.pan_minL = 120 self.pan_maxL = 230 self.tilt_minL = 80 self.tilt_maxL = 210 self.pan_minR = 80 self.pan_maxR = 170 self.tilt_minR = 70 self.tilt_maxR = 230 #pan_center = ((pan_max - pan_min) / 2) + pan_min #tilt_center = ((tilt_max - tilt_min) / 2) + tilt_min self.pan_centerL = 180 self.tilt_centerL = 155 self.pan_centerR = 126 self.tilt_centerR = 160 self.inPanic = False RPIO.setmode(RPIO.BCM)
def capacity(): res = [] def times(gpio_id, val): if len(res) < 6: res.append(int((datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds() * 10000)) print("Pridano") else: G.stop_waiting_for_interrupts() G.add_interrupt_callback(7, times, edge="rising") G.wait_for_interrupts() diff_list = [] for i in range(3): diff_list.append(res[i + 1] - res[i]) diff = reduce(lambda x, y: x + y, diff_list) / len(diff_list) tl = diff * 0.33 number = (tl / 10000) / 693 prefixes = { "0" : 10**3, "1" : 10**6, "2" :10**9 } for key, value in prefixes.iteritems(): if number * value > 1 and number * value < 1000: return (number * value, key)
def on_message(cmd): if cmd.command != 'button': return RPIO.output(BUZZER, 1) time.sleep(.05) RPIO.output(BUZZER, 0)
def read_temp(): lines = read_temp_raw() while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw() equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos + 2:] temp_c = float(temp_string) / 1000.0 temp_f = temp_c * 9.0 / 5.0 + 32.0 #Accendi e spegni ritmicamente tutti i led in caso di allarme (superamento soglia di temperatura) if temp_c >= temperatura: for a in ledPinsTemp: RPIO.output(a, True) time.sleep(0.1) ledOnTemp = False RPIO.output(ledPWM, True) #Accende la ventola per raffreddare #time.sleep(0.3) for a in ledPinsTemp: RPIO.output(a, False) time.sleep(0.1) ledOnTemp = False #Spegne tutti i led ed accende la ventola per il raffreddamento else: for a in ledPinsTemp: RPIO.output(a, False) time.sleep(0.1) ledOnTemp = False RPIO.output( ledPWM, False ) #Spegne la ventola perchè la temperatura è sotto soglia return temp_c #, temp_f
def checkkey(): global lighton char = screen.getch() if char == curses.KEY_UP: drive("forward") elif char == curses.KEY_DOWN: drive("stop") elif char == curses.KEY_LEFT: drive("left") elif char == curses.KEY_RIGHT: drive("right") elif char == ord('r'): drive("reverse") elif char == ord('w'): camera("up") elif char == ord('z'): camera("down") elif char == ord('a'): camera("left") elif char == ord('d'): camera("right") elif char == ord('s'): camera("home") elif char == ord('l'): if lighton: RPIO.output(24, False) lighton = False else: RPIO.output(24, True) lighton = True
def reset(self): """ Reset the arduino, use periodically to avoid sync errors """ RPIO.output(11, RPIO.HIGH) time.sleep(1.0 / 1000.0) RPIO.output(11, RPIO.LOW) time.sleep(20.0 / 1000.0)
def setDirection(self,channel,direction): #direction 0:fwd, 1:bwd if(channel=='A'): print "set channel A direction to "+str(direction); RPIO.output(self.APHASE_Pin,direction); if(channel=='B'): print "set channel B direction to "+str(direction); RPIO.output(self.BPHASE_Pin,direction);
def stopClk(self,gpio,val): if self.timer_running==True: print "tagid %s ended run on track %s"%(self.tag_id,self.track_id) self.timer_running=False RPIO.del_interrupt_callback(self.gpio_e) self.timer_clk.stop() self.track_clk.start(5)
def test7_alt0(self): logging.info(" ") logging.info(" ") logging.info("=== ALT0 TESTS ===") print(RPIO.gpio_function(5)) logging.info("Setting up GPIO-%s as alt0...", GPIO_OUT) RPIO.setup(5, RPIO.ALT0) self.assertEqual(RPIO.gpio_function(5))
def buffer_read(reg, len): RPIO.output(CSN, False) spi.xfer2([reg]) val = [] for i in range(0, len): val.append(spi.xfer2([0x00])) RPIO.output(CSN, True) return val
def pl_switch(address, value): if value not in ["on", "off"]: raise ValueError("Switch value must be 'on' or 'off'") address = int(address) validate_address(address) set_to_output(address) RPIO.output(address, value == "on")
def force_state(self, On_Off): if On_Off == _ON: GPIO.output(self.__gpio_pin, True) return self.__return_state(self.next) elif On_Off == _OFF: GPIO.output(self.__gpio_pin, False) return self.__return_state(self.prev) raise ValueError("The input value has to be 'ON' or 'OFF'")
def setManualMode(self, newModeSetting): self.manualServoMode = newModeSetting if (self.manualServoMode == False): self.led1on = False RPIO.output(LED1_PIN, True) else: self.led1on = True RPIO.output(LED1_PIN, False)
def _disable_event_detect(self): try: RPIO.del_interrupt_callback(self.number) except KeyError: # Ignore this exception which occurs during shutdown; this # simply means RPIO's built-in cleanup has already run and # removed the handler pass
def closeProgram(signal, frame): """ Close fonction""" print("\nResseting GPIO...", end="") RPIO.cleanup( ) #Reset every channel that has been set up by this program, and unexport interrupt gpio interfaces print(" ok") print("exiting") sys.exit(0)
def stopClk(self, gpio, val): if self.timer_running == True: print "tagid %s ended run on track %s" % (self.tag_id, self.track_id) self.timer_running = False RPIO.del_interrupt_callback(self.gpio_e) self.timer_clk.stop() self.track_clk.start(5)
def reset_state(self): """ Determines the proper state when the motor is stopped""" if GPIO.input(inputs['upper']): self.state = OPEN elif GPIO.input(inputs['lower']): self.state = CLOSED else: self.state = STOPPED
def loop(): try: while True: flicker() except KeyboardInterrupt: pass finally: GPIO.cleanup()
def all_off(): for pin in pins_pol: RPIO.output(pin, False) for pin in pins_pwm: servo.set_servo(pin, 0) #set PWM pin to off mag_value = [0, 0, 0, 0]
def __init__(self, pin): self.PIN = pin # the default output for the GPIO is 0 # this means that the fan will be off at startup self.status = False RPIO.setup(pin, RPIO.OUT) RPIO.output(pin, False) atexit.register(self._exit_handler_)
def enableTrack(self,tag_id): if self.rfid_enable==True: print "tagid %s enabled track %s"%(tag_id,self.track_id) self.rfid_enable=False self.tag_id=tag_id self.track_clk.start(20000) self.rfid_label.setText("%s"%tag_id) self.timer_enable=True RPIO.add_interrupt_callback(self.gpio_b,self.startClk,edge='rising',pull_up_down=RPIO.PUD_UP,debounce_timeout_ms=None)
def handle_gpio(): RPIO.add_interrupt_callback(int(rc["gpio"]), gpio_callback, pull_up_down=RPIO.PUD_UP, edge="rising", debounce_timeout_ms=500, threaded_callback=True) slog.info("ready at gpio #%s" % rc["gpio"]) RPIO.wait_for_interrupts()
def setLedColour(colGivn): if colGivn == OFF: for i in [RED, GREEN, BLUE]: RPIO.output(i, True) elif colGivn == RED or colGivn == GREEN or colGivn == BLUE: setLedColour(OFF) RPIO.output(colGivn, False) else: pass #do nothing
def update(self, t): delta = t - self.last_cycle if self.on and delta > self.duty_cycle * self.period: rpio.output(self.pin, False) self.on = False elif delta > self.period: rpio.output(self.pin, True) self.on = True self.last_cycle = t
def setLedColour(colGivn): if colGivn == OFF: for i in [RED,GREEN,BLUE]: RPIO.output(i, True) elif colGivn == RED or colGivn == GREEN or colGivn == BLUE: setLedColour(OFF) RPIO.output(colGivn, False) else: pass #do nothing
def xshut(gpios): """ Turn off all VL53L0X devices. Takes a list of GPIO pins the devices' XSHUT ports are connected to, and brings each one to 0 volts (low) """ for x in gpios: # PNP transistors so GPIO 1 = sensor power off RPIO.setup(x, RPIO.OUT, initial=1) time.sleep(0.5)
def __init__(self): """""" RaspiRobot2.__init__(self) self.exit = False self.video = VideoSrc() RPIO.add_tcp_callback(COM_PORT, self.process) self.start_timer()
def send(self, value, mode): GPIO.output(self.__rs, mode) # If there is an RW pin incicated, set it to low to write if self.__rw: GPIO.output(self.__rw, GPIO.LOW) # Write both nibbles self.write4bits(value & 0xF0) self.write4bits((value << 4) & 0xF0)
def _shift_out_byte(self, byte): if byte > 0xFF: byte &= 0xFF warnings.warn("Value passed to __shift_out_byte is larger than a byte! Truncating.") for bit in bin(byte)[2:].zfill(8): if bit == '0': RPIO.output(self._data_in_pin, RPIO.LOW) else: RPIO.output(self._data_in_pin, RPIO.HIGH) self._tick_clock()
def on_collision(self, gpio_id, value): """""" result = value if gpio_id == self.SW1_PIN and RPIO.input(self.SW2_PIN): result +=2 elif gpio_id == self.SW2_PIN: result *= 2 if RPIO.input(self.SW1_PIN): result +=1 self.send(encode(common.ID_BUMPER, result))