Skip to main content

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.

One object, six buttons

Button() takes over every button and installs the interrupts at once — no per-button instances.

Short and long press callbacks

register_callback('center', 'long', cb) — one press-and-release produces exactly one event.

Buttons feed the watchdog

Every press sets an activity flag that the launcher uses to decide on auto shutdown.

Hardware and pins​

ButtonGPIOLevel when pressedInternal resistorNotes
up46low (0)pull-updirection key
down0low (0)pull-updirection key
left18low (0)pull-updirection key
right45low (0)pull-updirection key
center43low (0)pull-updirection key (confirm)
start44high (1)pull-downthe 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 / right land 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 button module and cannot be changed in software. For where the buttons sit on the body, see Basic Operations.

Quick start​

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_callbackPolling get_button_state
When it firesShort press on release, long press when the threshold is reachedYou ask "is it held right now?" in your main loop
Good forOne-shot actions: tap to confirm, hold to exitContinuous actions: hold to change speed or brightness
Runs inInterrupt context — keep it very shortNormal context, can take as long as you like
Typical pageMenu confirm / exitFine-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
ArgumentTypeDefaultDescription
long_press_thresholdint1000How long counts as a long press, in milliseconds
debounce_timeint50Debounce 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
ArgumentTypeDescription
button_namestr'up' / 'down' / 'left' / 'right' / 'center' / 'start'
press_typestr'short' or 'long'
callbackfunctionA 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_name or press_type raises 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 (not False) when the name is not in the button table or the instance has been deinit()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 returns None, and further register_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_flag is a class variable: it is set to True the moment any button is pressed.
  • check_and_reset_activity() is a class method: it returns True and clears the flag if there was activity, otherwise False. 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 Button instance 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, and activity_flag still gets set normally. But if your app calls deinit(), no activity flag is produced while it runs.

How short and long press are decided​

A full press-and-release goes like this:

  1. 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.
  2. 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.
  3. 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​

SymptomCause / fix
Registered callback never firesName or type misspelled ('Up', 'press') → silently ignored; use all-lowercase 'up' / 'short'
Nothing happens when releasing after a long pressBy design: once a long press has reported, no short press follows
Long press unreliable when two buttons are heldAll six buttons share one timer instance, so only one button can be waiting for a long press at a time
Fast repeated taps get droppedDefault 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 rebootsCallbacks run in interrupt context → set a flag there and do the real work in the main loop
Two Button() instancesA GPIO has one interrupt, the newer one replaces the older → create exactly one per program
get_button_state() always returns NoneThe name is not in the table, or the instance was already deinit()ed
Buttons behave oddly after exiting the appdeinit() was skipped and the old handlers are still attached → always call it before exiting
Reading Pin.value() directly gives inverted logicstart is high-triggered (pull-down) while the rest are low-triggered → let get_button_state() decide for you
Device shuts down after a whileThat 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​

SymptomCause / fix
No button respondsNo Button() instance was created, or it was deinit()ed immediately
One button always reads as pressedThat 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 pressThe callback does memory-heavy or slow work (interrupt context) → set a flag instead
A short press is occasionally taken as a long presslong_press_threshold is too small → raise it
Short presses occasionally get lostDebounce window too long, or the press is too quick → lower debounce_time
An extra event arrives after releaseMechanical bounce outside the debounce window → raise debounce_time (the default 50 ms is usually enough)
Occasional glitches when used with the screen or LED stripThe 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.

Agent entry (coming soon)

The entry link will go here. Once it is live, one click takes you straight to describing the app you want.