ESP BOX#
Esp-Box#
The ESP32-S3-BOX and ESP32-S3-BOX-3 are development boards for the ESP32-S3 module. They feature a nice touchscreen display, a speaker, microphones, and expansion headers.
The espp::EspBox component provides a singleton hardware abstraction for initializing the touch, display, and audio subsystems, as well as automatically determining which version of the Box it’s running on.
API Reference#
Header File#
Classes#
-
class EspBox : public espp::BaseComponent#
The EspBox class provides an interface to the ESP32-S3-BOX and ESP32-S3-BOX-3 development boards.
The class provides access to the following features:
Touchpad
Interrupts
Buttons (boot and mute)
I2C
IMU (Inertial Measurement Unit), 6-axis ICM42607
The class is a singleton and can be accessed using the get() method.
Example#
espp::EspBox &box = espp::EspBox::get(); box.set_log_level(espp::Logger::Verbosity::INFO); logger.info("Running on {}", box.box_type()); // load the audio file (wav file bundled in memory), to set the audio system // up at its sample rate size_t wav_size = 0; size_t wav_sample_rate = 0; if (!load_audio(wav_size, wav_sample_rate)) { logger.error("Failed to load audio file!"); return; } logger.info("Loaded {} bytes of audio at {} Hz", wav_size, wav_sample_rate); // initialize the audio system: playback through the ES8311 and the speaker, // and recording from the dual microphone array through the ES7210, full // duplex on one I2S bus (so the microphones record at the speaker's rate) auto audio_config = box.default_audio_config(); audio_config.sample_rate = static_cast<uint32_t>(wav_sample_rate); if (!box.initialize_audio(audio_config)) { logger.error("Failed to initialize audio!"); return; } // initialize the LCD if (!box.initialize_lcd()) { logger.error("Failed to initialize LCD!"); return; } // set the pixel buffer to be 50 lines high static constexpr size_t pixel_buffer_size = box.lcd_width() * 50; // initialize the LVGL display for the esp-box if (!box.initialize_display(pixel_buffer_size)) { logger.error("Failed to initialize display!"); return; } // make the filter we'll use for the IMU to compute the orientation static constexpr float angle_noise = 0.001f; static constexpr float rate_noise = 0.1f; static espp::KalmanFilter<2> kf; kf.set_process_noise(rate_noise); kf.set_measurement_noise(angle_noise); static constexpr float beta = 0.1f; // higher = more accelerometer, lower = more gyro static espp::MadgwickFilter f(beta); using Imu = espp::EspBox::Imu; auto kalman_filter_fn = [](float dt, const Imu::Value &accel, const Imu::Value &gyro) -> Imu::Value { // Apply Kalman filter float accelRoll = atan2(accel.y, accel.z); float accelPitch = atan2(-accel.x, sqrt(accel.y * accel.y + accel.z * accel.z)); kf.predict({espp::deg_to_rad(gyro.x), espp::deg_to_rad(gyro.y)}, dt); kf.update({accelRoll, accelPitch}); float roll, pitch; std::tie(roll, pitch) = kf.get_state(); // return the computed orientation Imu::Value orientation{}; orientation.roll = roll; orientation.pitch = pitch; orientation.yaw = 0.0f; return orientation; }; auto madgwick_filter_fn = [](float dt, const Imu::Value &accel, const Imu::Value &gyro) -> Imu::Value { // Apply Madgwick filter f.update(dt, accel.x, accel.y, accel.z, espp::deg_to_rad(gyro.x), espp::deg_to_rad(gyro.y), espp::deg_to_rad(gyro.z)); float roll, pitch, yaw; f.get_euler(roll, pitch, yaw); // return the computed orientation Imu::Value orientation{}; orientation.roll = espp::deg_to_rad(roll); orientation.pitch = espp::deg_to_rad(pitch); orientation.yaw = espp::deg_to_rad(yaw); return orientation; }; // initialize the IMU if (!box.initialize_imu(kalman_filter_fn)) { logger.error("Failed to initialize IMU!"); return; } // create the GUI: builds the UI (labels, buttons, gravity lines, circle // layer) and starts the task which updates LVGL. All of its public methods // are thread-safe, so the touch callback and IMU task below can call them // directly. static Gui gui({.log_level = espp::Logger::Verbosity::INFO}); static const std::string instructions = fmt::format("Touch the screen to draw!\nPress the home button or the {} button to clear " "circles.\nPress the {} button to rotate the display.\nThe IMU and Audio " "tabs show the other subsystems.", LV_SYMBOL_TRASH, LV_SYMBOL_REFRESH); gui.set_label_text(instructions); // initialize the touchpad; each touch draws a circle (and plays a click // sound), while the home button clears the circles auto touch_callback = [&](const auto &touch) { // NOTE: since we're directly using the touchpad data, and not using the // TouchpadInput + LVGL, we'll need to ensure the touchpad data is // converted into proper screen coordinates instead of simply using the // raw values. static auto previous_touchpad_data = box.touchpad_convert(touch); auto touchpad_data = box.touchpad_convert(touch); if (touchpad_data != previous_touchpad_data) { logger.info("Touch: {}", touchpad_data); previous_touchpad_data = touchpad_data; // if the home button is pressed, clear the circles if (touchpad_data.btn_state) { gui.clear_circles(); } // if there is a touch point on the Draw tab, draw a circle and play a // click sound (touches on the other tabs go to their widgets) if (touchpad_data.num_touch_points > 0 && gui.draw_page_active()) { play_click(box); gui.draw_circle(touchpad_data.x, touchpad_data.y, 10); } } }; // NOTE: this example raises the BSP interrupt-task stack size via // sdkconfig.defaults (CONFIG_ESP_BOX_INTERRUPT_STACK_SIZE=8192); the // touch controller is read from that task and its error-logging path // needs more than the 4 KB BSP default. See the example README. if (!box.initialize_touch(touch_callback)) { logger.error("Failed to initialize touchpad!"); return; } // unmute the audio and set the volume to 60% box.mute(false); box.volume(60.0f); // set the display brightness to be 75% box.brightness(75.0f); // Record from the microphones (the ES7210 shares the I2S bus with the // speaker in full duplex, so recording runs at the speaker's sample rate) // and buffer the recorded stereo frames; the recording auto-stops when the // buffer is full and the main loop notices and updates the GUI auto mic_callback = [](const uint8_t *data, size_t num_bytes) { if (!recording) { return; } size_t offset = recording_len; size_t to_copy = std::min(num_bytes, recording_capacity - offset); if (to_copy > 0) { memcpy(recording_buffer + offset, data, to_copy); recording_last_us = esp_timer_get_time(); recording_len = offset + to_copy; } if (recording_len >= recording_capacity) { recording = false; } }; bool have_mic = box.start_audio_recording(mic_callback); if (!have_mic) { gui.set_audio_status("Mic unavailable (see log)"); } if (have_mic) { // start at a modest microphone gain: the BSP default is fairly hot and // can clip on close / loud sound. Nudge it up with the mic + button if // recordings are too quiet. box.microphone_volume(40.0f); // allocate the recording buffer (16-bit interleaved stereo at the // current sample rate): prefer PSRAM, fall back to a couple of seconds // in internal RAM size_t bytes_per_second = box.audio_sample_rate() * 2 * sizeof(int16_t); recording_capacity = MAX_RECORDING_SECONDS * bytes_per_second; recording_buffer = static_cast<uint8_t *>( heap_caps_malloc(recording_capacity, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); if (recording_buffer == nullptr) { recording_capacity = FALLBACK_RECORDING_SECONDS * bytes_per_second; recording_buffer = static_cast<uint8_t *>(heap_caps_malloc(recording_capacity, MALLOC_CAP_8BIT)); } if (recording_buffer == nullptr) { logger.warn("Could not allocate a recording buffer; recording disabled"); gui.set_audio_status("No recording buffer"); recording_capacity = 0; } else { logger.info("Recording buffer: {} KB ({} s at {} Hz stereo)", recording_capacity / 1024, recording_capacity / bytes_per_second, box.audio_sample_rate()); } } else { logger.warn("Could not initialize the microphone!"); } // The record button toggles recording; the play button toggles playback of // the recording (streamed to the speaker by the main loop) gui.set_record_callback([&]() { if (!have_mic || recording_capacity == 0) { logger.warn("Recording unavailable (no microphone / no buffer)"); gui.set_audio_status("Mic unavailable (see log)"); return; } if (recording) { recording = false; // the main loop notices and logs the summary } else { playing = false; gui.set_play_active(false); recording_len = 0; recording_start_us = esp_timer_get_time(); recording_last_us = recording_start_us.load(); recording = true; gui.set_record_active(true); gui.set_audio_status("Recording..."); } }); gui.set_play_callback([&]() { if (playing) { playing = false; gui.set_play_active(false); gui.set_audio_status("Playback stopped"); } else if (recording_len > 0) { recording = false; playing = true; gui.set_play_active(true); gui.set_audio_status("Playing..."); } else { logger.info("Nothing recorded yet; press the record button first"); gui.set_audio_status("Nothing recorded yet"); } }); // make a task to read out the IMU data and update the GUI with it espp::Task imu_task( {.callback = [&](std::mutex &m, std::condition_variable &cv) -> bool { // sleep first in case we don't get IMU data and need to exit early { std::unique_lock<std::mutex> lock(m); cv.wait_for(lock, 10ms); } static auto &box = espp::EspBox::get(); static auto imu = box.imu(); auto now = esp_timer_get_time(); // time in microseconds static auto t0 = now; auto t1 = now; float dt = (t1 - t0) / 1'000'000.0f; // convert us to s t0 = t1; std::error_code ec; // update the imu data if (!imu->update(dt, ec)) { return false; } // get accel auto accel = imu->get_accelerometer(); auto gyro = imu->get_gyroscope(); auto temp = imu->get_temperature(); auto orientation = imu->get_orientation(); auto gravity_vector = imu->get_gravity_vector(); auto box_type = box.box_type(); if (box_type == espp::EspBox::BoxType::BOX) { std::swap(gravity_vector.x, gravity_vector.y); gravity_vector.y = -gravity_vector.y; } std::string text; text += fmt::format("Accel: {:02.2f} {:02.2f} {:02.2f}\n", accel.x, accel.y, accel.z); text += fmt::format("Gyro: {:03.2f} {:03.2f} {:03.2f}\n", espp::deg_to_rad(gyro.x), espp::deg_to_rad(gyro.y), espp::deg_to_rad(gyro.z)); text += fmt::format("Angle: {:03.2f} {:03.2f}\n", espp::rad_to_deg(orientation.roll), espp::rad_to_deg(orientation.pitch)); text += fmt::format("Temp: {:02.1f} C\n", temp); // Now show the madgwick filter's estimate of "down" auto madgwick_orientation = madgwick_filter_fn(dt, accel, gyro); float roll = madgwick_orientation.roll; float pitch = madgwick_orientation.pitch; float vx = sin(pitch); float vy = -cos(pitch) * sin(roll); if (box_type == espp::EspBox::BoxType::BOX) { std::swap(vx, vy); vy = -vy; } // update the GUI with the new data; the Gui handles remapping the // vectors for the current display rotation gui.set_imu_text(text); gui.set_kalman_down(gravity_vector.x, gravity_vector.y); gui.set_madgwick_down(vx, vy); return false; }, .task_config = { .name = "IMU", .stack_size_bytes = 6 * 1024, .priority = 10, .core_id = 0, }}); imu_task.start(); // Main loop: stream any active playback to the speaker and notice when a // recording stops (either button press or the buffer filling up) size_t play_offset = 0; bool was_recording = false; while (true) { // feed the active playback in chunks, advancing by however much the // speaker's stream buffer accepted if (playing) { size_t len = recording_len; if (play_offset >= len) { playing = false; play_offset = 0; gui.set_play_active(false); gui.set_audio_status("Playback done"); logger.info("Playback done"); } else { play_offset += box.play_audio(recording_buffer + play_offset, std::min<size_t>(len - play_offset, 16384)); } } else { play_offset = 0; } // notice when the recording stopped (button press or buffer full) bool now_recording = recording; if (was_recording && !now_recording) { gui.set_record_active(false); gui.set_audio_status(fmt::format("Recorded {:.1f}s ({} plays)", static_cast<float>(recording_len) / (box.audio_sample_rate() * 2 * sizeof(int16_t)), LV_SYMBOL_PLAY)); // report the measured capture rate: stereo frames recorded over the // wall clock they took to arrive should match the nominal sample rate size_t num_frames = recording_len / (2 * sizeof(int16_t)); float elapsed_s = static_cast<float>(recording_last_us - recording_start_us) / 1e6f; float effective_hz = elapsed_s > 0.0f ? num_frames / elapsed_s : 0.0f; // Post-process the recording for playback on the box's MONO speaker: the // ES7210 records 16-bit interleaved stereo (mic 1 -> left slot, mic 2 -> // right), but the speaker only plays one I2S slot, so audio captured on // the other slot would be inaudible. Downmix each L/R frame to the // average and write it to BOTH slots so the mono speaker always plays // it. Also report the peak amplitude per channel: a peak near 0 means // the microphones captured silence (a codec / wiring problem), while a // healthy peak means capture is fine. auto *samples = reinterpret_cast<int16_t *>(recording_buffer); int16_t peak_left = 0, peak_right = 0; for (size_t i = 0; i < num_frames; i++) { int16_t l = samples[2 * i]; int16_t r = samples[2 * i + 1]; peak_left = std::max<int16_t>(peak_left, static_cast<int16_t>(std::abs(l))); peak_right = std::max<int16_t>(peak_right, static_cast<int16_t>(std::abs(r))); int16_t mono = static_cast<int16_t>((static_cast<int32_t>(l) + r) / 2); samples[2 * i] = mono; samples[2 * i + 1] = mono; } logger.info("Recorded {} frames in {:.2f} s (~{:.0f} Hz effective, {} Hz nominal); " "peak L={} R={} (of 32767 - near 0 means the mics captured silence)", num_frames, elapsed_s, effective_hz, box.audio_sample_rate(), peak_left, peak_right); } was_recording = now_recording; std::this_thread::sleep_for(50ms); }
Public Types
-
enum class BoxType#
The type of the box.
Values:
-
enumerator UNKNOWN#
unknown box
-
enumerator BOX#
ESP32-S3-BOX.
-
enumerator BOX3#
ESP32-S3-BOX-3.
-
enumerator UNKNOWN#
-
using button_callback_t = espp::Interrupt::event_callback_fn#
Alias for the button callback function.
-
using Pixel = lv_color16_t#
Alias for the pixel type used by the ESP-Box display.
-
using TouchpadData = espp::TouchpadData#
Alias for the touchpad data used by the ESP-Box touchpad.
-
using touch_callback_t = std::function<void(const TouchpadData&)>#
Alias for the touch callback when touch events are received.
-
using AudioConfig = espp::Audio::AppConfig#
How initialize_audio() sets the audio system up: the application’s side of espp::Audio (the board’s wiring is filled in by initialize_audio()). Start from default_audio_config() to keep this board’s defaults.
sample_rate: The audio sample rate, in Hz: 8000, 11025, 16000, 22050, 24000, 32000, 44100 or 48000 (the ES8311’s clock coefficients; the ES7210 supports the same rates)
playback_enabled: Set up playback: the I2S TX channel, the ES8311 DAC, the speaker and the playback task. Without it play_audio() queues nothing.
recording_enabled: Set up recording: the I2S RX channel, the ES7210 ADC (the dual microphone array) and the microphone task. Without it start_audio_recording() fails.
playback_buffer_size / playback_buffer_caps: the stream play_audio() queues into (0: about 67 ms of audio; larger lets one play_audio() call queue a whole UI sound, e.g. in MALLOC_CAP_SPIRAM)
playback_task_config / recording_task_config: the audio tasks (the recording callback runs on the recording task)
Note
Each I2S channel has a DMA ring of about 11.5 KB of internal DMA- capable RAM, and each task’s stack is in internal RAM too, so an application that only plays (or only records) saves that memory by turning the other direction off.
-
using microphone_callback_t = std::function<void(const uint8_t *data, size_t num_bytes)>#
Alias for the microphone callback, called with recorded audio data.
Public Functions
-
inline BoxType box_type() const#
Get the type of the box
See also
- Returns:
The type of the box that was detected
-
inline I2c &internal_i2c()#
Get a reference to the internal I2C bus
Note
The internal I2C bus is used for the touchscreen and audio codec
- Returns:
A reference to the internal I2C bus
-
inline espp::Interrupt &interrupts()#
Get a reference to the interrupts
- Returns:
A reference to the interrupts
-
bool initialize_touch(const touch_callback_t &callback = nullptr)#
Initialize the touchpad
Note
This will configure the touchpad interrupt pin which will automatically call the touch callback function when the touchpad is touched
Note
This can be called even if you have not initialized the display or the LCD.
- Parameters:
callback – The touchpad callback
- Returns:
true if the touchpad was successfully initialized, false otherwise
-
inline std::shared_ptr<TouchpadInput> touchpad_input() const#
Get the touchpad input
- Returns:
A shared pointer to the touchpad input
-
inline TouchpadData touchpad_data() const#
Get the most recent touchpad data
- Returns:
The touchpad data
-
void touchpad_read(uint8_t *num_touch_points, uint16_t *x, uint16_t *y, uint8_t *btn_state)#
Get the most recent touchpad data
See also
Note
This method is a convenience method for integrating with LVGL, the data it returns is identical to the data returned by the touchpad_data() method
- Parameters:
num_touch_points – The number of touch points
x – The x coordinate
y – The y coordinate
btn_state – The button state (0 = button released, 1 = button pressed)
-
TouchpadData touchpad_convert(const TouchpadData &data) const#
Convert touchpad data from raw reading to display coordinates
Note
Uses the touch_invert_x and touch_invert_y settings to determine if the x and y coordinates should be inverted
- Parameters:
data – The touchpad data to convert
- Returns:
The converted touchpad data
-
bool initialize_lcd()#
Initialize the LCD (low level display driver)
- Returns:
true if the LCD was successfully initialized, false otherwise
-
bool initialize_display(size_t pixel_buffer_size)#
Initialize the display (lvgl display driver)
Note
This will also allocate two full frame buffers in the SPIRAM
- Parameters:
pixel_buffer_size – The size of the pixel buffer
- Returns:
true if the display was successfully initialized, false otherwise
-
size_t rotated_display_width() const#
Get the display width in pixels, according to the current orientation
- Returns:
The display width in pixels, according to the current orientation
-
size_t rotated_display_height() const#
Get the display height in pixels, according to the current orientation
- Returns:
The display height in pixels, according to the current orientation
-
inline std::shared_ptr<Display<Pixel>> display() const#
Get a shared pointer to the display
- Returns:
A shared pointer to the display
-
inline const std::shared_ptr<DisplayDriver> &display_driver() const#
Get a shared pointer to the low-level display driver
- Returns:
A shared pointer to the display driver
-
void brightness(float brightness)#
Set the brightness of the backlight
Note
This function will only work after initialize_lcd() has been called
- Parameters:
brightness – The brightness of the backlight as a percentage (0 - 100)
-
float brightness() const#
Get the brightness of the backlight
Note
This function will only work after initialize_lcd() has been called
- Returns:
The brightness of the backlight as a percentage (0 - 100)
-
Pixel *vram0() const#
Get the VRAM 0 pointer (DMA memory used by LVGL)
Note
This is the memory used by LVGL for rendering
Note
This is null unless initialize_display() has been called
- Returns:
The VRAM 0 pointer
-
Pixel *vram1() const#
Get the VRAM 1 pointer (DMA memory used by LVGL)
Note
This is the memory used by LVGL for rendering
Note
This is null unless initialize_display() has been called
- Returns:
The VRAM 1 pointer
-
uint8_t *frame_buffer0() const#
Get the frame buffer 0 pointer
Note
This memory is designed to be used by the application developer and is provided as a convenience. It is not used by the display driver.
Note
This is null unless initialize_display() has been called
- Returns:
The frame buffer 0 pointer
-
uint8_t *frame_buffer1() const#
Get the frame buffer 1 pointer
Note
This memory is designed to be used by the application developer and is provided as a convenience. It is not used by the display driver.
Note
This is null unless initialize_display() has been called
- Returns:
The frame buffer 1 pointer
-
void write_lcd_frame(const uint16_t x, const uint16_t y, const uint16_t width, const uint16_t height, uint8_t *data)#
Write a frame to the LCD
Note
This method queues the data to be written to the LCD, only blocking if there is an ongoing SPI transaction
- Parameters:
x – The x coordinate
y – The y coordinate
width – The width of the frame, in pixels
height – The height of the frame, in pixels
data – The data to write
-
void write_lcd_lines(int xs, int ys, int xe, int ye, const uint8_t *data, uint32_t user_data)#
Write lines to the LCD
Note
This method queues the panel transfer asynchronously and may return before the write has completed.
- Parameters:
xs – The x start coordinate
ys – The y start coordinate
xe – The x end coordinate
ye – The y end coordinate
data – The data to write
user_data – User data to pass to the SPI transaction callback
-
bool initialize_boot_button(const button_callback_t &callback = nullptr)#
Initialize the boot button (side of the box)
- Parameters:
callback – The callback function to call when the button is pressed
- Returns:
true if the button was successfully initialized, false otherwise
-
bool boot_button_state() const#
Get the boot button state
- Returns:
The button state (true = button pressed, false = button released)
-
bool initialize_mute_button(const button_callback_t &callback = nullptr)#
Initialize the mute button (top of the box)
- Parameters:
callback – The callback function to call when the button is pressed
- Returns:
true if the button was successfully initialized, false otherwise
-
bool mute_button_state() const#
Get the mute button state
- Returns:
The button state (true = button pressed, false = button released)
-
bool initialize_audio()#
Initialize the audio system with the default AudioConfig: ES8311 playback and ES7210 recording at 48 kHz
- Returns:
true if the audio system was successfully initialized, false otherwise
-
bool initialize_audio(const AudioConfig &config)#
Initialize the audio system (ES8311 codec + speaker, ES7210 microphone ADC), full duplex on one I2S bus
Note
A failure part way through undoes what was set up before it (the I2S channels and their DMA rings, the stream buffer, the tasks, the codecs), so the call can be retried.
- Parameters:
config – The sample rate, which directions to set up, the playback buffer and the task configuration
- Returns:
true if the audio system was successfully initialized, false otherwise (also when neither playback nor recording is enabled, the sample rate is not one the codecs support, or no ES7210 answers at 0x40 / 0x41 when recording is enabled)
- bool initialize_sound (uint32_t default_audio_rate=48000, const espp::Task::BaseConfig &task_config={ .name="audio",.stack_size_bytes=4096,.priority=19,.core_id=1})
Initialize the sound subsystem (playback only)
Note
Sets up playback only, as before; initialize_microphone() adds recording.
- Parameters:
default_audio_rate – The default audio rate
task_config – The task configuration for the audio task
- Returns:
true if the sound subsystem was successfully initialized, false otherwise
-
void deinitialize_audio()#
Stop the audio system and free what initialize_audio() set up (the speaker is switched off). Idempotent.
Note
The audio methods below may be called from any task meanwhile, but initialize_audio() and deinitialize_audio() must not run concurrently with each other, nor from an audio callback.
-
inline bool is_audio_initialized() const#
Whether the audio system is initialized
- Returns:
True if initialize_audio() succeeded (until deinitialize_audio())
-
inline std::shared_ptr<espp::Audio> audio() const#
The audio component, for anything the BSP methods below do not expose
Note
deinitialize_audio() releases the hardware even while the returned pointer is held: the object is then uninitialized (its methods fail / return 0), and a later initialize_audio() makes a new one.
- Returns:
The audio component, or nullptr before initialize_audio()
-
void enable_audio(bool enable)#
Enable or disable the speaker (its power pin)
Note
initialize_audio() enables it when playback is set up.
- Parameters:
enable – True to enable, false to disable
-
void enable_sound(bool enable)#
Enable or disable sound
Note
This method sets the power pin to the appropriate value
-
uint32_t audio_sample_rate() const#
Get the audio sample rate
- Returns:
The audio sample rate, in Hz
-
bool audio_sample_rate(uint32_t sample_rate)#
Set the audio sample rate (the I2S clocks and both codecs). The audio queued for playback is dropped, since it was for the old rate.
- Parameters:
sample_rate – The audio sample rate, in Hz
- Returns:
True on success (false before initialize_audio(), or if a codec does not support the rate: the previous rate is kept)
-
size_t audio_buffer_size() const#
Get the audio buffer size
- Returns:
The size of one playback block, in bytes (1/60 s of audio)
-
void mute(bool mute)#
Mute or unmute the audio
Note
Before initialize_audio() (or without playback) the value is stored and applied when playback starts.
- Parameters:
mute – true to mute the audio, false to unmute the audio
-
bool is_muted() const#
Check if the audio is muted
- Returns:
true if the audio is muted, false otherwise
-
void volume(float volume)#
Set the volume
Note
Before initialize_audio() (or without playback) the value is stored and applied when playback starts.
- Parameters:
volume – The volume in percent (0 - 100)
-
float volume() const#
Get the volume
- Returns:
The volume in percent (0 - 100)
-
size_t play_audio(const uint8_t *data, size_t num_bytes)#
Play audio
Note
This function is non-blocking and queues the data for the audio task to play; to stream data larger than the internal buffer, call it repeatedly, advancing by the returned number of bytes (or make the buffer larger: AudioConfig::playback_buffer_size)
Note
Must be called from task context, not from an ISR.
- Parameters:
data – The audio data to play (16-bit signed interleaved stereo)
num_bytes – The number of bytes to play
- Returns:
The number of bytes actually queued (may be less than
num_bytesif the internal stream buffer is full)
-
size_t play_audio(std::span<const uint8_t> data)#
Play audio
Note
This function is non-blocking and queues the data for the audio task to play; to stream data larger than the internal buffer, call it repeatedly, advancing by the returned number of bytes (or make the buffer larger: AudioConfig::playback_buffer_size)
Note
Must be called from task context, not from an ISR.
- Parameters:
data – The audio data to play (16-bit signed interleaved stereo)
- Returns:
The number of bytes actually queued (may be less than the data size if the internal stream buffer is full)
-
size_t play_audio(const std::vector<uint8_t> &data)#
Play audio
- Parameters:
data – The audio data to play (16-bit signed interleaved stereo)
- Returns:
The number of bytes actually queued
-
void clear_audio()#
Drop any queued (not yet played) audio so a subsequent play_audio() starts immediately instead of waiting behind previously queued sound. Useful for UI sounds where a new event should restart the sound for maximum responsiveness.
-
bool start_audio_recording(std::function<void(const uint8_t *data, size_t length)> callback)#
Start recording audio
Note
The callback runs in the dedicated microphone task’s context (a separate task from audio playback), so keep it quick and non- blocking and size that task’s stack accordingly
- Parameters:
callback – Function to call with recorded audio data: 16-bit signed interleaved stereo (microphone 1 on the left slot, microphone 2 on the right, through the ES7210) at audio_sample_rate()
- Returns:
True if recording started successfully (false, among other reasons, when initialize_audio() did not enable recording)
-
void stop_audio_recording()#
Stop recording audio. Once it returns the callback is not called again (unless it is called from the callback itself).
- bool initialize_microphone (const microphone_callback_t &callback, const espp::Task::BaseConfig &task_config={.name="microphone",.stack_size_bytes=4096,.priority=10,.core_id=1})
Initialize the microphones (the dual microphone array through the ES7210 ADC) and start delivering audio data to the provided callback
Note
The audio subsystem must be initialized first. If it was set up without recording, it is set up again with recording enabled, so like initialize_audio() and deinitialize_audio() it must not run concurrently with them, nor from an audio callback.
- Parameters:
callback – The callback to call with recorded audio data: 16-bit signed interleaved stereo (microphone 1 on the left slot, microphone 2 on the right) at audio_sample_rate()
task_config – Ignored: the microphone task uses AudioConfig::recording_task_config
- Returns:
true if the microphone was successfully initialized, false otherwise
-
void microphone_volume(float volume)#
Set the microphone volume
Note
Before initialize_audio() (or without recording) the value is stored and applied when recording starts.
- Parameters:
volume – The volume as a percentage (0 - 100), mapped onto the ES7210 analog microphone gain range (0 dB - +37.5 dB)
-
float microphone_volume() const#
Get the microphone volume
- Returns:
The microphone volume as a percentage (0 - 100)
- bool initialize_imu (const Imu::filter_fn &orientation_filter=nullptr, const Imu::ImuConfig &imu_config={ .accelerometer_range=Imu::AccelerometerRange::RANGE_2G,.accelerometer_odr=Imu::AccelerometerODR::ODR_400_HZ,.gyroscope_range=Imu::GyroscopeRange::RANGE_2000DPS,.gyroscope_odr=Imu::GyroscopeODR::ODR_400_HZ})
Initialize the IMU
- Parameters:
orientation_filter – The orientation filter, if provided
imu_config – The IMU configuration
- Returns:
true if the IMU was successfully initialized, false otherwise
-
inline const std::string &get_name() const#
Get the name of the component
Note
This is the tag of the logger
- Returns:
A const reference to the name of the component
-
template<typename T = void>
inline void set_log_tag(const std::string_view&)# Not available: the tag is fixed at construction (pass it to the constructor). Enable CONFIG_ESPP_LOGGER_MUTABLE_TAG (menuconfig: ESPP Logger -> Mutable tag) to change it afterwards.
-
inline espp::Logger::Verbosity get_log_level() const#
Get the log level for the logger
See also
See also
- Returns:
The verbosity level of the logger
-
inline void set_log_level(espp::Logger::Verbosity level)#
Set the log level for the logger
See also
See also
- Parameters:
level – The verbosity level to use for the logger
-
inline void set_log_verbosity(espp::Logger::Verbosity level)#
Set the log verbosity for the logger
See also
See also
See also
Note
This is a convenience method that calls set_log_level
- Parameters:
level – The verbosity level to use for the logger
-
inline espp::Logger::Verbosity get_log_verbosity() const#
Get the log verbosity for the logger
See also
See also
See also
Note
This is a convenience method that calls get_log_level
- Returns:
The verbosity level of the logger
-
inline void set_log_rate_limit(std::chrono::duration<float> rate_limit)#
Set the rate limit for the logger
See also
Note
Only calls to the logger that have _rate_limit suffix will be rate limited
- Parameters:
rate_limit – The rate limit to use for the logger
Public Static Functions
-
static inline EspBox &get()#
Access the singleton instance of the EspBox class.
- Returns:
Reference to the singleton instance of the EspBox class
-
static inline size_t lcd_width()#
Get the width of the LCD in pixels
- Returns:
The width of the LCD in pixels
-
static inline size_t lcd_height()#
Get the height of the LCD in pixels
- Returns:
The height of the LCD in pixels
-
static inline auto get_lcd_dc_gpio()#
Get the GPIO pin for the LCD data/command signal
- Returns:
The GPIO pin for the LCD data/command signal
-
static inline size_t display_width()#
Get the display width in pixels
- Returns:
The display width in pixels
-
static inline size_t display_height()#
Get the display height in pixels
- Returns:
The display height in pixels
-
static inline auto get_mute_pin()#
Get the GPIO pin for the mute button (top of the box)
- Returns:
The GPIO pin for the mute button
-
static AudioConfig default_audio_config()#
The board’s default AudioConfig: 48 kHz, playback and recording, and the tasks “box audio out” / “box audio in” with this board’s stack, priority and core.
- Returns:
The default AudioConfig