Terminate code mid way through with a button press

December 21, 2023, 00:36

stolenpies

Hi all, I have the following code (hopefully this is formatted correctly in discord)
import time
import board
import digitalio
import usb_hid
import sys
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode

btn1_pin = (board.GP16)
btn2_pin = (board.GP15)

# Set up the button
btn1 = digitalio.DigitalInOut(btn1_pin)
btn1.direction = digitalio.Direction.INPUT
btn1.pull = digitalio.Pull.DOWN

btn2 = digitalio.DigitalInOut(btn2_pin)
btn2.direction = digitalio.Direction.INPUT
btn2.pull = digitalio.Pull.DOWN

keyboard = Keyboard(usb_hid.devices)

while True:
    if btn1.value:
        keyboard.send(Keycode.A)
        time.sleep(01)
        keyboard.send(Keycode.A)
        time.sleep(01)
        keyboard.send(Keycode.A)
        time.sleep(01)
        keyboard.send(Keycode.A)
        time.sleep(01)
        keyboard.send(Keycode.A)
        time.sleep(01)
        keyboard.send(Keycode.A)
        time.sleep(01)
        keyboard.send(Keycode.A)
        time.sleep(01)
        keyboard.send(Keycode.A)
        time.sleep(01)
        
        
    if btn2.value:
        keyboard.releaseall()
(Eventually the A keycodes will be swapped for scroll down arrow commands to I can scroll up and down a page) What I'm finding impossible to do is to stop the code mid way though with the press of btn2. is there a way to do this? thanks.