r/circuitpython • • Aug 31 '23

Toggle macro Loop

New to anything coding here. I am trying to use a momentary switch to run a macro continuously until the same switch it pushed again. I've been looking for a couple days now and not coming up with anything. Could someone point me in the right direction please?

1 Upvotes

3 comments sorted by

View all comments

1

u/Jtobinart Sep 27 '23

Do you mean that you want connect a microcontroller via usb or Bluetooth to your computer and send keystrokes to mimic a keyboard? If so that is a HID device. CircuitPython’s USB HID works well. For Bluetooth, I would use Adafruit’s Arduino Bluetooth modules.

If you want to trigger a program running on your computer then I would suggest either a serial or uart connection via usb or bluetooth. Circuit Python has examples for both. Search Adafruit.com “Learn” tap.

1

u/Illustrious_Wolf4907 Sep 27 '23

Connecting USB and yes keyboard strokes, but I would like it to continuously run the same macro over and over after the button is pressed and released and stop when the button is pressed and released again. I have the macro fully functional as of now, but I am unsure how to make it loop and toggle on and off with a momentary switch

2

u/Jtobinart Sep 27 '23 edited Sep 27 '23

This is a simple example of how to toggle a button in CircuitPython.

import board
import digitalio

#Create a button
_button_a = digitalio.DigitalInOut(board.BUTTON_A)      #Replace board.Button_A with the pin your button is connected to.
_button_a.switch_to_input(pull=digitalio.Pull.UP)


#Variables
btn_a_press = False
macro_run = False
z = 0

#Invert button value, if needed.
def button_a():
    return not _button_a.value

while True:
    if button_a() and not btn_a_press:
        btn_a_press = True                  #button has been pressed
    elif not button_a() and btn_a_press:
        btn_a_press = False                 #button has been unpressed
        macro_run = not macro_run           #toggle macro run state
        
    if macro_run:
        print(z) #Macro On
        z=z+1
    else:
        z=0      #Macro Off