Skip to content

Instantly share code, notes, and snippets.

@todbot
Last active June 26, 2024 17:57
Show Gist options
  • Save todbot/9cca8ae20f0a44e0863efe6523ab521a to your computer and use it in GitHub Desktop.
Save todbot/9cca8ae20f0a44e0863efe6523ab521a to your computer and use it in GitHub Desktop.
Demonstrate rotaryio sending USB keyboard events in CircuitPython on RaspberryPiPico
# wire a rotary encoder to GP2,GP3, and encoder switch to GP4, with commons going to Gnd
import board
import rotaryio
import keypad
import usb_hid
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode
CLK_PIN = board.GP4
DT_PIN = board.GP3
SW_PIN = board.GP2
keyboard = Keyboard(usb_hid.devices)
encoder = rotaryio.IncrementalEncoder(CLK_PIN, DT_PIN) # must be consecutive on Pico
encoder_button = keypad.Keys(pins=(SW_PIN,), value_when_pressed=False)
last_position = encoder.position
def left():
print("left")
keyboard.send(Keycode.D)
def right():
print("right")
keyboard.send(Keycode.A)
while True:
pos = encoder.position
if pos > last_position:
left()
if pos < last_position:
right()
last_position = pos
if button := encoder_button.events.get():
if button.pressed:
print("pressed!")
if button.released:
print("released!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment