KryonOSDocs
Hardware & Peripherals

Multi-Board Hardware HAL APIs

Board-specific APIs for LilyGO T-Deck Plus, QWERTY keyboard, trackball, and multi-board HAL.

19. Hardware & Device-Specific APIs (LilyGO T-Deck Plus & Multi-Board HAL)

KryonOS provides direct JavaScript APIs for hardware-equipped handheld devices like the LilyGO T-Deck Plus, Cardputer, and multi-board setups. These APIs abstract physical input controls, audio synthesis, and device telemetry while preserving full cross-device compatibility.

19.1 Trackball API (Trackball / System.trackball)

The Trackball API provides high-precision access to the 5-way physical rolling trackball on devices such as the LilyGO T-Deck Plus.

MethodParametersReturn TypeDescription
Trackball.getState()NoneObjectReturns snapshot { x, y, dx, dy, up, down, left, right, pressed, clicked }. Delta values auto-clear on read.
Trackball.getDelta()NoneObjectReturns relative motion { dx, dy } since last call and resets internal delta counters to 0.
Trackball.isClicked()NoneBooleanReturns true if a full press-and-release click cycle occurred since the last call.
Trackball.isPressed()NoneBooleanReturns true if the center trackball push switch is currently held down.
Trackball.getRawCounts()NoneObjectReturns raw edge pulse counts { up, down, left, right }.
Trackball.reset()NoneundefinedClears all accumulated deltas, edge pulse counters, and click flags.

Example: Virtual Cursor & Game Loop

// Game Loop with Trackball Navigation
var playerX = 160;
var playerY = 120;

while (running) {
    if (typeof Trackball !== "undefined") {
        var delta = Trackball.getDelta();
        playerX += delta.dx * 2;
        playerY += delta.dy * 2;

        if (Trackball.isClicked()) {
            fireLaser();
        }
    }
    System.delay(16);
}

19.2 Physical Keyboard API (Keyboard / System.keyboard)

The Keyboard API provides non-blocking access to the hardware QWERTY keyboard (e.g., T-Deck Plus C3 slave keyboard or Cardputer matrix).

MethodParametersReturn TypeDescription
Keyboard.getKey()NoneString | nullNon-blocking dequeue of the next pressed key character (e.g. "a", "\n", "\b", "\x1b"). Returns null if no key pressed.
Keyboard.getEvent()NoneObject | nullDequeues the next key event with metadata: { code: Number, char: String, name: String } (name: "BACKSPACE", "ENTER", "UP", "DOWN", "LEFT", "RIGHT", "TAB", "ESC", "SPACE", "CHAR").
Keyboard.isPressed(asciiCode)asciiCode: NumberBooleanChecks if a specific ASCII key is currently depressed.
Keyboard.getModifiers()NoneObjectReturns active modifier status { shift: Boolean, fn: Boolean, ctrl: Boolean, alt: Boolean }.
Keyboard.setBacklightLevel(pct)pct: Number (0-100)undefinedSets keyboard backlight illumination brightness percentage (0 = OFF, 100 = MAX).
Keyboard.getBacklightLevel()NoneNumberReturns current backlight brightness percentage.
Keyboard.clear()NoneundefinedFlushes all residual buffered keystrokes from the FIFO queue.

Example: Reading Live Key Stream

var key = Keyboard.getKey();
if (key !== null) {
    if (key === "\x1b") { // ESC
        running = false;
    } else if (key === "\n") { // Enter
        submitInput();
    } else {
        buffer += key;
    }
}

19.3 I2S Audio & Synthesizer API (Speaker / Audio / System.speaker)

The Audio API drives the onboard I2S audio amplifier (e.g., MAX98357A on LilyGO T-Deck Plus) through an asynchronous Core 0 FreeRTOS worker task. It supports procedural synthesis, preset sound effects, and streaming WAV playback with logarithmic perceptual volume scaling ($V_{\text{perceived}} = (\text{vol}/100)^2$).

Supported Audio Formats (MP3 & WAV / RIFF)

  • MPEG-1 / MPEG-2 Audio Layer III (MP3):
    • Powered by embedded minimp3 fixed-point decoder on Core 0.
    • Supports all standard bitrates (32 kbps to 320 kbps) and VBR (Variable Bitrate).
    • Sample rates from 8 kHz to 48 kHz.
    • Automatic ID3v2 header and metadata bypass (syncsafe tag parsing) preventing noise/buzz from embedded album artwork.
    • Dedicated 32 KB PSRAM stream ring buffer preventing audio starvation during background SD SPI reads.
  • Container / Format: Microsoft RIFF WAV, uncompressed Linear PCM (0x0001 or WAVEFORMATEXTENSIBLE 0xFFFE).
  • Channels: Mono (1 channel) or Stereo (2 channels). Mono files are automatically downmixed and duplicated into both I2S left and right DMA slots (L = R), ensuring compatibility with hardware SD_MODE pin straps.
  • Bit Depth: 8-bit unsigned PCM and 16-bit signed PCM (Little-Endian).
  • Sample Rate: 8,000 Hz to 48,000 Hz (e.g., 8 kHz, 11.025 kHz, 16 kHz, 22.05 kHz, 24 kHz, 32 kHz, 44.1 kHz, 48 kHz). The hardware I2S master clock dynamically reconfigures to match the file's sample rate.
  • Subchunk & Metadata Handling: Automatically navigates fmt and data subchunks, skipping broadcast audio headers (bext), padding blocks (JUNK), and trailing tags (LIST, INFO, ID3) to eliminate digital static/screeching.
  • PSRAM Streaming Cache: Files up to 6 MB on Internal Flash (/local) or MicroSD (/sd) are automatically buffered in PSRAM on playback, isolating the stream from the shared SPI bus to prevent display frame buffer collisions.
MethodParametersReturn TypeDescription
Speaker.playMp3(path)path: StringBooleanStarts asynchronous streaming MP3 playback from LittleFS or SD Card (e.g. "/sd/music/song.mp3"). Decodes in background on Core 0. Returns true if playback initiated successfully.
Speaker.play(path)path: StringBooleanUniversal audio player. Automatically detects format by reading file magic bytes (RIFF vs ID3/sync word 0xFFE0) and delegates to the appropriate native WAV or MP3 decoder.
Speaker.playWav(path)path: StringBooleanStarts asynchronous streaming playback of a WAV file from LittleFS or SD Card (e.g. "/local/system/sounds/boot.wav"). Returns true if playback initiated successfully.
Speaker.seek(positionMs)positionMs: NumberBooleanSeeks playback to the specified millisecond offset. Supported for both WAV and MP3 streaming.
Speaker.playTone(freq, durMs, [vol])freq: Number (Hz), durMs: Number, vol: Number (0-100, optional)BooleanSynthesizes a clean sine wave tone for durMs milliseconds at the given relative volume. Master volume is preserved.
Speaker.playMelody(notes)notes: Array of { f: Hz, d: ms }undefinedProcedurally plays an array of musical notes sequentially.
Speaker.playBeep(preset)preset: StringBooleanPlays built-in preset sound effects: "click", "beep", "alert", "error", or "chime".
Speaker.setVolume(volumePercent)volumePercent: Number (0-100)undefinedAdjusts master hardware audio volume using logarithmic perceptual scaling.
Speaker.getVolume()NoneNumberReturns master hardware volume (0-100).
Speaker.mute(m)m: BooleanundefinedMutes or unmutes audio output with smooth zero-crossing ramp down.
Speaker.isMuted()NoneBooleanReturns true if audio is currently muted.
Speaker.stop()NoneundefinedHalts active playback with software ramp-down to prevent speaker pop, waiting cleanly for Core 0 DMA acknowledgment.
Speaker.pause()NoneundefinedPauses active audio streaming.
Speaker.resume()NoneundefinedResumes paused audio streaming.
Speaker.isPlaying()NoneBooleanReturns true if audio is actively playing or streaming.
Speaker.getDuration()NoneNumberReturns total audio duration in seconds from hardware chunk header.
Speaker.getPosition()NoneNumberReturns live playback position in seconds from hardware DMA stream.

Audio API Aliases: Audio is an identical global alias for Speaker (e.g. Audio.playMp3("/sd/song.mp3") or System.speaker.playMp3(...)).

Example: Sound Effects, Beeps & WAV Playback

// Adjust master volume (perceptually scaled)
Speaker.setVolume(75);

// Built-in presets for user feedback
Speaker.playBeep("click"); // Tactile button click (1200 Hz, 15ms)
Speaker.playBeep("chime"); // Success confirmation chime (1046 Hz, 100ms)
Speaker.playBeep("error"); // Low-pitch error buzz (220 Hz, 150ms)

// Custom procedural tone synthesis
Speaker.playTone(440, 200, 80); // A4 note for 200ms at 80% relative volume

// Background asynchronous WAV streaming from MicroSD or Flash
Speaker.playWav("/sd/music/track1.wav");

// Touch / UI Event Best Practice:
// Use touch edge detection to prevent re-triggering playWav on every frame
var lastTouched = false;
function onLoop() {
    var touch = System.getTouch();
    if (touch && touch.touched) {
        if (!lastTouched) {
            // Only trigger on initial touch press
            if (!Speaker.isPlaying()) {
                Speaker.playWav("/local/sounds/effect.wav");
            }
            lastTouched = true;
        }
    } else {
        lastTouched = false;
    }
}

19.4 Device Telemetry & Capability API (Device / System.device)

The Device API enables applications to query board capabilities, identify hardware models, monitor battery health, and control screen brightness.

MethodParametersReturn TypeDescription
Device.getName()NoneStringReturns human-readable board target name (e.g. "T-Deck Plus", "T-Deck", "M5Stack Cardputer"). Dynamically identifies T-Deck Plus via built-in GNSS hardware detection.
Device.hasTrackball()NoneBooleanReturns true if the board features a physical trackball.
Device.hasKeyboard()NoneBooleanReturns true if the board features a physical keyboard.
Device.hasSpeaker()NoneBooleanReturns true if the board has an onboard speaker/I2S amplifier.
Device.hasTouch()NoneBooleanReturns true if touchscreen hardware is available.
Device.hasBattery()NoneBooleanReturns true if battery telemetry circuitry is present.
Device.getBatteryPercent()NoneNumberReturns current state-of-charge battery percentage (0-100).
Device.getBatteryVoltage()NoneNumberReturns measured battery cell voltage in Volts (e.g. 3.85).
Device.isCharging()NoneBooleanReturns true if external USB charger is connected.
Device.getChargeTimeRemaining()NoneNumberEstimated minutes until battery is fully charged (0 if discharging).
Device.getDischargeTimeRemaining()NoneNumberEstimated minutes of operational battery life remaining.
Device.setBrightness(pct)pct: Number (10-100)undefinedAdjusts LCD display backlight brightness.
Device.getBrightness()NoneNumberReturns current LCD backlight brightness percentage.

Example: Adaptive UI Based on Hardware Capabilities

if (Device.hasKeyboard()) {
    System.drawString("Press ENTER to start", 40, 180, 2);
} else if (Device.hasTouch()) {
    System.drawString("Tap anywhere to start", 40, 180, 2);
}