# Keyboard Emulator Using a Pi Pico and CircuitPython
# Additional Libraries: adafruit_hid

# Original code: 2018 Kattni Rembor for Adafruit Industries (MIT License)
# Updated version: 2024 Steve McL for Iffy Books (wtfpl)

import time
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

# The keyboard object
time.sleep(1)  # Sleep for a bit to avoid a race condition on some systems
keyboard = Keyboard(usb_hid.devices)
keyboard_layout = KeyboardLayoutUS(keyboard)  # US keyboard layout

# The pins we'll use for our switches
keypress_pins = [board.GP3, board.GP7, board.GP12]

# Our array of key objects
key_pin_array = []

# Make all pin objects' inputs with pullups
for pin in keypress_pins:
    key_pin = digitalio.DigitalInOut(pin)
    key_pin.direction = digitalio.Direction.INPUT
    key_pin.pull = digitalio.Pull.UP
    key_pin_array.append(key_pin)

# For most CircuitPython boards:
led = digitalio.DigitalInOut(board.GP28)
led.direction = digitalio.Direction.OUTPUT

print("Waiting for key pin...")

while True:
    # Check each pin
    for key_pin in key_pin_array:
        if not key_pin.value:  # Is it grounded?
            i = key_pin_array.index(key_pin)
            print("Pin " + str(i) + " is grounded")

            # Turn on the red LED
            led.value = True

            # Wait for the pin to be ungrounded
            while not key_pin.value:
                pass

            # Action for first key
            if i==0:
                keyboard_layout.write("Hey! It works!")

            # Action for second key
            elif i==1:
                keyboard.press(Keycode.CONTROL, Keycode.TAB)
                keyboard.release_all() 
            
            # Action for third key
            elif i==2:
                for number in range(25):
                    keyboard_layout.write(str(number))
                    keyboard_layout.write("\n")

            # Turn off the red LED
            led.value = False

    time.sleep(0.01)