def __init__(self, dpad_l_pin=board.D3, dpad_r_pin=board.D4, dpad_u_pin=board.D1, dpad_d_pin=board.D0): # Setup DPAD # self.left_pin = DigitalInOut(dpad_l_pin) self.left_pin.direction = Direction.INPUT self.left_pin.pull = Pull.UP self.left = Debouncer(self.left_pin) self.right_pin = DigitalInOut(dpad_r_pin) self.right_pin.direction = Direction.INPUT self.right_pin.pull = Pull.UP self.right = Debouncer(self.right_pin) self.up_pin = DigitalInOut(dpad_u_pin) self.up_pin.direction = Direction.INPUT self.up_pin.pull = Pull.UP self.up = Debouncer(self.up_pin) self.down_pin = DigitalInOut(dpad_d_pin) self.down_pin.direction = Direction.INPUT self.down_pin.pull = Pull.UP self.down = Debouncer(self.down_pin)
def __init__(self, mc_top_pin=board.SCK, mc_middle_pin=board.MOSI, mc_bottom_pin=board.MISO): # Setup Minecraft Buttons # if mc_top_pin is not None: self.mc_top_pin = DigitalInOut(mc_top_pin) self.mc_top_pin.direction = Direction.INPUT self.mc_top_pin.pull = Pull.UP self.mc_top = Debouncer(self.mc_top_pin) else: self.mc_top = None if mc_middle_pin is not None: self.mc_middle_pin = DigitalInOut(mc_middle_pin) self.mc_middle_pin.direction = Direction.INPUT self.mc_middle_pin.pull = Pull.UP self.mc_middle = Debouncer(self.mc_middle_pin) else: self.mc_middle = None if mc_bottom_pin is not None: self.mc_bottom_pin = DigitalInOut(mc_bottom_pin) self.mc_bottom_pin.direction = Direction.INPUT self.mc_bottom_pin.pull = Pull.UP self.mc_bottom = Debouncer(self.mc_bottom_pin) else: self.mc_bottom = None
def __init__(self, pin, name, type='Digital'): if type == 'Digital': self.pin = DigitalInOut(pin) self.debounced = Debouncer(self.pin) self.debounceRose = Debouncer(self.pin) self.debounceFell = Debouncer(self.pin) elif type == 'Analog': self.pin = AnalogIn(pin) self.name = name
def demoLoop(): led = digitalio.DigitalInOut(board.D13) led.direction = digitalio.Direction.OUTPUT touchA0 = touchio.TouchIn( board.A0 ) #built-in capacitive sensor. needs no external h/w except 1MOhm pulldown touchSwA0 = Debouncer(touchA0) testObservable = Observable('testObservable', lambda: random.randint(0,1000) < 1,\ 'something has happened', 'call me', 12345, event='random', reason='Dunno', led=led) #an observer with a random check testTimer = TimerObservable('testTimer', period=1000, led=led) #period is in ms testWentTrue = WentTrueObservable('testWentTrue', inp=touchSwA0, led=led) observer1 = Observer('observer1', testObservable) observer2 = Observer('observer2', testWentTrue) observer3 = Observer('observer3', testTimer) observerableList = [testObservable, testWentTrue, testTimer] #The forever loop. Causes observable to check their events and then notify their observers. while True: for obs in observerableList: res = obs.check( ) #ask this observable to check it event. This will cause a notify if it has happened if res and obs.name == 'testObservable': #did testObservable happen? if observer1 in testObservable._observers: #if so, remove observer1. He's finished now testObservable.deregister( observer1 ) #and here is how you can deregister. Would be useful to be able to reregister
def __init__(self, cursor, debounce_interval=0.01): CursorManager.__init__(self, cursor) self._pressed = 0 self._debouncer = Debouncer( lambda: bool(self._pressed & self._pad_btns["btn_a"]), interval=debounce_interval, )
def __init__(self, cursor: Cursor, debounce_interval: float = 0.01) -> None: CursorManager.__init__(self, cursor) self._debouncer = Debouncer( lambda: bool(self._pad_states & (1 << self._pad_btns["btn_a"])), interval=debounce_interval, )
def init_control(self): """Initialize the control here (i.e. set pin mode, get addresses, etc) Set the Pin for the button with the internal pull up resistor""" self.control_pin = self.gpio.DigitalInOut(self.pin_obj) self.control_pin.switch_to_input(pull=self.resistor) # If edge detection has been configured lets take advantage of that if self.edge_detection is not None: self.button = Debouncer(self.control_pin) if self.debounce is not None: self.button.interval = self.debounce
def run(): display = Display() generator = Generator() button_a = Debouncer(make_debouncable(board.D9)) button_b = Debouncer(make_debouncable(board.D6)) button_c = Debouncer(make_debouncable(board.D5)) encoder_button = Debouncer(make_debouncable(board.D12)) encoder = rotaryio.IncrementalEncoder(board.D10, board.D11) current_position = None # current encoder position change = 0 # the change in encoder position delta = 0 # how much to change the frequency by shape = shapes.SINE # the active waveform frequency = 440 # the current frequency display.update_shape(shape) # initialize the display contents display.update_frequency(frequency) while True: encoder_button.update() button_a.update() button_b.update() button_c.update() current_position, change = get_encoder_change(encoder, current_position) if change != 0: if not button_a.value: delta = change * 1000 elif not button_b.value: delta = change * 100 elif not button_c.value: delta = change * 10 else: delta = change frequency = change_frequency(frequency, delta) if encoder_button.fell: shape = change_shape(shape) display.update_shape(shape) display.update_frequency(frequency) generator.update(shape, frequency)
def __init__(self, cursor: Cursor, debounce_interval: float = 0.01) -> None: CursorManager.__init__(self, cursor) self._debouncers = {} for btn in self._pad_btns: self._debouncers[btn] = Debouncer( lambda btn=btn: bool( (self._pad_states & (1 << self._pad_btns[btn]))), interval=debounce_interval, )
def demoLoop(): #indicators redLed = digitalio.DigitalInOut(board.D13) redLed.direction = digitalio.Direction.OUTPUT #objects that cause events touchA0 = touchio.TouchIn( board.A0 ) #built-in capacitive sensor. needs no external h/w except 1MOhm pulldown touchSwA0 = Debouncer(touchA0) #Events that determine if the objects they monitor hae done something interesting simpleEvent = SimpleEvent( obj=touchSwA0) #Watch the touch sw on A0 and report if it IS True timerEvent = TimerEvent( name='timerEvent', period=3000) #this one doesn't have an 'obj' as it monitors time wentTrueEvent = WentTrueEvent( obj=touchSwA0, name='wentTrueEvent' ) #Watch the touch sw on A0 and report if it GOES True #Observables that monitor events and notify registered observers testSimpleEventObservable = Observable(name='testSimpleEventObservable', event=simpleEvent) testTimerEventObservable = Observable(name='testTimerEventObservable', event=timerEvent) testWentTrueObservable = Observable(name='testWentTrueObservable', event=wentTrueEvent) #observers that get notifications from observables and do something about it simpleObserver = Observer( 'simpleObserver', testSimpleEventObservable, led=redLed) #who the observable should notify if event happens timerObserver = Observer('timerObserver', testTimerEventObservable, led=redLed) wentTrueObserver = Observer('wentTrueObserver', testWentTrueObservable, testWentTrueObservable, led=redLed) #list of observables to be checked in the 'forever' loop #observerableList = [testSimpleEventObservable, testTimerEventObservable, testWentTrueObservable] observerableList = [testWentTrueObservable] #The forever loop. Causes observable to check their events and then notify their observers. while True: for obs in observerableList: res = obs.check( ) #ask this observable to check it event. This will cause a notify if it has happened
def __init__(self, address, nums, interval=0.05): self.data = 0 self.address = address self.nums = nums self.signel = {} self.pressed = {} self.released = {} self.busMask = 0 self.bus = SMBus(1) self.isRunning = False for i in range(self.nums): self.signel[i] = Debouncer(self.readSignal(i), interval) self.busMask = self.busMask | (1 << i) thread = threading.Thread(target=self.run, args=()) thread.daemon = True thread.start()
def init(self): """ Connect to the device """ self.pin_obj = getattr(board, self.pin) self.gpio = digitalio self._state = 0 # Used to track changes self.previous_state = self._state if re.match(r'D\d+$', self.pin): self.is_digital = True elif re.match(r'A\d+$', self.pin): self.is_digital = False else: self.is_digital = True if self.resistor is not None: if self.resistor == "up" or self.resistor == digitalio.Pull.UP: self._resistor = digitalio.Pull.UP elif self.resistor == "down" or self.resistor == digitalio.Pull.DOWN: self._resistor = digitalio.Pull.DOWN else: # Unknown resistor pull, defaulting to None self.config['resistor'] = self._resistor = None else: # Unknown resistor pull, defaulting to None self.config['resistor'] = self._resistor = None self._control_pin = self.gpio.DigitalInOut(self.pin_obj) self._control_pin.switch_to_input(pull=self._resistor) # Switches use debounce for better detection # TODO: get rid of this to allow long press, release, and press detection if self.type == 'switch': self.config['edge_detection'] = 'both' if self.edge_detection is not None: self._control = Debouncer(self._control_pin) if self.debounce is not None: self._control.interval = self.debounce self.reset_elapsed_time() return True
def init_hw(): # Display i2c = busio.I2C(board.SCL, board.SDA) display = Sparkfun_SerLCD_I2C(i2c) display.clear() # Thermocouples spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) therm0 = MAX31855(spi, digitalio.DigitalInOut(pinsetup['therm0'])) therm1 = MAX31855(spi, digitalio.DigitalInOut(pinsetup['therm1'])) # Relays (high to enable because we go through the transistor switch) relay0 = digitalio.DigitalInOut(pinsetup['relay0']) relay0.direction = digitalio.Direction.OUTPUT relay0.value = False relay1 = digitalio.DigitalInOut(pinsetup['relay1']) relay1.direction = digitalio.Direction.OUTPUT relay1.value = False # Encoder setup enc = rotaryio.IncrementalEncoder(pinsetup['encoderA'], pinsetup['encoderB']) pb = digitalio.DigitalInOut(pinsetup['button']) pb.direction = digitalio.Direction.INPUT pb.pull = digitalio.Pull.DOWN switch = Debouncer(pb) # RGB on dial (low to enable) r = digitalio.DigitalInOut(pinsetup['r']) r.direction = digitalio.Direction.OUTPUT r.value = True g = digitalio.DigitalInOut(pinsetup['g']) g.direction = digitalio.Direction.OUTPUT g.value = True b = digitalio.DigitalInOut(pinsetup['b']) b.direction = digitalio.Direction.OUTPUT b.value = True return (display, therm0, therm1, relay0, relay1, enc, switch, (r, g, b))
def make_crikit_signal_debouncer(pin): """Return a lambda to read the specified pin""" ss.pin_mode(pin, ss.INPUT_PULLUP) return Debouncer(lambda: ss.digital_read(pin))
# from adafruit_ble.uart_client import UARTClient # from adafruit_ble.scanner import Scanner # from adafruit_bluefruit_connect.packet import Packet from adafruit_bluefruit_connect.button_packet import ButtonPacket from adafruit_bluefruit_connect.color_packet import ColorPacket from neopixel import NeoPixel from board import NEOPIXEL, SWITCH from adafruit_debouncer import Debouncer from digitalio import DigitalInOut, Direction, Pull import adafruit_fancyled.adafruit_fancyled as fancy pin = DigitalInOut(SWITCH) # Set up built-in pushbutton switch pin.direction = Direction.INPUT pin.pull = Pull.UP switch = Debouncer(pin) pixels = NeoPixel(NEOPIXEL, 1) # Set up built-in NeoPixel AQUA = 0x00FFFF # (0, 255, 255) GREEN = 0x00FF00 # (0, 255, 0) ORANGE = 0xFF8000 # (255, 128, 0) RED = 0xFF0000 # (255, 0, 0) BLUE = 0x0000FF # (0, 0, 255) gradients = { 'Off': [(0.0, RED), (0.75, ORANGE)], 'On': [(0.0, GREEN), (1.0, AQUA)] } palette = fancy.expand_gradient(gradients['Off'], 30)
rainbow_chase, chase, rainbow_comet, auto_clear=True, auto_reset=True, ) def go_dark(): '''set all pixels to black''' pixels.fill(BLACK) pixels.show() # Debouncer ------------------------------------------------------ buttons = [Debouncer(mpr121[i]) for i in range(12)] # Audio Setup ------------------------------------------------------ spkr_enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE) spkr_enable.direction = digitalio.Direction.OUTPUT spkr_enable.value = True audio = AudioOut(board.SPEAKER) tracks = ( WaveFile(open("sounds/F2.wav", "rb")), # 0 WaveFile(open("sounds/G2.wav", "rb")), # 1 WaveFile(open("sounds/A2.wav", "rb")), # 2 WaveFile(open("sounds/Bb2.wav", "rb")), # 3
i2c = busio.I2C(board.SCL, board.SDA) rtc = adafruit_ds3231.DS3231(i2c) audio = audioio.AudioOut(board.A0) strip = neopixel.NeoPixel(NEOPIXEL_PIN, NUM_PIXELS, brightness=1, auto_write=False) strip.fill(0) # NeoPixels off ASAP on startup strip.show() switch_io = DigitalInOut(SWITCH_PIN) switch_io.direction = Direction.INPUT switch_io.pull = Pull.UP switch = Debouncer(switch_io) # create a PWMOut object on Pin A2. pwm = pulseio.PWMOut(SERVO_PIN, duty_cycle=2**15, frequency=50) # Create a servo object, my_servo. servo = servo.ContinuousServo(pwm) servo.throttle = 0.0 # Set the time for testing # Once finished testing, the time can be set using the REPL using similar code if TESTING: # year, mon, date, hour, min, sec, wday, yday, isdst t = time.struct_time((2018, 12, 31, 23, 58, 55, 1, -1, -1)) # you must set year, mon, date, hour, min, sec and weekday # yearday is not supported, isdst can be set but we don't do anything with it at this time
board.GP16, board.GP17, board.GP18, board.GP19, board.GP20, board.GP21, board.GP22, ) touch_ins = [] touchs = [] for pin in touch_pins: touchin = touchio.TouchIn(pin) touchin.threshold += touch_threshold_adjust touch_ins.append(touchin) touchs.append(Debouncer(touchin)) print("\n----------") print("picotouch hello") while True: if debug: for i in range(len(touch_ins)): touchin = touch_ins[i] print(touchin.raw_value, ', ', end='') print() time.sleep(0.01) for i in range(len(touchs)): touch = touchs[i] touch.update() if touch.rose:
import board import digitalio import adafruit_rfm69 from adafruit_debouncer import Debouncer LED = digitalio.DigitalInOut(board.D13) LED.direction = digitalio.Direction.OUTPUT spi = board.SPI() ########################################## # buttons btn_red_pin = digitalio.DigitalInOut(board.A0) btn_red_pin.direction = digitalio.Direction.INPUT btn_red_pin.pull = digitalio.Pull.UP btn_red = Debouncer(btn_red_pin) ########################################## # RFM69 RADIO_FREQ_MHZ = 433.0 CS = digitalio.DigitalInOut(board.A4) RESET = digitalio.DigitalInOut(board.A5) rfm69 = adafruit_rfm69.RFM69(spi, CS, RESET, RADIO_FREQ_MHZ) rfm69.encryption_key = None rfm69.tx_power = 20 rfm69.bitrate = 250000 / 2 print("itsybitsy_rfm69_minimal.py") while True:
def make_criket_signal_debouncer(pin): # create pin signal objects ss.pin_mode(pin, ss.INPUT_PULLUP) return Debouncer(lambda: ss.digital_read(pin))
import time import board from digitalio import DigitalInOut, Direction, Pull from adafruit_debouncer import Debouncer button = DigitalInOut(board.D4) button.direction = Direction.INPUT button.pull = Pull.UP switch = Debouncer(button) while True: switch.update() if switch.fell: print('pressed') print('was released for ', switch.last_duration) elif switch.rose: print('released') print('was pressed for ', switch.last_duration) else: print('Stable for ', switch.current_duration) time.sleep(0.1)
from adafruit_bluefruit_connect.color_packet import ColorPacket from adafruit_bluefruit_connect.button_packet import ButtonPacket # NeoPixel control pin pixel_pin = board.D5 # Number of pixels in the collar (arranged in two rows) pixel_num = 24 pixels = neopixel.NeoPixel(pixel_pin, pixel_num, brightness=0.5, auto_write=False) # Create a switch from the ItsyBity's on-board pushbutton to toggle charge mode mode_pin = digitalio.DigitalInOut(board.SWITCH) mode_pin.direction = digitalio.Direction.INPUT mode_pin.pull = digitalio.Pull.UP switch = Debouncer(mode_pin) # Create the animations comet = Comet(pixels, speed=0.06, color=(180,0,255), tail_length=10, bounce=True) chase = Chase(pixels, speed=0.05, size=3, spacing=3, color=(0,255,255), reverse=True) rainbow_comet = RainbowComet(pixels, speed=.06) pulse = Pulse(pixels, speed=.04, color=(255,0,0), period = 0.2) # Our animations sequence seconds_per_animation = 10 animations = AnimationSequence(comet, rainbow_comet, chase, advance_interval=seconds_per_animation, auto_clear=True) # Current display determines whether we are showing the animation sequence or the pulse animation current_display = animations # Mode changes the color of random animations randomly
# SPDX-FileCopyrightText: Copyright (c) 2021 John Park for Adafruit # # SPDX-License-Identifier: MIT # FunHouse Mail Slot Detector import board from adafruit_debouncer import Debouncer from digitalio import DigitalInOut, Pull from adafruit_funhouse import FunHouse beam_sense_pin = DigitalInOut(board.A0) # defaults to input beam_sense_pin.pull = Pull.UP # turn on internal pull-up resistor beam_sensor = Debouncer(beam_sense_pin) AMBER = 0xF0D000 BLUE = 0x00D0F0 RED = 0xFF0000 WHITE = 0xFFFFFF GRAY = 0x606060 funhouse = FunHouse(default_bg=None, scale=3) funhouse.peripherals.dotstars.brightness = 0.05 funhouse.peripherals.dotstars.fill(AMBER) # Create the labels funhouse.display.show(None) mail_label = funhouse.add_text(text="No Mail yet", text_position=(4, 14), text_color=AMBER) reset_label = funhouse.add_text(text="reset", text_position=(3, 70),
displayio.release_displays() # Set up button pins pin_a = digitalio.DigitalInOut(board.D9) pin_a.direction = digitalio.Direction.INPUT pin_a.pull = digitalio.Pull.UP pin_b = digitalio.DigitalInOut(board.D6) pin_b.direction = digitalio.Direction.INPUT pin_b.pull = digitalio.Pull.UP pin_c = digitalio.DigitalInOut(board.D5) pin_c.direction = digitalio.Direction.INPUT pin_c.pull = digitalio.Pull.UP button_a = Debouncer(pin_a) #9 button_b = Debouncer(pin_b) #6 button_c = Debouncer(pin_c) #5 # Load font font = bitmap_font.load_font('/mround-31.bdf') # Set up display & add group i2c = board.I2C() display_bus = displayio.I2CDisplay(i2c, device_address=0x3C) display = adafruit_displayio_ssd1306.SSD1306(display_bus, width=128, height=32) group = displayio.Group(max_size=1) display.show(group) # Add content to group default_text = "I VOTE !"
IMAGE_FOLDER = ( "/bmps", "/bmps2", "/bmps3", ) # pylint: disable=invalid-name # --- Display setup --- matrix = Matrix(bit_depth=6) display = matrix.display ACCEL = adafruit_lis3dh.LIS3DH_I2C(busio.I2C(board.SCL, board.SDA), address=0x19) _ = ACCEL.acceleration # Dummy reading to blow out any startup residue pin_down = DigitalInOut(board.BUTTON_DOWN) pin_down.switch_to_input(pull=Pull.UP) button_down = Debouncer(pin_down) pin_up = DigitalInOut(board.BUTTON_UP) pin_up.switch_to_input(pull=Pull.UP) button_up = Debouncer(pin_up) ALIGN_RIGHT = True auto_advance = True i = 0 NUM_FOLDERS = 2 #first folder is numbered 0 slideshow = SlideShow( display, None, folder=IMAGE_FOLDER[i], order=0,
def __init__(self, joy_z_pin=board.D2): self.joy_z_pin = DigitalInOut(joy_z_pin) self.joy_z_pin.direction = Direction.INPUT self.joy_z_pin.pull = Pull.UP self.joy_z = Debouncer(self.joy_z_pin)
mode_initiated = False mode_duration_counter = 0 mode_phase = 0 HIGHEST_MODE = 10 icon_counter = 0 fastloop_counter = 0 # Built in red LED led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT # Digital input with pullup on D7 button = DigitalInOut(board.D11) button.direction = Direction.INPUT button.pull = Pull.UP debounced_button = Debouncer(button) left_colors = [D_RED, D_RED, D_RED, D_RED, D_RED, D_RED, D_RED, D_RED] right_colors = [D_RED, D_RED, D_RED, D_RED, D_RED, D_RED, D_RED, D_RED] while True: # check_button() debounced_button.update() if debounced_button.fell: mode += 1 if mode > HIGHEST_MODE: mode = 0 mode_initiated = False mode_duration_counter = 0 mode_phase = 0
while x != display.width: x = x + 1 text_area.x = x chase_left.animate() chase_right.animate() time.sleep(0.008) # adjust to change scrolling speed # Remove any existing displays displayio.release_displays() # Set up the top button used to trigger a special message when pressed switch_pin = digitalio.DigitalInOut(board.SWITCH) switch_pin.direction = digitalio.Direction.INPUT switch_pin.pull = digitalio.Pull.UP switch = Debouncer(switch_pin) # Initialize the LED Glasses # # In this example scale is set to True. When True the logical display is # three times the physical display size and scaled down to allow text to # look more natural for small display sizes. Hence the display is created # as 54x15 when the physical display is 18x5. # i2c = busio.I2C(board.SCL, board.SDA, frequency=1000000) is31 = is31fl3741.IS31FL3741(i2c=i2c) is31_framebuffer = is31fl3741.IS31FL3741_FrameBuffer( is31, 54, 15, glassesmatrix_ledmap_no_ring, scale=True, gamma=True) display = framebufferio.FramebufferDisplay(is31_framebuffer, auto_refresh=True) # Set up the left and right eyelight rings
# define and set up inputs to use the debouncer def make_criket_signal_debouncer(pin): # create pin signal objects ss.pin_mode(pin, ss.INPUT_PULLUP) return Debouncer(lambda: ss.digital_read(pin)) # The IR sensors on are pullups, connect to ground to activate clock_pin = make_criket_signal_debouncer(crickit.SIGNAL1) voice_1_pin = make_criket_signal_debouncer(crickit.SIGNAL2) voice_2_pin = make_criket_signal_debouncer(crickit.SIGNAL3) voice_3_pin = make_criket_signal_debouncer(crickit.SIGNAL4) voice_4_pin = make_criket_signal_debouncer(crickit.SIGNAL5) # Crickit capacitive touch pads touch_1_pad = Debouncer(lambda: crickit.touch_1.value) touch_4_pad = Debouncer(lambda: crickit.touch_4.value) touch_2_3_pad = Debouncer( lambda: crickit.touch_2.value and crickit.touch_3.value) crickit.continuous_servo_1.set_pulse_width_range(min_pulse=500, max_pulse=2500) speed = -0.04 #this is clockwise/forward at a moderate tempo def play_voice(vo): mixer.stop_voice(vo) mixer.play(samples[vo], voice=vo, loop=False) while True: clock_pin.update() #debouncer at work
import time from math import ceil import board import rotaryio import neopixel from adafruit_debouncer import Debouncer import digitalio import pwmio # Setup the hardware encoder = rotaryio.IncrementalEncoder(board.D9, board.D7) button_io = digitalio.DigitalInOut(board.D10) button_io.direction = digitalio.Direction.INPUT button_io.pull = digitalio.Pull.UP button = Debouncer(button_io) strip = neopixel.NeoPixel(board.D11, 16, brightness=1, auto_write=False) last_position = 0 def check_encoder(): """Check if the encoder has been rotated. returns the direction (-1 or +1) if it has, 0 if not. """ global last_position position = encoder.position if position > last_position: direction = 1 elif position < last_position: