Skip to content

Instantly share code, notes, and snippets.

@kou1okada
Last active August 5, 2025 11:59
Show Gist options
  • Save kou1okada/cf46d861ecb6e8ec69680cd7b73d5762 to your computer and use it in GitHub Desktop.
Save kou1okada/cf46d861ecb6e8ec69680cd7b73d5762 to your computer and use it in GitHub Desktop.
FootSwitch.py for Raspberry Pi Pico with CircuitPython
# FootSwitch.py for Raspberry Pi Pico with CircuitPython
# Copyright 2024 (c) Koichi OKADA. All right reserved.
# This script is distributed under the MIT license.
import usb_hid
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode
import time
import board
import digitalio
###############################################################################
# Configurations
# key mapping for GPIO.
# Max 28 keys, because GPIO of Raspberry Pi Pico is GP0-GP28.
KeyMap = [
Keycode.LEFT_CONTROL,
Keycode.LEFT_SHIFT,
Keycode.SPACE,
Keycode.B,
Keycode.E,
Keycode.F,
Keycode.G,
Keycode.ONE,
Keycode.TWO,
Keycode.THREE,
Keycode.FOUR,
Keycode.FIVE,
]
# deadtime [ns] for anti-chattering
deadtime = 1000**3 // 24
# wait [s] for 1 loop
wait = 0.001
# Debug level
debug = 0
###############################################################################
# Initialize
KeyStat = [0] * len(KeyMap)
Last = [0] * len(KeyMap)
IO = [
board.GP0,
board.GP1,
board.GP2,
board.GP3,
board.GP4,
board.GP5,
board.GP6,
board.GP7,
board.GP8,
board.GP9,
board.GP10,
board.GP11,
board.GP12,
board.GP13,
board.GP14,
board.GP15,
board.GP16,
board.GP17,
board.GP18,
board.GP19,
board.GP20,
board.GP21,
board.GP22,
board.GP23,
board.GP24,
board.GP25,
board.GP26,
board.GP27,
board.GP28,
]
gp = [None] * len(KeyMap)
kbd = Keyboard(usb_hid.devices)
for i in range(len(KeyMap)):
gp[i] = digitalio.DigitalInOut(IO[i])
gp[i].switch_to_input(pull=digitalio.Pull.UP)
led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT
t0 = t1 = t2 = t3 = time.monotonic_ns()
step = 0
###############################################################################
# main loop
while True:
t = t2 = time.monotonic_ns()
for i, io in enumerate(gp):
stat = not io.value
if stat != KeyStat[i] and deadtime < t - Last[i]:
Last[i] = t
KeyStat[i] = 0 if KeyStat[i] else 1
kbd.press(KeyMap[i]) if KeyStat[i] else kbd.release(KeyMap[i])
led.value = sum(KeyStat)
t3 = t1
t1 = time.monotonic_ns()
step += 1
if debug:
if 1 < debug:
print(f"[{time.monotonic_ns()}, {KeyStat}],")
if (step == 3000):
print(f"{step}, {t2 - t1}")
break
wait1 = wait - (time.monotonic_ns() - t2) / 1000**3
wait1 = wait1 if 0 < wait1 else 0
time.sleep(wait1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment