Skip to content

Instantly share code, notes, and snippets.

@idriszmy
Created July 6, 2021 04:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save idriszmy/1459b7ff3768a474f5c997973a6a85ac to your computer and use it in GitHub Desktop.
Save idriszmy/1459b7ff3768a474f5c997973a6a85ac to your computer and use it in GitHub Desktop.
DIY USB Keyboard Mouse Using Maker Pi Pico
'''
References:
- CircuitPython HID Keyboard and Mouse
https://learn.adafruit.com/circuitpython-essentials/circuitpython-hid-keyboard-and-mouse
CircuitPython libraries bundle: https://circuitpython.org/libraries
Additional libraries:
- adafruit_hid
Last Modified
- 6 July 2021
'''
import time
import analogio
import board
import digitalio
import usb_hid
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
from adafruit_hid.keycode import Keycode
from adafruit_hid.mouse import Mouse
x_axis = analogio.AnalogIn(board.A1)
y_axis = analogio.AnalogIn(board.A0)
control_key = Keycode.SHIFT
# Sleep for a bit to avoid a race condition on some systems
time.sleep(1)
mouse = Mouse(usb_hid.devices)
keyboard = Keyboard(usb_hid.devices)
keyboard_layout = KeyboardLayoutUS(keyboard) # We're in the US :)
pot_min = 0.8
pot_max = 2.5
step = (pot_max - pot_min) / 20.0
def get_voltage(pin):
return (pin.value * 3.3) / 65536
def steps(axis):
""" Maps the potentiometer voltage range to 0-20 """
result = round((axis - pot_min) / step)
if result > 8 and result < 12:
result = 10
return result
buttons_pressed = False
while True:
x = get_voltage(x_axis)
y = get_voltage(y_axis)
if x > 3.0:
mouse.click(Mouse.LEFT_BUTTON)
time.sleep(0.2) # Debounce delay
#print(steps(x), steps(y))
#time.sleep(0.1)
if steps(x) == 10 and steps(y) == 10:
if buttons_pressed == True:
buttons_pressed = False
keyboard.release_all()
mouse.release_all()
else:
if buttons_pressed == False:
buttons_pressed = True
keyboard.press(control_key)
time.sleep(0.1)
mouse.press(Mouse.MIDDLE_BUTTON)
if steps(x) > 11.0:
#print(steps(x))
mouse.move(x=1)
if steps(x) < 9.0:
#print(steps(x))
mouse.move(x=-1)
if steps(x) > 19.0:
#print(steps(x))
mouse.move(x=2)
if steps(x) < 1.0:
#print(steps(x))
mouse.move(x=-2)
if steps(y) > 11.0:
#print(steps(y))
mouse.move(y=-1)
if steps(y) < 9.0:
#print(steps(y))
mouse.move(y=1)
if steps(y) > 19.0:
#print(steps(y))
mouse.move(y=-2)
if steps(y) < 1.0:
#print(steps(y))
mouse.move(y=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment