Skip to main content

Five-Way Button (button)

button is the built-in five-way button input module of the Firefly T1 firmware. It detects short presses and long presses on the up, down, left, right and center buttons using interrupts plus debouncing, and hands each event to your program through a callback.

Fixed pins

up=18, down=45, left=46, right=0, center=44; internal pull-up, active low.

Frozen into the firmware

Just use from button import Button. Nothing has to be copied to the SD card.

Event-driven

Your main loop focuses on rendering light effects while callbacks handle button events.

Pinout​

up (GPIO18)
left (GPIO46) center (GPIO44) right (GPIO0)
down (GPIO45)
Button name (button_name)GPIONotes
up18Regular GPIO
down45Strapping pin
left46Strapping pin
right0Strapping pin, and the BOOT button
center44Regular GPIO
Do not hold down, left or right at power-on / reset

These three pins (GPIO0 / GPIO45 / GPIO46) are ESP32-S3 strapping pins: they decide the boot mode at the exact moment of power-on or reset.

Pressing them after boot is completely fine; but if one is held during power-on / reset, the device may fail to boot normally or enter download mode.

Quick Start​

from button import Button
import time

buttons = Button() # only ONE per program

def on_center_short():
print("center short press")

buttons.register_callback('center', 'short', on_center_short)

while True:
time.sleep(0.1)

What you see: every press-and-release of the center button prints "center short press" once in the REPL. Note that it prints at the moment of release, not the moment you press.

API Reference​

Constructor Button()​

Button(long_press_threshold=1000, debounce_time=50)
ParameterUnitDefaultSuggestedDescription
long_press_thresholdms1000300–3000Holding longer than this counts as a long press
debounce_timems5020–50Debounce; applies to both the press and the release edge

It starts listening immediately after construction — there is no separate start(). It takes over the interrupts of five GPIOs and hardware timer Timer(1).

buttons = Button(long_press_threshold=500, debounce_time=30)

Register a callback register_callback()​

register_callback(button_name, press_type, callback)
ParameterTypeValue
button_namestr'up' / 'down' / 'left' / 'right' / 'center'
press_typestr'short' / 'long'
callbackfunctionA zero-argument function

Returns nothing. Three behaviours you must know:

  • Wrong parameters do not raise an error — they fail silently ('Center' or 'mid' simply do nothing). This is the most common pitfall;
  • Registering the same button and event again replaces the previous callback; callbacks do not stack;
  • Callbacks cannot take arguments. To pass a value, use a default-argument closure: lambda n=name: print(n).

Read the state get_button_state()​

get_button_state(button_name) # returns bool or None

Returns whether the button is currently held; returns None for an invalid button name.

It reads the pin directly, bypassing debouncing and the internal state, so it suits continuous processing while a button is held — for example, holding a button to sweep a parameter:

while buttons.get_button_state('center'):
print("center held...")
time.sleep(0.1)

Release resources deinit()​

deinit()

Stops every timer, detaches the interrupts of all five GPIOs and clears the internal state.

The instance is dead after deinit()

Calling register_callback() or get_button_state() afterwards raises an exception. To use the buttons again, construct a new instance.

Trigger Timing​

This is the easiest part of the module to get wrong. The exact behaviour of the four scenarios:

ScenarioActual behaviour
Short press (press → release, total duration below the threshold)Fires 'short' once at the moment of release
Long press (held until the threshold)Fires 'long' once at the moment the threshold is reached — once only, no auto-repeat
Releasing after a long pressDoes not fire 'short'
Holding two buttons at onceOnly the last pressed button can complete long-press detection

Common Pitfalls​

  1. All five buttons share one Timer(1). On the ESP32 port Timer(1) and Timer(3) are the same timer, so simultaneous long presses cannot work; do not use Timer(1) / Timer(3) in your own code either.
  2. Only one Button instance may exist. Each GPIO keeps only the last interrupt handler, so a second instance silently kills every callback of the first. Keep it in a module-level variable.
  3. Callbacks run in the scheduler context and block the main loop. Inside a callback, only print, set a flag, or call beep.tone(). Move screen redraws, long sleeps and complex I2C/SPI work to the main loop.
  4. Extremely quick taps get swallowed by debouncing. If a tap's total "press → release" time is shorter than debounce_time, the release event is filtered out, the short press never fires, and the internal state needs another press to recover. The default 50 ms is safe for normal tapping (about 60–150 ms).
  5. No double-click or auto-repeat detection. Implement it yourself by comparing two short-press timestamps with time.ticks_ms() (see the recipes below).
