def __init__(self, bus=1, device=0, speed=1000000, pin_rst=def_pin_rst, pin_ce=0, pin_irq=def_pin_irq, pin_mode=def_pin_mode): self.pin_rst = pin_rst self.pin_ce = pin_ce self.pin_irq = pin_irq self.spi = SPIClass() self.spi.open(bus, device) self.spi.mode = 0 self.spi.msh = speed if pin_mode is not None: GPIO.setmode(pin_mode) if pin_rst != 0: GPIO.setup(pin_rst, GPIO.OUT) GPIO.output(pin_rst, 1) GPIO.setup(pin_irq, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(pin_irq, GPIO.FALLING, callback=self.irq_callback) if pin_ce != 0: GPIO.setup(pin_ce, GPIO.OUT) GPIO.output(pin_ce, 1) self.init()
def moveUP(self): GPIO.add_event_detect(motor.upperSW, GPIO.RISING, bouncetime=1000) PWM.start(self.pwmPIN, self.duty, self.freq, 0) GPIO.output(self.upDIR, GPIO.HIGH) status = 1 print "Moving motor UP" return 0, time.time()
def __init__ (self , pins): self.pins = pins self.sweepStartData = dataPacket(time.time(),self.decode()) self.currentData = self.sweepStartData GPIO.add_event_detect(self.pins.button, GPIO.RISING) self.pins.pulseLatchReset() self.pins.pulseDecoderReset()
def main(): global running # other wise we cant stop thread outputs = ["P9_12", "P9_14", "P9_16", "P9_18"] inputs = ["P9_11", "P9_13", "P9_15", "P9_17"] #set up pins for out in outputs: GPIO.setup(out, GPIO.OUT) GPIO.output(out, GPIO.HIGH) for ins in inputs: GPIO.setup(ins, GPIO.IN) GPIO.add_event_detect(ins, GPIO.FALLING) #sets a flag on the pin #start thread to monitor inputs thread = threading.Thread(target=lambda: switchOnFall(inputs, outputs)) thread.start() print("Enter anything to quit") raw_input() #stall program till user presses enter, #clean up running = False for out in outputs: GPIO.output(out, GPIO.LOW) GPIO.cleanup()
def setup_io(): """ Used to setup pins on the BBB. """ print("Setting up I/O") script_io = """ sudo config-pin -a P9_26 can sudo config-pin -a P9_24 can sudo config-pin -a P8_7 gpio sudo config-pin -a P8_8 gpio sudo config-pin -a P8_10 gpio sudo config-pin -a P8_12 gpio sudo config-pin -a P8_14 gpio sudo config-pin -a P8_16 gpio sudo config-pin -a P8_18 gpio sudo config-pin -a P8_26 gpio """ os.system("bash -c '%s'" % script_io) GPIO.setup(led_red, GPIO.OUT) GPIO.setup(led_green, GPIO.OUT) GPIO.setup(led_blue, GPIO.OUT) GPIO.setup(button_logger, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(button_logger, GPIO.FALLING) GPIO.setup(button_denial, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(button_denial, GPIO.FALLING) GPIO.setup(button_idrep, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(button_idrep, GPIO.FALLING) GPIO.setup(button_bus_fuzz, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(button_bus_fuzz, GPIO.FALLING) GPIO.setup(button_corrupt, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(button_corrupt, GPIO.FALLING) sleep(2)
def moveDOWN(self): GPIO.add_event_detect(motor.lowerSW, GPIO.RISING, bouncetime=1000) PWM.start(self.pwmPIN, self.duty, self.freq, 0) GPIO.output(self.downDIR, GPIO.HIGH) status = 0 print "Moving motor DOWN" return 1, time.time()
def __init__(self, shared_memory, rootLogger=None, camerasock=None): """ """ threading.Thread.__init__(self) self.shared_memory = shared_memory self.ui_state = 'PAUSE' self.lastfun1 = time.time() self.lastfun2 = time.time() self.lastchange = time.time() self.fun1 = False self.fun2 = False self.user_pattern = False # user defined pattern or default? self.ptrn_idx = 0 self.last_process_time = time.time() self.process_time = 0 self.rootLogger = rootLogger self.rootLogger.info('Initialize HUI Thread ...') self.camerasock = camerasock self.camidx = 0 ADC.setup() for btn in BTNS: GPIO.setup(btn, GPIO.IN) GPIO.add_event_detect(btn, GPIO.RISING) for led in LEDS: GPIO.setup(led, GPIO.OUT) for idx in SWITCHES: GPIO.setup(SWITCHES[idx], GPIO.IN) ring_leds()
def main(): print "Setting up GPIO" # Variables GPIO.setup("P9_11", GPIO.IN) GPIO.add_event_detect("P9_11", GPIO.BOTH) GPIO.setup("P9_15", GPIO.OUT) global running try: while True: if GPIO.event_detected("P9_11"): if GPIO.input("P9_11"): print "Hazards on" running = True t1 = threading.Thread( target = blink_leds, args = ( "P9_15", ) ) t1.setDaemon( True ) t1.start() else: running = False print "Hazards off" GPIO.output("P9_15", GPIO.LOW) except KeyboardInterrupt: GPIO.cleanup() print "Ending program"
def edge_detect(port, event_callback, bounce): """Add detection for RISING and FALLING events.""" import RPi.GPIO as GPIO GPIO.add_event_detect(port, GPIO.BOTH, callback=event_callback, bouncetime=bounce)
def gpio(self, event=None): GPIO.add_event_detect("P8_12", GPIO.RISING, callback=self.my_callback_one) GPIO.add_event_detect("P8_14", GPIO.RISING, callback=self.my_callback_two)
def run(self): GPIO.add_event_detect(config.Ol, GPIO.RISING, callback=self.update_encoder_l) GPIO.add_event_detect(config.Or, GPIO.RISING, callback=self.update_encoder_r) current_time_l = time.time() current_time_r = time.time() while base.RUN_FLAG: if (time.time() >= current_time_l + TIME_INTERVAL): global ENC_VEL velocity_l = ( self.counter_l * (WHEEL_RADIUS * CONST) ) / TIME_INTERVAL ENC_VEL[base.LEFT] = velocity_l self.counter_l = 0 current_time_l = time.time() #print "velocity_l %s cm/s" % velocity_l if (time.time() >= current_time_r + TIME_INTERVAL): global ENC_VEL velocity_r = ( self.counter_r * (WHEEL_RADIUS * CONST) ) / TIME_INTERVAL ENC_VEL[base.RIGHT] = velocity_r self.counter_r = 0 current_time_r = time.time()
def setup_in_ports(gpio_pin_list): for gpio_pin in gpio_pin_list: if gpio_pin.pin_type == Constant.GPIO_PIN_TYPE_BBB: L.l.info('Set pincode={} type={} index={} as input'.format( gpio_pin.pin_code, gpio_pin.pin_type, gpio_pin.pin_index_bcm)) GPIO.setup(gpio_pin.pin_code, GPIO.IN) std_gpio.set_pin_edge(gpio_pin.pin_index_bcm, 'both') try: GPIO.add_event_detect( gpio_pin.pin_code, GPIO.BOTH) # , callback=event_detected, bouncetime=300) __pool_pin_codes.append(gpio_pin.pin_code) L.l.info('OK callback on gpio'.format(gpio_pin.pin_code)) except Exception, ex: L.l.warning( 'Unable to add event callback pin={} err={}'.format( gpio_pin.pin_code, ex)) try: GPIO.add_event_detect(gpio_pin.pin_code, GPIO.FALLING) L.l.info('OK pooling on gpio {} err='.format( gpio_pin.pin_code, ex)) __pool_pin_codes.append(gpio_pin.pin_code) except Exception, ex: L.l.warning( 'Unable to add pooling on pin {} err={}'.format( gpio_pin.pin_code, ex))
def main(): PIR = "P8_11" GPIO.setup(PIR, GPIO.IN) GPIO.add_event_detect(PIR, GPIO.RISING) node = os.popen("uname -n").readline() node = node.split('\n')[0] """ nome do arquivo: dadosTemperatura_Teste_nodeX_hora.mintus.segundo_dia.mes.ano.txt """ nome_Arquivo = node + 'Tempertatura_' + \ time.strftime('_%l.%M.%S_%d.%m.%Y')+'.txt' arquivo = open(nome_Arquivo, 'w') while True: if GPIO.event_detected(PIR): break while True: if GPIO.event_detected(PIR): break arquivo.writelines( time.strftime('Horario da captura: %l:%M:%S %p %Z on %d\ , %Y; ') + 'Temperatura na CPU: ' + str(temp_cpu()) + '; Temperatura na GPU \ :' + '0') time.sleep(1) arquivo.close() diretorio = "hduser@master:/home/hduser/HadoopDados" subprocess.call(["scp", nome_Arquivo, diretorio])
def moveDOWN(self): GPIO.add_event_detect(motor.lowerSW, GPIO.RISING, bouncetime=1000) PWM.start(self.pwmPIN, self.duty, self.freq, 0) GPIO.output(self.downDIR, GPIO.HIGH) status = 0 print "Moving motor DOWN" return 1, time.time()
def main(): global running # other wise we cant stop thread #set up pins for out in outputs: GPIO.setup(out,GPIO.OUT) GPIO.output(out,GPIO.LOW) GPIO.output(outputs[0], GPIO.HIGH) GPIO.output(outputs[1], GPIO.HIGH) GPIO.setup("P9_18",GPIO.IN) GPIO.add_event_detect("P9_18",GPIO.FALLING) GPIO.wait_for_edge("P9_18",GPIO.FALLING) #start thread to run program thread = threading.Thread(target= lambda:function()) thread.start() print("Enter anything to quit") raw_input() #stall program till user presses enter, #clean up running = False for out in outputs: GPIO.output(out,GPIO.LOW) GPIO.cleanup()
def Encoder(): GPIO.setup("P9_12", GPIO.IN) GPIO.add_event_detect("P9_12", GPIO.BOTH, callback=encoderCallback) pub = rospy.Publisher('beaglebone_encoder', Encoders) rospy.init_node('beaglebone_encoder') r = rospy.Rate(50) encodersMsg = Encoders() lastPub = rospy.get_time()+10 wheel_size = 1.32212398060626 pps = 80 distance_per_pulse = wheel_size / pps last_count = 0 global counter while not rospy.is_shutdown(): current_count = counter dcount = current_count - last_count last_count = current_count encodersMsg.stamp = rospy.Time.now() stamp_sec = encodersMsg.stamp.to_sec() encodersMsg.dt = stamp_sec - lastPub lastPub = stamp_sec encodersMsg.d_dist = dcount * distance_per_pulse encodersMsg.d_left = dcount encodersMsg.d_count_left = current_count encodersMsg.v = encodersMsg.d_dist/encodersMsg.dt pub.publish(encodersMsg) r.sleep()
def moveUP(self): GPIO.add_event_detect(motor.upperSW, GPIO.RISING, bouncetime=1000) PWM.start(self.pwmPIN, self.duty, self.freq, 0) GPIO.output(self.upDIR, GPIO.HIGH) status = 1 print "Moving motor UP" return 0, time.time()
def main(): grid = [] i2c = Adafruit_I2C( 0x48, busnum=2 ) # if it wasnt 1 am i might actually do something with the temp sensor here display = Adafruit_I2C(0x70, busnum=2) #init display display.write8(0x21, 0x00) display.write8(0x81, 0x00) display.write8(0xe7, 0x00) #init grid for Kappa in range(0, size): grid.append([0] * size) #clear gird writeToDisplay(grid, display) #init inputs inputs = ["P9_11", "P9_12", "P9_15", "P9_21", "P9_17"] for Kappa in inputs: GPIO.setup(Kappa, GPIO.IN) GPIO.add_event_detect(Kappa, GPIO.FALLING) thread = threading.Thread(target=lambda: gridMove(grid, display, inputs)) thread.start() #let the user quit the program raw_input() global running running = False GPIO.cleanup() display.writeList(0x00, [0x00] * 16)
def run(self): GPIO.add_event_detect(config.Ol, GPIO.RISING, callback=self.update_encoder_l) GPIO.add_event_detect(config.Or, GPIO.RISING, callback=self.update_encoder_r) current_time_l = time.time() current_time_r = time.time() while base.RUN_FLAG: if (time.time() >= current_time_l + TIME_INTERVAL): global ENC_VEL velocity_l = (self.counter_l * (WHEEL_RADIUS * CONST)) / TIME_INTERVAL ENC_VEL[base.LEFT] = velocity_l self.counter_l = 0 current_time_l = time.time() #print "velocity_l %s cm/s" % velocity_l if (time.time() >= current_time_r + TIME_INTERVAL): global ENC_VEL velocity_r = (self.counter_r * (WHEEL_RADIUS * CONST)) / TIME_INTERVAL ENC_VEL[base.RIGHT] = velocity_r self.counter_r = 0 current_time_r = time.time()
def edge_detect(pin, event_callback, bounce): """Add detection for RISING and FALLING events.""" GPIO.add_event_detect(pin, GPIO.BOTH, callback=event_callback, bouncetime=bounce)
def main(): global playerX global playerY global board GPIO.setup(up, GPIO.IN) GPIO.setup(down, GPIO.IN) GPIO.setup(left, GPIO.IN) GPIO.setup(right, GPIO.IN) GPIO.setup(clear, GPIO.IN) GPIO.add_event_detect(left, GPIO.RISING, callback=mycallback, bouncetime=500) GPIO.add_event_detect(up, GPIO.RISING, callback=mycallback, bouncetime=500) GPIO.add_event_detect(down, GPIO.RISING, callback=mycallback, bouncetime=500) GPIO.add_event_detect(right, GPIO.RISING, callback=mycallback, bouncetime=500) GPIO.add_event_detect(clear, GPIO.RISING, callback=clearBoard, bouncetime=500) board[playerY][playerX] = 'P' printer(board) """ while True: #The prevous locations board[playerY][playerX] = 'X' #This goes through the commands to apply the proper outcome to the commands com = input("Please Enter A Command: ") if com == "up": playerY = playerY - 1 elif com == "down": playerY = playerY + 1 elif com == "left": playerX = playerX - 1 elif com == "right": playerX += 1 elif com == "clear": board = [['-'] * m for i in range(n)] """ try: while True: time.sleep(1) except KeyboardInterrupt: GPIO.cleanup()
def digitalGpioExamples(): # Set up pin P8_10 as an output GPIO.setup("P8_10", GPIO.OUT) # or GPIO.setup("GPIO0_26", GPIO.OUT) referring to the actual pin name instead of header_number GPIO.output("P8_10", GPIO.HIGH) GPIO.cleanup() # Set up pin P8_14 as an input GPIO.setup("P8_14", GPIO.IN) # Check to see if there is a signal or not and report on the status if GPIO.input("P8_14"): print("HIGH") else: print("LOW") # If you want edge detection instead, look no further (THIS IS BLOCKING, so be aware) GPIO.wait_for_edge("P8_14", GPIO.RISING) # Non blocking version GPIO.add_event_detect("P9_12", GPIO.FALLING) #your amazing code here #detect wherever: if GPIO.event_detected("P9_12"): print "event detected!"
def run(self): GPIO.add_event_detect(config.Or, GPIO.RISING, callback=self.update_encoder_r) GPIO.add_event_detect(config.Ol, GPIO.RISING, callback=self.update_encoder_l) current_time_l = time.time() current_time_r = time.time() while True and not self._stop: if (time.time() >= current_time_l + time_interval): velocity_l = ( self.counter_l * (wheel_radius * const) ) / time_interval self.counter_l = 0 current_time_l = time.time() print "velocity_l %s cm/s ticks sum %s" % (velocity_l, ENC_POS[LEFT]) if (time.time() >= current_time_r + time_interval): velocity_r = ( self.counter_r * (wheel_radius * const) ) / time_interval self.counter_r = 0 current_time_r = time.time() print "velocity_r %s cm/s ticks sum %s" % (velocity_r, ENC_POS[RIGHT])
def edge_detect(pin, event_callback, bounce): """Add detection for RISING and FALLING events.""" # pylint: disable=import-error,undefined-variable import Adafruit_BBIO.GPIO as GPIO GPIO.add_event_detect(pin, GPIO.BOTH, callback=event_callback, bouncetime=bounce)
def run(self): GPIO.add_event_detect(self.pins[0], GPIO.RISING) while True: if GPIO.event_detected(self.pins[0]): self.edgeDetected() if time.time() - self.currentEdge > self.timeout: self.setZero() self.publish()
def app_init(): GPIO.setup("P8_12", GPIO.IN) GPIO.add_event_detect("P8_12", GPIO.RISING, callback=button_release, bouncetime=500) lcd_i2c.lcd_init()
def main(stdscr): # Use --size to specify size of board. Defaults to 8x8 parser = argparse.ArgumentParser() parser.add_argument("--size", type=int, default=8) args = parser.parse_args() size = args.size # Setup curses curses.noecho() curses.cbreak() stdscr.keypad(True) curses.curs_set(1) # Setup GPIO GPIO.setup("P9_22", GPIO.IN) # down GPIO.add_event_detect("P9_22", GPIO.RISING) GPIO.setup("P9_24", GPIO.IN) # left GPIO.add_event_detect("P9_24", GPIO.RISING) GPIO.setup("P9_23", GPIO.IN) # up GPIO.add_event_detect("P9_23", GPIO.RISING) GPIO.setup("P9_21", GPIO.IN) # right GPIO.add_event_detect("P9_21", GPIO.RISING) GPIO.setup("P9_26", GPIO.IN) # clear GPIO.add_event_detect("P9_26", GPIO.RISING) new_frame(stdscr, size) cur_x = 0 cur_y = 0 while True: stdscr.refresh() # Updates current position based on button pressed if GPIO.event_detected("P9_24"): if cur_x > 0: cur_x = cur_x - 1 elif GPIO.event_detected("P9_21"): if cur_x < size - 1: cur_x = cur_x + 1 elif GPIO.event_detected("P9_23"): if cur_y > 0: cur_y = cur_y - 1 elif GPIO.event_detected("P9_22"): if cur_y < size - 1: cur_y = cur_y + 1 elif GPIO.event_detected("P9_26"): new_frame(stdscr, size) cur_x = 0 cur_y = 0 # Prints an X in the current position stdscr.addstr(5 + cur_y, 2 + cur_x * 2, 'X') stdscr.move(5 + cur_y, 2 + cur_x * 2)
def initHardware(): pSens0 = DPressureSens(0,P_mplx_id) IMUsens0 = MPU_9150(0,mplx_id_0) IMUsens1 = MPU_9150(0,mplx_id_1) pActuator = Valve(0,pValve0) dActuator = DiscreteValve(0,dValve0) GPIO.setup(stopButton, GPIO.IN) GPIO.add_event_detect(stopButton, GPIO.RISING) return pSens0, IMUsens0, IMUsens1, pActuator, dActuator
def io_setup(): GPIO.setup(BLUE_LEDPIN, GPIO.OUT) GPIO.setup(MODULE_EN, GPIO.OUT) GPIO.setup(MODULE_RST, GPIO.OUT) GPIO.setup(G0_PIN, GPIO.IN) GPIO.setup(G1_PIN, GPIO.OUT) GPIO.setup(G2_PIN, GPIO.OUT) # GPIO.add_event_detect(G0_PIN, GPIO.FALLING, callback=g0int) GPIO.add_event_detect(G0_PIN, GPIO.RISING, callback=g0int)
def add_interrupts(self): GPIO.add_event_detect(self.empt, GPIO.FALLING, callback=self.water_is_empty(), bouncetime=300) GPIO.add_event_detect(self.full, GPIO.RISING, callback=self.water_is_full(), bouncetime=300)
def main(): global cursorX global cursorY global length global height global board #board set at 8x8 for led matrix length = "8" height = "8" print(length + " X " + height + " Board Loading...") board = [[0]*int(length) for i in range(int(height))] board[0][0] = 1 cursorX = 0 cursorY = 0 old_posL = 0 old_posR = 0 #Draw initial board printBoard() #Shake button GPIO.setup("P9_11", GPIO.IN) GPIO.add_event_detect("P9_11", GPIO.BOTH, callback = call, bouncetime = 250) try: while True: #Game loop cur_positionL = myEncoderL.position cur_positionR = myEncoderR.position #print(str(cur_positionL) + " | "+ str(cur_positionR) + " | "+str(cursorX)+" | "+str(cursorY)) #update cursor position if cur_positionL > old_posL: if cursorY != 0: cursorY -= 1 elif cur_positionL < old_posL: if cursorY != int(height)-1: cursorY += 1 if cur_positionR > old_posR: if cursorX != 0: cursorX -= 1 elif cur_positionR < old_posR: if cursorX != int(length)-1: cursorX += 1 #Draw on new cursor board[cursorY][cursorX] = 1 old_posL = cur_positionL old_posR = cur_positionR printBoard() time.sleep(0.4) #refresh rate except KeyboardInterrupt: print("Thanks for playing!") GPIO.cleanup()
def moveUP(self): try: GPIO.add_event_detect(motor.upperSW, GPIO.RISING, bouncetime=1000) except RuntimeError: pass PWM.start(self.pwmPIN, self.duty, self.freq, 0) GPIO.output(self.upDIR, GPIO.HIGH) print "Moving motor UP" return 0, time.time()
def run(self): for pin in self.input_pins: GPIO.add_event_detect(pin, GPIO.FALLING) while True: for pin in self.input_pins: if GPIO.event_detected(pin): t = time() if t > self.ltime[pin] + self.EVENT_INTERVAL: self.ltime[pin] = t self.handlers[pin]()
def moveUP(self): try: GPIO.add_event_detect(motor.upperSW, GPIO.RISING, bouncetime=1000) except RuntimeError: pass PWM.start(self.pwmPIN, self.duty, self.freq, 0) GPIO.output(self.upDIR, GPIO.HIGH) print "Moving motor UP" return 0, time.time()
def __init__(self, port, callback): self.port = port self.callback = callback GPIO.setup(self.port, GPIO.IN) print "DETECT EVENTS:", self.port # GPIO.RISING, GPIO.FALLING, GPIO.BOTH GPIO.remove_event_detect(self.port) GPIO.add_event_detect(self.port, GPIO.RISING, callback=self.check_rising, bouncetime=300)
def __init__(self, pin, detect_edges = None): """ Create a Switch object that reads input from the given pin. """ self.pin = pin self.last_detected_pressed_id = 0 self.current_detected_pressed_id = 0 GPIO.setup(pin, GPIO.IN, GPIO.PUD_UP) self.rising_edge_callbacks = [] self.falling_edge_callbacks = [] self.edges_detected = detect_edges if detect_edges != None: GPIO.add_event_detect(pin, detect_edges, self._edge_event, self.DEBOUNCING_TIME)
def hw_init(self): '''initialize gpio port.''' self.logger.info('initializing {} on gpio pin {:s}.'.format(self.config_name, str(self.gpio_pin))) try: GPIO.setup(self.gpio_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(self.gpio_pin,GPIO.FALLING,callback=self.__event_callback,bouncetime=200) except Exception as e: self.logger.info('failed to setup {:s} on {:s}.'.format(self.config_name, self.log_name)) self.logger.info('Error: {:s}.'.format(str(e))) raise SystemExit('Unable to setup {:s} on {:s}'.format(self.config_name, self.log_name))
def main(): # Setup GPIO GPIO.setup("P9_22", GPIO.IN) # down GPIO.add_event_detect("P9_22", GPIO.RISING) GPIO.setup("P9_12", GPIO.OUT) led0 = False GPIO.setup("P9_24", GPIO.IN) # left GPIO.add_event_detect("P9_24", GPIO.RISING) GPIO.setup("P9_13", GPIO.OUT) led1 = False GPIO.setup("P9_23", GPIO.IN) # up GPIO.add_event_detect("P9_23", GPIO.RISING) GPIO.setup("P9_11", GPIO.OUT) led2 = False GPIO.setup("P9_21", GPIO.IN) # right GPIO.add_event_detect("P9_21", GPIO.RISING) GPIO.setup("P9_14", GPIO.OUT) led3 = False GPIO.setup("P9_26", GPIO.IN) # clear GPIO.add_event_detect("P9_26", GPIO.RISING) # If button is pressed, switch the appropriate LED while True: if GPIO.event_detected("P9_23"): switch_led(11, led2) led2 = not led2 if GPIO.event_detected("P9_22"): switch_led(12, led0) led0 = not led0 if GPIO.event_detected("P9_24"): switch_led(13, led1) led1 = not led1 if GPIO.event_detected("P9_21"): switch_led(14, led3) led3 = not led3 if GPIO.event_detected("P9_26"): GPIO.output("P9_11", GPIO.LOW) led2 = False GPIO.output("P9_12", GPIO.LOW) led0 = False GPIO.output("P9_13", GPIO.LOW) led1 = False GPIO.output("P9_14", GPIO.LOW) led3 = False
def __init__(self, pin, objects=[]): """ pin: GPIO pin on which to wait for rising edge. objects: list of objects to call stop() methods for. """ self.pin = pin self.objects = objects # Set up GPIO interrupt on rising edge. GPIO.setup(pin, GPIO.IN) GPIO.add_event_detect(pin, GPIO.BOTH, callback=self.__handler, bouncetime=500) return None
def configure_gpio(): # Configure outputs for _, pin in OUTPUTS.items(): GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, GPIO.LOW) # Assert MAINRS by default GPIO.output(OUTPUTS['MAINRS'], GPIO.HIGH) # Configure inputs for _, pin in INPUTS.items(): GPIO.setup(pin, GPIO.IN) GPIO.add_event_detect(pin, GPIO.BOTH)
def configure_gpio(): # Configure outputs for _, pin in OUTPUTS.items(): GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, GPIO.LOW) # Assert MAINRS by default GPIO.output(OUTPUTS['MAINRS'], GPIO.HIGH) # Configure inputs for _,pin in INPUTS.items(): GPIO.setup(pin, GPIO.IN) GPIO.add_event_detect(pin, GPIO.BOTH)
def __init__(self, port, callback): self.port = port self.callback = callback GPIO.setup(self.port, GPIO.IN) print "DETECT EVENTS:", self.port # GPIO.RISING, GPIO.FALLING, GPIO.BOTH GPIO.remove_event_detect(self.port) GPIO.add_event_detect(self.port, GPIO.RISING, callback=self.check_rising, bouncetime=300)
def _init(): try: gpio.setup(_WIND, gpio.IN) gpio.setup(_PULSE, gpio.IN) gpio.add_event_detect(_WIND, gpio.FALLING, _handle_event) gpio.add_event_detect(_PULSE, gpio.RISING, _handle_event) except: _exit() raise try: atexit.register(_exit) except: _exit() raise
def setupPins(pins): # build node script to set pin direction: mux = 7 pud = "pulldown" script = "var b = require('bonescript');" for (p, _) in pins: script += " b.pinMode('%s',b.INPUT,%i,'%s','fast');" % (p, mux, pud) command = ["node", "-e", script] subprocess.call(command, cwd="/usr/local/lib") # now use adafruit python lib for (p, callback) in pins: GPIO.setup(p, GPIO.IN) GPIO.add_event_detect(p, GPIO.BOTH) GPIO.add_event_callback(p, ButtonHandler(p, callback).handler)
def enableInterrupt(self): #GPIO.setmode(GPIO.BOARD) GPIO.setup(GPIO_INTERRUPT_PIN, GPIO.IN) GPIO.add_event_detect(GPIO_INTERRUPT_PIN, GPIO.RISING, callback = self.handleInterrupt) bus.write_byte_data(self.address, THRESH_ACT, ACTIVITY_TRESH) bus.write_byte_data(self.address, ACT_INACT_CTL, ACT_AXES) bus.write_byte_data(self.address, TRESH_FF, FALL_TRESH) #bus.write_byte_data(self.address, TRESH_TAP, TAP_TRESH) #bus.write_byte_data(self.address, DUR, DUR_TRESH) #bus.write_byte_data(self.address, LATENT, TAP_LATENCY) #bus.write_byte_data(self.address, WINDOW, TAP_WINDOW) bus.write_byte_data(self.address, INT_MAP, 0x8B) bus.write_byte_data(self.address, INT_ENABLE, ACT_ENABLE) self.clearInterrupt()
def add_event_detect(pin_id, edge): if pin_id[0] == 'P': return GPIO.add_event_detect(pin_id,edge) elif pin_id[0] == 'E': raise Exception("Interupt feature is not yet implemented on this pin (" + pin_id + ")") else: pin_id_error() return 0
def main(): ## pin setup and initialization ## for key in sevenSegDisplay: GPIO.setup(sevenSegDisplay[key], GPIO.OUT) for pin in floorButtons: GPIO.setup(pin, GPIO.IN) GPIO.add_event_detect(pin, GPIO.FALLING) currentFloor = 0 destFloor = 0 displayNum(0) ## lift is at floor 0 ## while True: for pin in floorButtons: if GPIO.event_detected(pin): destFloor = floorButtons.index(pin) break time.sleep(0.02) if currentFloor != destFloor: time.sleep(0.25) step = 0 if currentFloor < destFloor: step = 1 else: step = -1 while (currentFloor + step) != destFloor: time.sleep(2) currentFloor += step displayNum(currentFloor) time.sleep(2.25) currentFloor += step for i in range (3): setAllLeds(0) time.sleep(0.5) displayNum(currentFloor) time.sleep(0.5)
def main(): global status status = -1 # up = 1, down = 0 motor = pinConfig() motor.setPin() if GPIO.input(motor.upperSW): # if on upperSW move down print "@Upper switch..." status = motor.moveDOWN() elif GPIO.input(motor.lowerSW): # if on lowerSW move up print "@Lower switch..." status = motor.moveUP() else: print "@Middle..." status = motor.moveUP() # print "GPIO event enabled" GPIO.add_event_detect(motor.upperSW, GPIO.RISING, bouncetime=1000) GPIO.add_event_detect(motor.lowerSW, GPIO.RISING, bouncetime=1000) try: while True: # print status if status == 1: if GPIO.input(motor.upperSW) and GPIO.event_detected(motor.upperSW): print "@Upper switch..." motor.moveStop() print "... ... Sleep ZZZzz" time.sleep(pinConfig.restTIme) status = motor.moveDOWN() elif status == 0: if GPIO.input(motor.lowerSW) and GPIO.event_detected(motor.lowerSW): print "@Lower switch..." motor.moveStop() print "... ... Sleeping ZZZzz" time.sleep(pinConfig.restTIme) status = motor.moveUP() except KeyboardInterrupt: motor.moveStop() GPIO.cleanup()
def setup(self): GPIO.setup(MOTOR1A, GPIO.OUT) GPIO.setup(MOTOR1B, GPIO.OUT) GPIO.output(MOTOR1A, GPIO.LOW) GPIO.output(MOTOR1B, GPIO.LOW) GPIO.setup(ENCODER_AR, GPIO.IN) GPIO.setup(ENCODER_AF, GPIO.IN) GPIO.setup(ENCODER_BR, GPIO.IN) GPIO.setup(ENCODER_BF, GPIO.IN) GPIO.add_event_detect(ENCODER_AR, GPIO.RISING, Edger(self, 'AR')) GPIO.add_event_detect(ENCODER_AF, GPIO.FALLING, Edger(self, 'AF')) GPIO.add_event_detect(ENCODER_BR, GPIO.RISING, Edger(self, 'BR')) GPIO.add_event_detect(ENCODER_BF, GPIO.FALLING, Edger(self, 'BF'))
def __init__(self, server, sock, address): super(RobotControl, self).__init__(server, sock, address) # setup GPIO pins for proximity sensors for PIN in self.PROXIMITY_GPIO: GPIO.setup(PIN, GPIO.IN) # try to add event detection for proximity GPIO pins for PIN, val in self.PROXIMITY_GPIO.items(): # wait until the GPIO is configured as an input while GPIO.gpio_function(PIN) != GPIO.IN: GPIO.setup(PIN, GPIO.IN) GPIO.add_event_detect(PIN, GPIO.FALLING, self.__proximityDetect, 10) for LED in self.LEDS_GPIO.itervalues(): GPIO.setup(LED, GPIO.OUT) GPIO.output(LED, GPIO.LOW) GPIO.output(self.LEDS_GPIO["RED_pin"], GPIO.HIGH) self.saber = Sabertooth(self.UART, self.TTY) self.saber.setRamp(15)
def __init__(self): """ Input: N/A Output: N/A Constructor for button handler class. Configures pins for I/O. See BBB_Pinouts for BBB wiring configuration. """ GPIO.setup("P8_7", GPIO.IN) # Front Bumper GPIO.setup("P8_8", GPIO.IN) # Back Bumper GPIO.setup("P8_9", GPIO.IN) # Forward Button GPIO.setup("P8_10", GPIO.IN) # Backward Button GPIO.setup("P8_11", GPIO.IN) # Stop Button GPIO.add_event_detect("P8_7", GPIO.FALLING) # Front Bumper GPIO.add_event_detect("P8_8", GPIO.FALLING) # Back Bumper GPIO.add_event_detect("P8_9", GPIO.FALLING) # Forward Button GPIO.add_event_detect("P8_10", GPIO.FALLING) # Back Button GPIO.add_event_detect("P8_11", GPIO.FALLING) # Stop Button self.buttonState = ButtonState.noBtn
def __init__(self, pin_anem, pin_dir, pin_rain): self._logger = logging.getLogger('ADS80422.ADS80422') ADS80422.pin_anem = pin_anem ADS80422.pin_dir = pin_dir ADS80422.pin_rain = pin_rain GPIO.setup(pin_anem, GPIO.IN) GPIO.setup(pin_rain, GPIO.IN) # when a falling edge is detected on port pinAnem, regardless of whatever # else is happening in the program, the function callback will be run GPIO.add_event_detect(ADS80422.pin_anem, GPIO.RISING, callback=self._service_interrupt_anemometer, bouncetime=20) GPIO.add_event_detect(ADS80422.pin_rain, GPIO.RISING, callback=self._service_interrupt_rain, bouncetime=20) ADC.setup()
def run_detector(): model = config["DEVICE"]["Model"] pin = config["DEVICE"]["GPIOPin"] delay = int(config["DEVICE"]["NotifyRate"]) if model == "pi": import RPi.GPIO as io io.setmode(io.BCM) io.setup(int(pin), io.IN) while True: if io.input(pin): send_motion_event() time.sleep(delay * 60) time.sleep(1) elif model == "bone": from Adafruit_BBIO import GPIO GPIO.setup(pin, GPIO.IN) GPIO.add_event_detect(pin, GPIO.RISING) while True: if GPIO.event_detected(pin): send_motion_event() time.sleep(delay * 60) time.sleep(1)
def __init__(self, server, sock, address): super(RobotControl, self).__init__(server, sock, address) # setup GPIO pins for proximity sensors for PIN in self.PROXIMITY_GPIO: GPIO.setup(PIN, GPIO.IN) # try to add event detection for proximity GPIO pins for PIN, val in self.PROXIMITY_GPIO.items(): # wait until the GPIO is configured as an input while GPIO.gpio_function(PIN) != GPIO.IN: GPIO.setup(PIN, GPIO.IN) GPIO.add_event_detect(PIN, GPIO.FALLING, self.__proximityDetect, 10) for LED in self.LEDS_GPIO.itervalues(): GPIO.setup(LED, GPIO.OUT) GPIO.output(LED, GPIO.LOW) # Connected to Sabertooth S2 as "emergency stop" button GPIO.setup(self.STOP_GPIO, GPIO.OUT) GPIO.output(self.STOP_GPIO, GPIO.HIGH) # Triggers when button pressed GPIO.setup(self.STOP_BUTTON, GPIO.IN) while GPIO.gpio_function(self.STOP_BUTTON) != GPIO.IN: GPIO.setup(self.STOP_BUTTON, GPIO.IN) GPIO.add_event_detect(self.STOP_BUTTON, GPIO.RISING, self.__stopButton, 10) # HMC5883L Magnetometer self.mag = MAG(declination=(11,35)) # HC-SR04 pin setup # ECHO_TRIGGER initiates ultrasonic pulse GPIO.setup(self.ECHO_TRIGGER, GPIO.OUT) # ECHO_RETURN - needs to be level shifted from 5.0V to 3.3V # time of +ve pulse is the distance GPIO.setup(self.ECHO_RETURN, GPIO.IN) while GPIO.gpio_function(self.ECHO_RETURN) != GPIO.IN: GPIO.setup(self.ECHO_RETURN, GPIO.IN) GPIO.add_event_detect(self.ECHO_RETURN, GPIO.BOTH, self.__measureEcho, 1) GPIO.output(self.ECHO_TRIGGER, GPIO.LOW) # Start servo scanning movement thread self.SCAN = True threading.Thread(target=self.__servoScan).start() # Start HC-SR04 timing/measurement thread threading.Thread(target=self.__HCSR04).start() self.do_beep(0.25) GPIO.output(self.LEDS_GPIO["RED_pin"], GPIO.HIGH) self.saber = Sabertooth(self.UART, self.TTY) self.saber.setRamp(15)
file.close() global count global countIDLE count = 0 countIDLE = 0 totalflow = 0 PWMstarted = 0 def countPulse(channel): global count count = count+1 GPIO.add_event_detect(flowPULSE, GPIO.RISING, callback=countPulse) while True: try: #get current time now=time.localtime(time.time()) pt=time.asctime(now) #formatted time for file currentmonth=now.tm_mon currentday=now.tm_mday currentyear=now.tm_year start_counter = 1 count=0 time.sleep(1) start_counter = 0
if __name__ == '__main__': try: #Initialize node rospy.init_node('encoders') #Create publisher, to send out a String with the first joint name of every received message as an example. pubFR = rospy.Publisher('/py_controller/front_right_wheel/encoder', JointState, queue_size=10) pubRR = rospy.Publisher('/py_controller/rear_right_wheel/encoder', JointState, queue_size=10) pubFL = rospy.Publisher('/py_controller/front_left_wheel/encoder', JointState, queue_size=10) pubRL = rospy.Publisher('/py_controller/rear_left_wheel/encoder', JointState, queue_size=10) #sets up GPIO channels GPIO.setup("P9_23", GPIO.IN) GPIO.setup("P9_30", GPIO.IN) GPIO.setup("P8_17", GPIO.IN) GPIO.setup("P8_26", GPIO.IN) GPIO.add_event_detect("P9_23", GPIO.BOTH) GPIO.add_event_detect("P9_30", GPIO.BOTH) GPIO.add_event_detect("P8_17", GPIO.BOTH) GPIO.add_event_detect("P8_26", GPIO.BOTH) GPIO.add_event_callback("P9_23", callLeft) GPIO.add_event_callback("P9_30", callLeft) GPIO.add_event_callback("P8_17", callRight) GPIO.add_event_callback("P8_26", callRight) rospy.spin() #If we are interrupted, catch the exception, but do nothing except rospy.ROSInterruptException: pass
# Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # # tilt_switch.py # Response when tilt switch is triggered with interrupt way, and # de-bounces by software # # Author : sosorry # Date : 05/01/2016 import Adafruit_BBIO.GPIO as GPIO import time WAIT_TIME = 200 GPIO.setup("P9_12", GPIO.IN, pull_up_down=GPIO.PUD_UP) def mycallback(channel): print("Switch tilted @"), time.ctime() try: GPIO.add_event_detect("P9_12", GPIO.FALLING, callback=mycallback, bouncetime=WAIT_TIME) while True: time.sleep(1) except KeyboardInterrupt: print "Exception: KeyboardInterrupt" finally: GPIO.cleanup()
#!/usr/bin/python # # Example of controlling GPIO pins with Python # import Adafruit_BBIO.GPIO as GPIO GPIO.setup("P8_10", GPIO.OUT) GPIO.output("P8_10", GPIO.HIGH) GPIO.cleanup() GPIO.setup("GPIO0_26", GPIO.OUT) GPIO.setup("P8_14", GPIO.IN) if GPIO.input("P8_14"): print("HIGH") else: print("LOW") GPIO.add_event_detect("P9_12", GPIO.FALLING) #your amazing code here #detect wherever: if GPIO.event_detected("P9_12"): print "event detected!" GPIO.cleanup()
self.data = self.data[-self.max_size:] def get(self): out = self.data[:] return out event_times = {'P8_9':Buff(), 'P8_10':Buff()} def pin_change_cb(pin_id): event_times[pin_id].append(time.time()) if BBB: GPIO.cleanup() for key in event_times: GPIO.add_event_detect(key, GPIO.FALLING, pin_change_cb, 0) def get_duration(pin_id, min_dur=.1, shelf_life=5): times = array(event_times[pin_id].get()) times = times[time.time() - times < shelf_life] deltas = diff(times) deltas = deltas[deltas > min_dur] ## at least min_dur if len(times) > 0: out = median(deltas), times[-1] else: out = nan, nan return out DEG = math.pi / 180. WIDTH = 800