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.
| Method | Parameters | Return Type | Description |
|---|---|---|---|
Trackball.getState() | None | Object | Returns snapshot { x, y, dx, dy, up, down, left, right, pressed, clicked }. Delta values auto-clear on read. |
Trackball.getDelta() | None | Object | Returns relative motion { dx, dy } since last call and resets internal delta counters to 0. |
Trackball.isClicked() | None | Boolean | Returns true if a full press-and-release click cycle occurred since the last call. |
Trackball.isPressed() | None | Boolean | Returns true if the center trackball push switch is currently held down. |
Trackball.getRawCounts() | None | Object | Returns raw edge pulse counts { up, down, left, right }. |
Trackball.reset() | None | undefined | Clears 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).
| Method | Parameters | Return Type | Description |
|---|---|---|---|
Keyboard.getKey() | None | String | null | Non-blocking dequeue of the next pressed key character (e.g. "a", "\n", "\b", "\x1b"). Returns null if no key pressed. |
Keyboard.getEvent() | None | Object | null | Dequeues 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: Number | Boolean | Checks if a specific ASCII key is currently depressed. |
Keyboard.getModifiers() | None | Object | Returns active modifier status { shift: Boolean, fn: Boolean, ctrl: Boolean, alt: Boolean }. |
Keyboard.setBacklightLevel(pct) | pct: Number (0-100) | undefined | Sets keyboard backlight illumination brightness percentage (0 = OFF, 100 = MAX). |
Keyboard.getBacklightLevel() | None | Number | Returns current backlight brightness percentage. |
Keyboard.clear() | None | undefined | Flushes 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
minimp3fixed-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.
- Powered by embedded
- Container / Format: Microsoft RIFF WAV, uncompressed Linear PCM (
0x0001orWAVEFORMATEXTENSIBLE 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 hardwareSD_MODEpin 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
fmtanddatasubchunks, 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.
| Method | Parameters | Return Type | Description |
|---|---|---|---|
Speaker.playMp3(path) | path: String | Boolean | Starts 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: String | Boolean | Universal 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: String | Boolean | Starts 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: Number | Boolean | Seeks 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) | Boolean | Synthesizes 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 } | undefined | Procedurally plays an array of musical notes sequentially. |
Speaker.playBeep(preset) | preset: String | Boolean | Plays built-in preset sound effects: "click", "beep", "alert", "error", or "chime". |
Speaker.setVolume(volumePercent) | volumePercent: Number (0-100) | undefined | Adjusts master hardware audio volume using logarithmic perceptual scaling. |
Speaker.getVolume() | None | Number | Returns master hardware volume (0-100). |
Speaker.mute(m) | m: Boolean | undefined | Mutes or unmutes audio output with smooth zero-crossing ramp down. |
Speaker.isMuted() | None | Boolean | Returns true if audio is currently muted. |
Speaker.stop() | None | undefined | Halts active playback with software ramp-down to prevent speaker pop, waiting cleanly for Core 0 DMA acknowledgment. |
Speaker.pause() | None | undefined | Pauses active audio streaming. |
Speaker.resume() | None | undefined | Resumes paused audio streaming. |
Speaker.isPlaying() | None | Boolean | Returns true if audio is actively playing or streaming. |
Speaker.getDuration() | None | Number | Returns total audio duration in seconds from hardware chunk header. |
Speaker.getPosition() | None | Number | Returns 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.
| Method | Parameters | Return Type | Description |
|---|---|---|---|
Device.getName() | None | String | Returns 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() | None | Boolean | Returns true if the board features a physical trackball. |
Device.hasKeyboard() | None | Boolean | Returns true if the board features a physical keyboard. |
Device.hasSpeaker() | None | Boolean | Returns true if the board has an onboard speaker/I2S amplifier. |
Device.hasTouch() | None | Boolean | Returns true if touchscreen hardware is available. |
Device.hasBattery() | None | Boolean | Returns true if battery telemetry circuitry is present. |
Device.getBatteryPercent() | None | Number | Returns current state-of-charge battery percentage (0-100). |
Device.getBatteryVoltage() | None | Number | Returns measured battery cell voltage in Volts (e.g. 3.85). |
Device.isCharging() | None | Boolean | Returns true if external USB charger is connected. |
Device.getChargeTimeRemaining() | None | Number | Estimated minutes until battery is fully charged (0 if discharging). |
Device.getDischargeTimeRemaining() | None | Number | Estimated minutes of operational battery life remaining. |
Device.setBrightness(pct) | pct: Number (10-100) | undefined | Adjusts LCD display backlight brightness. |
Device.getBrightness() | None | Number | Returns 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);
}