from button import Button
import time

buttons = Button()
pending = {'prev': False, 'next': False}

def on_left():
pending['prev'] = True # only sets a flag — very fast

def on_right():
pending['next'] = True

buttons.register_callback('left', 'short', on_left)
buttons.register_callback('right', 'short', on_right)

while True:
if pending['prev']:
pending['prev'] = False
print("previous (heavy work is fine here)")
if pending['next']:
pending['next'] = False
print("next (heavy work is fine here)")

time.sleep(0.02) # time-consuming rendering goes here too

Recipes​

Click feedback beep​

Short operations like this are safe inside a callback. The launcher itself uses beep.tone(7000, 50) (7000 Hz for 50 ms):

import beep

def feedback():
beep.tone(7000, 50)

buttons.register_callback('up', 'short', feedback)
buttons.register_callback('down', 'short', feedback)
buttons.register_callback('center', 'short', feedback)

Long press to sleep​

import pm

def on_center_long():
beep.tone(7000, 50)
pm.sleep() # returns "no sleep" while charging

buttons.register_callback('center', 'long', on_center_long)

Simulate a double click​

The module has no double-click detection, so compare two short-press timestamps with time.ticks_ms():

DOUBLE_CLICK_MS = 300
last_click = [0]

def on_center_short():
now = time.ticks_ms()
if time.ticks_diff(now, last_click[0]) < DOUBLE_CLICK_MS:
print("center double click")
last_click[0] = 0 # reset so a triple click is not two double clicks
else:
last_click[0] = now # record the first click

buttons.register_callback('center', 'short', on_center_short)

Complete Example​

Firefly T1 apps live on the SD card under /sd/apps/<app-folder>/ and start from boot.py. The launcher releases its own buttons before entering an app, so an app can safely create its own Button (still only one).

Drop this into /sd/apps/my-light-app/boot.py and it runs: short press up/down cycles the effect, short press center confirms, long press center exits.

from button import Button
import beep
import time

EFFECTS = ['Solid red', 'Green breathing', 'Rainbow fade']
index = 0
running = True

buttons = Button(long_press_threshold=800, debounce_time=30)


def beep_click():
beep.tone(7000, 50)


def on_up():
global index
index = (index - 1) % len(EFFECTS)
beep_click()
print("Previous:", EFFECTS[index])


def on_down():
global index
index = (index + 1) % len(EFFECTS)
beep_click()
print("Next:", EFFECTS[index])


def on_center_short():
beep_click()
print("Confirm:", EFFECTS[index])


def on_center_long():
global running
running = False


buttons.register_callback('up', 'short', on_up)
buttons.register_callback('down', 'short', on_down)
buttons.register_callback('center', 'short', on_center_short)
buttons.register_callback('center', 'long', on_center_long)

while running:
# Put your light effect rendering here
time.sleep(0.05)

buttons.deinit()

Related modules: Power Management (pm) and Buzzer (beep).

Troubleshooting​

SymptomCause / Fix
Buttons do nothing at allMisspelled button name or event type (silently ignored) → check 'up'/'down'/'left'/'right'/'center' and 'short'/'long'
Buttons do nothing at allA second Button instance overwrote the interrupts → keep exactly one, in a module-level variable
Buttons do nothing at alldeinit() was called earlier → construct a new Button()
TypeError when a button firesThe callback takes an argument → make it zero-argument
Short presses occasionally lostThe tap was faster than debounce_time → lower it to 20–30 ms
The device stutters after a callback redrawsTime-consuming work inside the callback → set a flag and do the work in the main loop
The device will not boot normallyA strapping pin was held during power-on / reset → release it and power on again

AI Usage (coming soon)​

Soon you will not have to write code line by line: describe the button behaviour you want in natural language, and the Agent generates a complete program for the Firefly T1 based on the API documented here.

For example, just tell it:

Short press center to switch effects, long press to sleep, with a beep on every press.

It then combines Button, beep and pm into a runnable program and puts it in /sd/apps/ on the SD card.

Agent entry (coming soon)

The link will go here. Once it is live, one click starts your description of the app you want.