Button Control (button)
The Beetle S1 has six buttons on the body: five direction keys (up / down / left / right / center) plus one function key (start). The firmware wraps pin configuration, debouncing and press-length detection into the button module: create one Button() object, register callbacks, and you get separate "short press" and "long press" events.
Button() takes over every button and installs the interrupts at once — no per-button instances.
register_callback('center', 'long', cb) — one press-and-release produces exactly one event.
Every press sets an activity flag that the launcher uses to decide on auto shutdown.
Hardware and pins
| Button | GPIO | Level when pressed | Internal resistor | Notes |
|---|---|---|---|---|
up | 46 | low (0) | pull-up | direction key |
down | 0 | low (0) | pull-up | direction key |
left | 18 | low (0) | pull-up | direction key |
right | 45 | low (0) | pull-up | direction key |
center | 43 | low (0) | pull-up | direction key (confirm) |
start | 44 | high (1) | pull-down | the body's "function key", unique to the S1 |
Interrupts are triggered on both edges (IRQ_FALLING | IRQ_RISING), so the handler runs on press and on release.
Two things worth knowing:
up/down/rightland on GPIO46 / GPIO0 / GPIO45, which are ESP32-S3 strapping pins. The S1 pulls them up so power-on always sees normal boot levels — which also means they should not be reused for other peripherals.- The pin numbers are hardcoded in the
buttonmodule and cannot be changed in software. For where the buttons sit on the body, see Basic Operations.
Quick start
Callback style (recommended)
from button import Button
buttons = Button() # defaults: 1 s counts as a long press, 50 ms debounce
def on_confirm():
print("confirm")
def on_exit():
print("exit")
buttons.register_callback('center', 'short', on_confirm)
buttons.register_callback('center', 'long', on_exit)
What you'll see: tapping center prints "confirm"; holding center for more than a second prints "exit", and releasing afterwards does not print "confirm".
Polling style
import time
from button import Button
buttons = Button()
value = 50
while True:
if buttons.get_button_state('left'): # hold left to increase
value = min(100, value + 1)
elif buttons.get_button_state('right'): # hold right to decrease
value = max(0, value - 1)
time.sleep(0.03) # about 33 times per second
What you'll see: holding left steps the value up continuously, holding right steps it down — ideal for "hold to adjust" interactions.
Which one should you use?
Callback register_callback | Polling get_button_state | |
|---|---|---|
| When it fires | Short press on release, long press when the threshold is reached | You ask "is it held right now?" in your main loop |
| Good for | One-shot actions: tap to confirm, hold to exit | Continuous actions: hold to change speed or brightness |
| Runs in | Interrupt context — keep it very short | Normal context, can take as long as you like |
| Typical page | Menu confirm / exit | Fine-tuning a parameter |
You can use both at once: register a short-press callback for a button and also poll its state in the main loop, with no interference.
API reference
Button(long_press_threshold=1000, debounce_time=50)
from button import Button
buttons = Button() # 1 s long press, 50 ms debounce
buttons = Button(long_press_threshold=500) # 0.5 s now counts as a long press
buttons = Button(debounce_time=20) # more responsive debounce
| Argument | Type | Default | Description |
|---|---|---|---|
long_press_threshold | int | 1000 | How long counts as a long press, in milliseconds |
debounce_time | int | 50 | Debounce window, in milliseconds |
Returns the button object. Constructing it configures all six GPIOs (up / down / left / right / center pull-up, start pull-down) and installs both-edge interrupts.
- Create only one instance per program. A GPIO has a single interrupt handler, so a second instance replaces the first and neither works properly.
- Per-button state, timers and callback tables are all built in the constructor, so you can register callbacks immediately afterwards.
register_callback(button_name, press_type, callback)
buttons.register_callback('up', 'short', on_up) # up, short press
buttons.register_callback('center', 'long', on_exit) # center, long press
| Argument | Type | Description |
|---|---|---|
button_name | str | 'up' / 'down' / 'left' / 'right' / 'center' / 'start' |
press_type | str | 'short' or 'long' |
callback | function | A function that takes no arguments |
No return value. Only the last callback is kept per button per event type; registering again overwrites it.
- A misspelled
button_nameorpress_typeraises nothing — the call is silently ignored. This is the pitfall that costs people the most time; names must be all lowercase. - Registering no callback at all is fine: the button still sets the activity flag, and
get_button_state()still works.
get_button_state(button_name)
pressed = buttons.get_button_state('left') # True means it is being held right now
Returns bool. The module already handles polarity for you (low-triggered buttons are inverted, start is not), so you only look at True / False.
- It reads the pin's current level — no debouncing and no press-length logic — which makes it the right choice for "held down" checks in a main loop.
- It returns
None(notFalse) when the name is not in the button table or the instance has beendeinit()ed.
deinit()
buttons.deinit()
No arguments, no return value. Releases everything: stops the timers, removes all interrupt handlers and clears the internal dictionaries.
- Always call it before your program exits. If the interrupts are still attached to the GPIOs when control returns to the launcher, buttons get handled by two code paths at once.
- Afterwards the instance is dead:
get_button_state()only returnsNone, and furtherregister_callback()calls have no effect.
check_and_reset_activity() and activity_flag
from button import Button
if Button.check_and_reset_activity():
print("there was button activity")
Button.activity_flagis a class variable: it is set toTruethe moment any button is pressed.check_and_reset_activity()is a class method: it returnsTrueand clears the flag if there was activity, otherwiseFalse. You can call it without an instance.- The launcher's auto-shutdown thread calls it once per second and resets the idle timer when there is activity — so using the buttons keeps the device from shutting down on schedule.
- Only one
Buttoninstance can be truly active at a time (there is one interrupt per pin). The launcher has one for auto shutdown; when your app creates another it takes over the same interrupts, andactivity_flagstill gets set normally. But if your app callsdeinit(), no activity flag is produced while it runs.
How short and long press are decided
A full press-and-release goes like this:
- Press → interrupt fires → once debounce passes: set
activity_flag, record the press time, mark the state as pressed, and start a one-shot timer with period =long_press_threshold. - Timer expires while still held → the long-press callback runs. The timer is one-shot and is not restarted, so a long press fires exactly once.
- Release → the held duration is computed: shorter than the threshold → short-press callback; equal or longer → nothing (the long press already reported).
The conclusion: a long press never also reports a short press, so one interaction produces at most one event.
Common pitfalls
| Symptom | Cause / fix |
|---|---|
| Registered callback never fires | Name or type misspelled ('Up', 'press') → silently ignored; use all-lowercase 'up' / 'short' |
| Nothing happens when releasing after a long press | By design: once a long press has reported, no short press follows |
| Long press unreliable when two buttons are held | All six buttons share one timer instance, so only one button can be waiting for a long press at a time |
| Fast repeated taps get dropped | Default 50 ms debounce window, so consecutive presses must be farther apart → use Button(debounce_time=20) |
| Slow or heavy work in a callback causes hangs or reboots | Callbacks run in interrupt context → set a flag there and do the real work in the main loop |
Two Button() instances | A GPIO has one interrupt, the newer one replaces the older → create exactly one per program |
get_button_state() always returns None | The name is not in the table, or the instance was already deinit()ed |
| Buttons behave oddly after exiting the app | deinit() was skipped and the old handlers are still attached → always call it before exiting |
Reading Pin.value() directly gives inverted logic | start is high-triggered (pull-down) while the rest are low-triggered → let get_button_state() decide for you |
| Device shuts down after a while | That is the S1 auto-sleep (300 s with no button activity by default), not a broken button → press any key, or turn auto_shutdown off in config.json |
More recipes
Beep feedback on every button
import beep
from button import Button
def feedback():
beep.tone(2000, 60)
buttons = Button()
for name in ('up', 'down', 'left', 'right', 'center'):
buttons.register_callback(name, 'short', feedback)
Hold-to-repeat
A long-press callback fires only once. For "hold and repeat", set a flag in the callback and let the main loop handle the timing:
import time
from button import Button
repeat = False
buttons = Button()
def on_down():
global repeat
repeat = True
buttons.register_callback('down', 'long', on_down)
while True:
if repeat and buttons.get_button_state('down'):
print("repeating")
time.sleep(0.2)
else:
repeat = False
time.sleep(0.02)
Complete example
Save this as /sd/apps/button-demo/boot.py on the SD card: up/down change the brightness level, a long press of center exits. The callbacks only change a number and set a flag, while everything heavy (printing, beeping, refreshing the strip) happens in the main loop — the only safe pattern inside interrupt context.
import time
import beep
from button import Button
level = 5 # brightness level 0-10
dirty = False # is there a change waiting to be handled
running = True
def bump(delta):
"""The callback does the lightest possible work: change a number, set a flag"""
global level, dirty
level = max(0, min(10, level + delta))
dirty = True
def on_exit():
global running
running = False
buttons = Button()
buttons.register_callback('up', 'short', lambda: bump(1))
buttons.register_callback('down', 'short', lambda: bump(-1))
buttons.register_callback('center', 'long', on_exit)
try:
while running:
if dirty:
dirty = False
brightness = level / 10
print("brightness:", brightness)
beep.tone(2000, 40)
# Put the real work here: refresh the LED strip, draw on the screen...
time.sleep(0.03)
finally:
beep.stop()
buttons.deinit()
Troubleshooting
| Symptom | Cause / fix |
|---|---|
| No button responds | No Button() instance was created, or it was deinit()ed immediately |
| One button always reads as pressed | That pin is used by another peripheral or shorted, or the key is stuck → check each one with get_button_state() |
| The device reboots on a press | The callback does memory-heavy or slow work (interrupt context) → set a flag instead |
| A short press is occasionally taken as a long press | long_press_threshold is too small → raise it |
| Short presses occasionally get lost | Debounce window too long, or the press is too quick → lower debounce_time |
| An extra event arrives after release | Mechanical bounce outside the debounce window → raise debounce_time (the default 50 ms is usually enough) |
| Occasional glitches when used with the screen or LED strip | The callback and the main loop touch the same data → keep callbacks to simple variables and hand complex structures to the main loop |
Related modules: LED Control (WS2812) · Buzzer (beep) · Display (ST7789)
AI usage (coming soon)
Soon you won't have to write debouncing yourself or wonder what is safe inside a callback: describe the button interaction you want in plain language, and the Agent will follow the APIs in this page to generate a complete program that runs on the Beetle S1.
For example, just say:
Up brightens and down dims, a long press of center exits; beep on every press, and stop the buzzer before exiting.
It will combine Button callbacks, get_button_state() and beep into a working program, and place it in /sd/apps/ on the SD card.
The entry link will go here. Once it is live, one click takes you straight to describing the app you want.