class PiperJoystickZ: 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) def update(self): self.joy_z.update() def zPressed(self): return not self.joy_z.value def zPressedEvent(self): return self.joy_z.fell def zReleasedEvent(self): return self.joy_z.rose
class DebouncedCursorManager(CursorManager): """Simple interaction user interface interaction for Adafruit_CursorControl. This subclass provide a debounced version on the A button and provides queries for when the button is just pressed, and just released, as well it's current state. "Just" in this context means "since the previous call to update." :param adafruit_cursorcontrol cursor: The cursor object we are using. """ 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, ) @property def is_clicked(self): """Returns True if the cursor button was pressed during previous call to update() """ return self._debouncer.rose pressed = is_clicked @property def released(self): """Returns True if the cursor button was released during previous call to update() """ return self._debouncer.fell @property def held(self): """Returns True if the cursor button is currently being held """ return self._debouncer.value def update(self): """Updates the cursor object.""" self._pressed = self._pad.get_pressed() self._check_cursor_movement(self._pressed) self._debouncer.update()
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)
(100, 0), (48, 40, 30, 25), ] cvsa_index = 0 cvsb_index = 2 cvai = 0 cvbi = 0 cva_last = time.monotonic() cvb_last = time.monotonic() cvsa = cvs_list[cvsa_index] cvsb = cvs_list[cvsb_index] while True: butt1.update() now = time.monotonic() if now > cva_last + rateA: cva_last = now cvai = (cvai + 1) % len(cvsa) duty_cycle = int(cvsa[cvai] * 65535 / 100) outA.duty_cycle = 65535 - duty_cycle if now > cvb_last + rateB: cvb_last = now cvbi = (cvbi + 1) % len(cvsb) duty_cycle = int(cvsb[cvbi] * 65535 / 100) outB.duty_cycle = 65535 - duty_cycle # rateA = 0.01 + (potAknob.value / 65535 / 2) rateA = (potAknob.value / 65535) #/ len(cvsa)) rateB = 0.01 + (potBknob.value / 65535 / 2) if butt1.fell: # pressed
class GPIOControl(Control): """ GPIO Control Get GPIO input via button, switch, etc. """ """ Properties """ @property def state(self): """ Return the state of the component (from memory, no IO!) """ return self._state if not self.invert_state else not self._state @property def state_changed(self): """ Return if the state changed from previous state""" return self.previous_state != self._state @property def elapsed_time(self): self.time_elapsed = time.perf_counter() - self.time_start return self.time_elapsed """ Methods """ 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 update(self): """ Get data from GPIO connection""" data = None self.previous_state = self.state if self.edge_detection is not None: self._control.update() if self.edge_detection == "both": if self._control.fell or self._control.rose: # Pressed or Released self._state = 1 if self._control_pin.value else 0 _event = "ControlUpdated" if self._control.rose: if self.invert_state: _event = "ControlReleased" else: _event = "ControlPressed" elif self._control.fell: if self.invert_state: _event = "ControlPressed" else: _event = "ControlReleased" self.fire({"event": _event}) else: # "fell" or "rose" if getattr(self._control, self.edge_detection): _event = "ControlUpdated" if self.edge_detection == "rose": if self.invert_state: _event = "ControlReleased" else: _event = "ControlPressed" elif self.edge_detection == "fell": if self.invert_state: _event = "ControlPressed" else: _event = "ControlReleased" self.fire({"event": _event}) self._state = 1 if self._control_pin.value else 0 else: # No edge detection self._state = 1 if self._control_pin.value else 0 if self.type == 'switch': if self.state_changed: self.fire() elif self.type == 'button': if self.state: if self.elapsed_time > UPDATE_THROTTLE: self.fire() self.reset_elapsed_time() else: if self.state_changed: self.fire() return data def reset_elapsed_time(self): """ Reset duration tracker """ self.time_start = time.perf_counter()
return min(max(mapped, out_max), out_min) touchA_min = touchA.raw_value recording = False record_start = 0 record_events = [] last_time = 0 delta_t = 0.05 playing_idx = 0 playing = False while True: dots.show() rec_switch.update() if not playing: touchA_val = map_range(touchA.raw_value, touchA_min, touchA_min * 2, 0, 255) touchB_val = touchB.value now = time.monotonic() if (now - last_time) > delta_t: last_time = now if recording: record_events.append( ((time.monotonic() - record_start), touchA_val, touchB_val)) else: if playing: (t, touchA_val, touchB_val) = record_events[playing_idx]
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: packet = rfm69.receive(timeout=0.1) if packet is None: LED.value = False else: LED.value = True print("{:+.1f}dbm '{}'" "".format( rfm69.rssi, str(packet, "utf-8"), ), ) print("send Welcome Here!!") rfm69.send(bytes("Welcome Here!!", "utf-8")) # check button input btn_red.update() if btn_red.fell: print("send HelloWorld!") rfm69.send(bytes("HelloWorld!", "utf-8"))
sin_wave = waveforms.Waveform('sin', steps=256) rnd_wave = waveforms.Waveform('rnd', steps=16) wave = sin_wave.wave volt_offset = 0.0 volt_amplitude = 2.0 period = 1.0 dt = period / len(wave) i = 0 val = 0 wave_index = 0 last_time = time.monotonic() while True: but1.update() but2.update() period = utils.map_range(knob_a.value, 0, 1023, 0.01, 10) now = time.monotonic() if now > dt + last_time: last_time = now wave_index = (wave_index + 1) % len(wave) print("updated", wave_index) # get the wave value, scale it by amplitude and offsetit val = offset + amplitude * wave[wave_index] # convert to volts and send it out set_out_a_volts(val) #note_volts = [0, 0.0833, 0.1666, 0.25, 0.333, 0.4166, 0.5, 0.5833, 0.6666, 0.75, 0.83333, 0.9166, 1] #note_volts = [0, 0.1666, 0.25, 0.333, 0.5, 0.6666, 0.75, 0.83333, 1]
class PiperDpad: 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 update(self): self.left.update() self.right.update() self.up.update() self.down.update() def leftPressed(self): return not self.left.value def leftPressedEvent(self): return self.left.fell def leftReleasedEvent(self): return self.left.rose def rightPressed(self): return not self.right.value def rightPressedEvent(self): return self.right.fell def rightReleasedEvent(self): return self.right.rose def upPressed(self): return not self.up.value def upPressedEvent(self): return self.up.fell def upReleasedEvent(self): return self.up.rose def downPressed(self): return not self.down.value def downPressedEvent(self): return self.down.fell def downReleasedEvent(self): return self.down.rose
reset_label = funhouse.add_text(text="reset", text_position=(3, 70), text_color=GRAY) funhouse.display.show(funhouse.splash) def send_io_data(mail_value): funhouse.peripherals.led = True funhouse.network.push_to_io("mail", mail_value) funhouse.peripherals.led = False send_io_data(1) while True: beam_sensor.update() if beam_sensor.fell: funhouse.peripherals.set_dotstars(RED, WHITE, BLUE, WHITE, RED) funhouse.peripherals.play_tone(2000, 0.25) funhouse.set_text("Mail is here!", mail_label) funhouse.set_text_color(BLUE, mail_label) send_io_data(0) if funhouse.peripherals.button_down: funhouse.peripherals.dotstars.fill(AMBER) funhouse.set_text("No Mail yet", mail_label) funhouse.set_text_color(AMBER, mail_label) send_io_data(1)
WHITE = 0xCCCCCC BLACK = 0x000000 pixel_pin = board.D9 pixels = neopixel.NeoPixel(pixel_pin, 2, brightness=1.0) pixels.fill(BLACK) time.sleep(0.3) pixels.fill(WHITE) time.sleep(0.3) pixels.fill(BLACK) time.sleep(0.3) pixels[0] = MAGENTA pixels[1] = CYAN while True: switch_a.update() # Debouncer checks for changes in switch state switch_b.update() if switch_a.fell: keyboard.press(switch_a_output) pixels[0] = WHITE if switch_a.rose: keyboard.release(switch_a_output) pixels[0] = MAGENTA if switch_b.fell: keyboard.press(switch_b_output) pixels[1] = WHITE if switch_b.rose: keyboard.release(switch_b_output) pixels[1] = CYAN
def play_song(songname): for note in songbook[songname]: play_note(note) def update(songnames, selected): oled.fill(0) line = 0 for songname in songnames: if line == selected: oled.text(">", 0, line * 8) oled.text(songname, 10, line * 8) line += 1 oled.show() selected_song = 0 song_names = sorted(list(songbook.keys())) while True: button_select.update() button_play.update() update(song_names, selected_song) if button_select.fell: print("select") selected_song = (selected_song + 1) % len(songbook) elif button_play.fell: print("play") play_song(song_names[selected_song])
global fontIndex previousFontIndex = fontIndex while fontIndex == previousFontIndex: fontIndex = random.randint(0, len(FONTS) - 1) def preloadLetter(letter): # TODO: Also preload next font? Both upper- and lower-case? label.Label(FONTS[fontIndex], text=letter) print(letter, end='') displayLetter() while True: leftButton.update() rightButton.update() selectButton.update() aButton.update() bButton.update() if leftButton.fell: backLetter() elif rightButton.fell: forwardLetter() if selectButton.fell: switchLetterCase() displayLetter() if aButton.fell:
button_b = digitalio.DigitalInOut(board.D3) button_b.direction = digitalio.Direction.INPUT button_b.pull = digitalio.Pull.UP button_bd = Debouncer(button_b) #led = digitalio.DigitalInOut(board.D9) #led.direction = digitalio.Direction.OUTPUT pwm = pulseio.PWMOut(board.D9, frequency=50) pwm.duty_cycle = 0 brightness = 0 step = 2048 while True: # print ( str(button_a.value) + ' ' + str(button_b.value) ) button_ad.update() if (button_ad.value == False): brightness += step if (brightness > 65535): brightness = 65535 button_bd.update() if (button_bd.value == False): brightness -= step if (brightness < 0): brightness = 0 pwm.duty_cycle = brightness # print (brightness) time.sleep(0.1)
def rainbow_cycle(iColor, wait): for i in range(pixels.n): idx = int((i * 256 / len(pixels)) + iColor) pixels[i] = wheel(idx & 255) pixels.write() time.sleep(wait) # Main Loop shouldTwinkle = True iColor = 0 while True: # use pad A1 as capacitive touch to toggle display modes touchSignal.update() if touchSignal.rose: print("Touched!") led.value = not led.value # toggle displayMode shouldTwinkle = not shouldTwinkle # time.sleep(0.25) pixels.fill((0, 0, 0)) # lightshow if (shouldTwinkle is True): flashRandom(0.02) else: iColor = (iColor + 1) % 256 # run from 0 to 255 rainbow_cycle(iColor, 0.001) # rainbowcycle with 1ms delay per step
# Provide a ground for the joystick - this is to facilitate # easier wiring joystick_gnd = DigitalInOut(board.A5) joystick_gnd.direction = Direction.OUTPUT joystick_gnd.value = 0 # Setup joystick pins, and choose an outputScale which results in an # easy to control mouse pointer # x_axis = PiperJoystickAxis(board.A4, outputScale=20) y_axis = PiperJoystickAxis(board.A3, outputScale=20) mouse = Mouse(usb_hid.devices) while True: # Call the debouncing library frequently left.update() right.update() dx = x_axis.readJoystickAxis() dy = y_axis.readJoystickAxis() mouse.move(x=dx, y=dy) if left.fell: mouse.press(Mouse.LEFT_BUTTON) elif left.rose: mouse.release(Mouse.LEFT_BUTTON) if right.fell: mouse.press(Mouse.RIGHT_BUTTON) elif right.rose: mouse.release(Mouse.RIGHT_BUTTON)
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT """ This example shows how to use the debouncer library on the signals coming from a cap-sense pin with touchio. """ import time import board import touchio from adafruit_debouncer import Debouncer touch_pad = board.A1 touch = touchio.TouchIn(touch_pad) touch_debounced = Debouncer(touch) while True: touch_debounced.update() if touch_debounced.fell: print("Just released") if touch_debounced.rose: print("Just pressed") if touch_debounced.value: print("touching") else: # print('not touching') pass time.sleep(0.05)
# Initialize things strip.fill(0x000000) strip.show() work_time = 6 break_time = 2 time_to_check = 0 state = False mode, dial_color, time_remaining, increment = compute_mode_settings(True) # The main loop while True: # check whether the rotary encoder has been pushed. If so enter time-set mode. button.update() if button.fell: work_time = set_timer(0x400000, work_time) break_time = set_timer(0x004000, break_time) strip.fill(0x000000) strip.show() mode, dial_color, time_remaining, increment = compute_mode_settings( True) now = time.monotonic() if now >= time_to_check: #only check each second time_remaining -= 1 if time_remaining <= 0: # time to switch modes? strip.fill(0x000000) # clear the dial strip.show() # make some noise beep(2, 0.5, 0.25, 4000)
# 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 !" text_area = label.Label(font, text=default_text, color=0xFFFFFF, x=0, y=17) group.append(text_area) while True: # Debounce buttons button_a.update() button_b.update() button_c.update() # Check for button presses & set text if button_a.fell: text_area.text = default_text text_area.x = 0 elif button_b.fell: text_area.text = "I VOTED!" text_area.x = 0 elif button_c.fell: text_area.text = "DID U?" text_area.x = 18 display.show(group)
class piperPin: def __init__(self, pin, name): self.pin = DigitalInOut(pin) self.debounced = Debouncer(self.pin) self.debouncedRising = Debouncer(self.pin) self.debouncedFalling = Debouncer(self.pin) self.name = name # Report the pin's state for use by the digital view # def reportPin(self, pinStr): global digital_view if digital_view: print(chr(17), self.name, "|", pinStr, chr(16), end="") # Sets the pin to be an output at the specified logic level # def setPin(self, pinState): global digital_view self.pin.direction = Direction.OUTPUT self.pin.value = pinState self.reportPin(str(pinState)) # Reads the pin by setting it to an input and setting it's pull-up/down and then returning its value # (Note that this means you can't use it to detect the state of output pins) # def checkPin(self, pinPull): self.pin.direction = Direction.INPUT self.pin.pull = pinPull pinValue = self.pin.value self.reportPin(str(float(pinValue))) return pinValue # Same as checkPin except debounced # def checkPinDebounced(self, pinPull): self.pin.direction = Direction.INPUT self.pin.pull = pinPull self.debounced.update() pinValue = self.debounced.value self.reportPin(str(float(pinValue))) return pinValue # Look for rising edge. Typically happens when a button (with pullup) # is released. # def checkPinRose(self, pinPull): self.pin.direction = Direction.INPUT self.pin.pull = pinPull self.debouncedRising.update() pinValue = self.debouncedRising.rose self.reportPin(str(float(pinValue))) # ??? return pinValue # Look for falling edge. Typically happens when a button (with pullup) # is pressed. # def checkPinFell(self, pinPull): self.pin.direction = Direction.INPUT self.pin.pull = pinPull self.debouncedFalling.update() pinValue = self.debouncedFalling.fell self.reportPin(str(float(pinValue))) # ??? return pinValue # Reads an analog voltage from the specified pin # def readVoltage(self): pinValue = self.pin.value / 65536 self.reportPin(str(pinValue)) return pinValue * 3.3
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 voice_1_pin.update() voice_2_pin.update() voice_3_pin.update() voice_4_pin.update() touch_1_pad.update() touch_4_pad.update() touch_2_3_pad.update() crickit.continuous_servo_1.throttle = speed # spin the disc at speed defined by touch pads if clock_pin.fell: # sensor noticed change from white (reflection) to black (no reflection) # this means a clock tick has begun, time to check if any steps will play led.value = 0 if voice_1_pin.value: # a black step (no reflection) mark during clock tick, play a sound! led.value = 1 # light up LED when step is read # print('| .kick. | | | |') play_voice(0) if voice_2_pin.value:
if not uart_connection: print("Scanning...") for adv in ble.start_scan(ProvideServicesAdvertisement, timeout=5): print(adv.address) print(type(adv.address)) if TARGET == adv.address: print("found target " + TARGET) uart_connection = ble.connect(adv) break # Stop scanning whether or not we are connected. ble.stop_scan() while uart_connection and uart_connection.connected: # r, g, b = map(scale, accelerometer.acceleration) switch.update() if switch.fell: # Check for button press try: uart_connection[UARTService].write( button_packet.to_bytes()) # Transmit press except OSError: pass uart_connection = None time.sleep(0.3) while True: uart_addresses = [] pixels[0] = BLUE # Blue LED indicates disconnected status pixels.show()
order=0, auto_advance=False, fade_effect=False, dwell=IMAGE_DURATION[i], h_align=HorizontalAlignment.RIGHT, ) last_movement = time.monotonic() MODE = 1 elif time.monotonic() > last_movement + SLEEP_DURATION: MODE = 0 display.show(empty_group) if MODE == 1: if auto_advance and time.monotonic( ) > LAST_ADVANCE + IMAGE_DURATION[i]: advance() button_down.update() button_up.update() if button_up.fell: auto_advance = not auto_advance if button_down.fell: i = i + 1 if i > NUM_FOLDERS: i = 0 slideshow = SlideShow( display, None, folder=IMAGE_FOLDER[i], order=0, auto_advance=False, fade_effect=False, dwell=IMAGE_DURATION[i],
class Control(): def __init__(self, pin, name=None, key=None, resistor=None, edge_detection=None, debounce=None, redis_conn=None): self.pin_obj = getattr(board, pin) if key is None: raise Exception('No "key" Found in Control Config') else: self.key = key.replace(" ", "_").lower() if name is None: self.name = self.key.replace("_", " ").title() else: self.name = name self.gpio = digitalio self.debounce = debounce if debounce is not None else None try: self.r = redis_conn if redis_conn is not None else redis.Redis( host='127.0.0.1', port=6379) except KeyError: self.r = redis.Redis(host='127.0.0.1', port=6379) if resistor is not None: if resistor == "up" or resistor == digitalio.Pull.UP: self.resistor = digitalio.Pull.UP elif resistor == "down" or resistor == digitalio.Pull.DOWN: self.resistor = digitalio.Pull.DOWN else: self.resistor = resistor if edge_detection is not None: if edge_detection == "falling" or edge_detection == "fell": self.edge_detection = "fell" elif edge_detection == "rising" or edge_detection == "rose": self.edge_detection = "rose" elif edge_detection == "both": self.edge_detection = "both" else: self.edge_detection = None return 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 read(self): """Read the sensor(s), parse the data and store it in redis if redis is configured If edge detection is being used return the detection event instead""" if self.edge_detection is not None: self.button.update() if self.edge_detection == "both": if self.button.fell or self.button.rose: return True else: return False else: # "fell" or "rose" return getattr(self.button, self.edge_detection) else: return None def read_raw(self): """Read the sensor(s) but return the raw data, useful for debugging""" pass def read_pin(self): """Read the pin from the board digital reads only""" data = self.gpio.DigitalInOut(self.pin_obj).value return data def emitEvent(self, data): message = {'event': 'ControlUpdate', 'data': {self.key: data}} print(message["data"]) self.r.publish('controls', json.dumps(message))
import time # https://snapcraft.io/install/micropython/raspbian # sudo apt update # sudo apt install snapd # sudo reboot # sudo snap install micropython bus = SMBus(1) # Create a new I2C bus i2caddress1 = 0x38 # Address of MCP23017 device i2caddress2 = 0x39 # Address of MCP23017 device BUT_MASK = 0x01FF def readSignal(): data = bus.read_byte_data(i2caddress1, BUT_MASK) return data >> 1 & 1 signal = Debouncer(readSignal) while True: signal.update() if signal.fell: print('Just pressed') if signal.rose: print('Just released')
keep_this_rgb = 0 btn1_start_time = 0 btn2_start_time = 0 btn3_start_time = 0 btn4_start_time = 0 btn1_status = "waiting" btn2_status = "waiting" btn3_status = "waiting" btn4_status = "waiting" knob_r_prior_disp_saved_mode = 0 knob_g_prior_disp_saved_mode = 0 knob_b_prior_disp_saved_mode = 0 while True: # check_button() debounced_button1.update() debounced_button2.update() debounced_button3.update() debounced_button4.update() if debounced_button1.fell: btn1_start_time = time.monotonic() circle_mem_1.outline = D_YELLOW btn1_status = "pressed" if debounced_button2.fell: btn2_start_time = time.monotonic() circle_mem_2.outline = D_YELLOW btn2_status = "pressed" if debounced_button3.fell: btn3_start_time = time.monotonic() circle_mem_3.outline = D_YELLOW
# 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 time.sleep(0.01) fastloop_counter += 1 if fastloop_counter > 9: fastloop_counter = 0 else: continue
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT from adafruit_debouncer import Debouncer from adafruit_pybadger import pybadger b_btn = Debouncer(lambda: pybadger.button.b == 0) a_btn = Debouncer(lambda: pybadger.button.a == 0) up_btn = Debouncer(lambda: pybadger.button.up == 0) down_btn = Debouncer(lambda: pybadger.button.down == 0) left_btn = Debouncer(lambda: pybadger.button.left == 0) right_btn = Debouncer(lambda: pybadger.button.right == 0) while True: b_btn.update() a_btn.update() up_btn.update() down_btn.update() right_btn.update() left_btn.update() if b_btn.fell: print("B pressed") if b_btn.rose: print("B released") if a_btn.fell: print("A pressed") if a_btn.rose: print("A released")
class PiperMineCraftButtons: 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 update(self): if self.mc_top: self.mc_top.update() if self.mc_middle: self.mc_middle.update() if self.mc_bottom: self.mc_bottom.update() def topPressed(self): if self.mc_top: return not self.mc_top.value else: return False def topPressedEvent(self): if self.mc_top: return self.mc_top.fell else: return False def topReleasedEvent(self): if self.mc_top: return self.mc_top.rose else: return False def middlePressed(self): if self.mc_middle: return not self.mc_middle.value else: return False def middlePressedEvent(self): if self.mc_middle: return self.mc_middle.fell else: return False def middleReleasedEvent(self): if self.mc_middle: return self.mc_middle.rose else: return False def bottomPressed(self): if self.mc_bottom: return not self.mc_bottom.value else: return False def bottomPressedEvent(self): if self.mc_bottom: return self.mc_bottom.fell else: return False def bottomReleasedEvent(self): if self.mc_bottom: return self.mc_bottom.rose else: return False
# pylint: disable=invalid-name import board import digitalio from adafruit_debouncer import Debouncer pin = digitalio.DigitalInOut(board.D11) pin.direction = digitalio.Direction.INPUT pin.pull = digitalio.Pull.UP switch1 = Debouncer(pin) switch2 = Debouncer(board.D12) while True: switch1.update() switch2.update() if switch1.fell: print('Just pressed 1') if switch1.rose: print('Just released 1') if switch1.value: print('not pressed 1') else: print('pressed 1') if switch2.fell: print('Just pressed 2') if switch2.rose: print('Just released 2') if switch2.value: