Skip to content

The Update Loop

After this page you can animate your app with elapsed-time checks.

The Cyber Fidget firmware runs your app's update() function about 50 times per second. Understanding what happens in each "frame" and how timing works will help you build smooth, responsive apps.


What is this?

The main loop runs continuously. Roughly every 20 milliseconds, the firmware:

  1. Updates hardware (buttons, battery, slider, etc.)
  2. Processes any button events
  3. Calls your app's update() function

Each call to update() is like one frame of a movie -- you draw a complete picture from scratch, then the next frame replaces it.

Like frames in a movie

Each frame is a complete picture drawn from scratch. In this pattern, your code clears the last frame -- you redraw everything every time. That's why you always clear() before drawing.


The clear -> draw -> display cycle

Every frame, your app typically does:

  1. clear() -- Erase the display buffer (or the parts you care about).
  2. draw -- Draw text, shapes, sprites, etc. into the buffer.
  3. display() -- Send the buffer to the physical OLED screen.

The firmware keeps a drawing buffer, a working copy of the screen in memory. Your drawing commands write to it; display() pushes it to the pixels. Until you call display(), the user sees the previous frame.

Why redraw everything?

The OLED is a simple framebuffer display. There's no built-in compositing or layers -- you own the whole 128 x 64 canvas each frame.


millis()-based timing vs delay()

Use millis() for timing. Add these examples into the studio starter where each comment says. The starter already calls display.display() at the end of update().

  • delay(100) - Does nothing in studio apps on the device or in the browser emulator. It does not create a pause. In built-in firmware code it can block the calling task.
  • millis() -- Returns elapsed milliseconds since boot. Check it each frame and act when enough time has passed.
// Insert at the top of the file, below the #include lines
static unsigned long lastFrameTime = 0;
static int currentFrame = 0;

// Insert inside begin(), below setColorsOff();
lastFrameTime = millis();
currentFrame = 0;

// Insert inside update(), just above display.display();
unsigned long frameTime = millis();
if (frameTime - lastFrameTime >= 100) {  // 10 animation steps per second
    lastFrameTime = frameTime;
    currentFrame = (currentFrame + 1) % 8;
}
display.clear();
display.fillCircle(15 + currentFrame * 14, 32, 5);
Full code for this step

This full code is for code name MyApp (create it with App Name "My App"); if your app has another code name, change MyApp and myApp to yours.

In the starter, nullptr means a pointer has no object. * in a declaration marks a pointer (an address), and before a pointer reads its object. & in a type refers to an existing object; before a value it gives its address. const means the code cannot change the value through that declaration.

MyApp.cpp
#include "MyApp.h"
#include "globals.h"
#include "HAL.h"
#include "MenuManager.h"

static unsigned long lastFrameTime = 0;
static int currentFrame = 0;
MyApp myApp(HAL::buttonManager());
MyApp* MyApp::instance = nullptr;

MyApp::MyApp(ButtonManager& btnMgr) :
    buttonManager(btnMgr), display(HAL::displayProxy()), audio(HAL::audioManager()) { instance = this; }

// begin() runs once when your app opens from the menu.
// Set things up here: hook up the buttons and start with the lights off.
void MyApp::begin() {
    registerButtonCallbacks();
    setColorsOff();
    lastFrameTime = millis();
    currentFrame = 0;
}

// update() runs about 50 times a second while your app is open.
// Clear the screen, draw what you want, then show it.
// The case hides about 8 pixels at each screen corner, so keep text and
// important pixels out of those corners.
void MyApp::update() {
    display.clear();
    display.setTextAlignment(TEXT_ALIGN_CENTER);
    display.setFont(ArialMT_Plain_16);
    display.drawString(64, 24, "MyApp");
    unsigned long frameTime = millis();
    if (frameTime - lastFrameTime >= 100) {  // 10 animation steps per second
        lastFrameTime = frameTime;
        currentFrame = (currentFrame + 1) % 8;
    }
    display.clear();
    display.fillCircle(15 + currentFrame * 14, 32, 5);
    display.display();
}

// end() runs when your app closes. Let go of the buttons and turn the
// lights off (if your app plays sounds, call audio.stopTone() here too).
void MyApp::end() {
    unregisterButtonCallbacks();
    setColorsOff();
}

// The bottom-left button closes your app and goes back to the menu.
void MyApp::onButtonBackPressed(const ButtonEvent& event) {
    if (event.eventType == ButtonEvent_Released) {
        instance->end();
        MenuManager::instance().returnToMenu();
    }
}

void MyApp::registerButtonCallbacks() {
    buttonManager.registerCallback(button_BottomLeftIndex, onButtonBackPressed);
}

void MyApp::unregisterButtonCallbacks() {
    buttonManager.unregisterCallback(button_BottomLeftIndex);
}

Avoid delay() in apps

Do not use delay() to schedule an app action. Compare millis() with a saved time, then return from update() so other work can run.


Code example: frame-based animation

// Insert at the top of the file, below the #include lines
static unsigned long lastStep = 0;
static int dropY = 8;

// Insert inside begin(), below setColorsOff();
lastStep = millis();
dropY = 8;

// Insert inside update(), just above display.display();
unsigned long frameTime = millis();
if (frameTime - lastStep >= 100) {
    lastStep = frameTime;
    dropY += 4;
    if (dropY > 56) {
        dropY = 8;
    }
}
// Draw on every update, even between movement steps.
display.clear();
for (int column = 0; column < 6; ++column) {
    display.fillRect(14 + column * 18, dropY, 3, 5);
}
Full code for this step

This full code is for code name MyApp (create it with App Name "My App"); if your app has another code name, change MyApp and myApp to yours.

MyApp.cpp
#include "MyApp.h"
#include "globals.h"
#include "HAL.h"
#include "MenuManager.h"

static unsigned long lastStep = 0;
static int dropY = 8;
MyApp myApp(HAL::buttonManager());
MyApp* MyApp::instance = nullptr;

MyApp::MyApp(ButtonManager& btnMgr) :
    buttonManager(btnMgr), display(HAL::displayProxy()), audio(HAL::audioManager()) { instance = this; }

// begin() runs once when your app opens from the menu.
// Set things up here: hook up the buttons and start with the lights off.
void MyApp::begin() {
    registerButtonCallbacks();
    setColorsOff();
    lastStep = millis();
    dropY = 8;
}

// update() runs about 50 times a second while your app is open.
// Clear the screen, draw what you want, then show it.
// The case hides about 8 pixels at each screen corner, so keep text and
// important pixels out of those corners.
void MyApp::update() {
    display.clear();
    display.setTextAlignment(TEXT_ALIGN_CENTER);
    display.setFont(ArialMT_Plain_16);
    display.drawString(64, 24, "MyApp");
    unsigned long frameTime = millis();
    if (frameTime - lastStep >= 100) {
        lastStep = frameTime;
        dropY += 4;
        if (dropY > 56) {
            dropY = 8;
        }
    }
    // Draw on every update, even between movement steps.
    display.clear();
    for (int column = 0; column < 6; ++column) {
        display.fillRect(14 + column * 18, dropY, 3, 5);
    }
    display.display();
}

// end() runs when your app closes. Let go of the buttons and turn the
// lights off (if your app plays sounds, call audio.stopTone() here too).
void MyApp::end() {
    unregisterButtonCallbacks();
    setColorsOff();
}

// The bottom-left button closes your app and goes back to the menu.
void MyApp::onButtonBackPressed(const ButtonEvent& event) {
    if (event.eventType == ButtonEvent_Released) {
        instance->end();
        MenuManager::instance().returnToMenu();
    }
}

void MyApp::registerButtonCallbacks() {
    buttonManager.registerCallback(button_BottomLeftIndex, onButtonBackPressed);
}

void MyApp::unregisterButtonCallbacks() {
    buttonManager.unregisterCallback(button_BottomLeftIndex);
}

You can update logic at a different rate than the draw rate. For example, change the 100 in the elapsed-time check to 30 to use a 30 ms movement threshold, while drawing on every update. Movement happens on the first update after that threshold, so its timing is approximate.


Functions on this page

Call What it does
unsigned long millis()
Example: unsigned long now = millis();
Read elapsed time in ms; use unsigned subtraction to time actions across clock wraparound.
unsigned long micros()
Example: unsigned long nowUs = micros();
Read elapsed microseconds; both targets have only 1000-microsecond resolution.
void delay(unsigned long)
Example: delay(10);
Does nothing on the device or in the app emulator - use millis() timing.
void delayMicroseconds(unsigned int)
Example: delayMicroseconds(100);
Does nothing on the device or in the app emulator - use millis() timing.
long random(long maxExclusive)
long random(long minInclusive, long maxExclusive)

Example: int roll = random(1, 7);
Choose an integer from the first bound inclusive to the second exclusive; one argument starts at 0.
void randomSeed(unsigned long)
Example: randomSeed(42);
Does nothing in studio apps, on the device and in the browser emulator.
long map(long x, long in_min, long in_max, long out_min, long out_max)
Example: long brightness = map(value, 0, 100, 0, 255);
Rescale an integer range; does not clamp values outside the range.
template <typename T> T constrain(T x, T lo, T hi)
Example: long bounded = constrain(value, 0L, 100L);
Clamp a value between inclusive bounds; use long integers on both targets.
template <typename T> T min(T a, T b)
Example: int smaller = min(a, b);
Choose the smaller of two values of the same type.
template <typename T> T max(T a, T b)
Example: int larger = max(a, b);
Choose the larger of two values of the same type.
float radians(float deg)
Example: float angle = radians(90.0f);
Convert degrees to radians (one full turn is about 6.283 radians).
float degrees(float rad)
Example: float angle = degrees(1.0f);
Convert radians to degrees (360 degrees is one full turn).
unsigned long millis_NOW
Example: millis_NOW
The time in ms when this frame started; read it instead of calling millis() repeatedly.

Framework detail: TASK_20MS and HAL::loopHardware()

Advanced: how the firmware schedules updates

You do not need these details to build apps in the studio. They describe the firmware internals for readers writing an app by hand and building it into the firmware.

Inside the firmware, the main loop uses a 20 ms task interval (TASK_20MS = 20). This firmware-source excerpt is not code for a studio app:

// In AppManager::loop(), with other firmware work between these lines:
HAL::loopHardware();

if ((millis_NOW - millis_APP_TASK_20MS) >= TASK_20MS) {
    millis_APP_TASK_20MS = millis_NOW;
    runActiveApp();
}

HAL::loopHardware() runs every main loop iteration and handles:

  • Button state polling (s_buttonManager.update())
  • Slider reading (every 20 ms)
  • Accelerometer (every 50 ms)
  • Battery (every 200 ms)
  • RGB strip updates

Your app's update() is only called when the 20 ms timer fires, so about 50 updates per second is the target. Slow work can make updates arrive later; keep each call short. Do not call HAL::loopHardware() from a studio app.