8 Commits

Author SHA1 Message Date
a3d6a85516 Includes. 2025-03-01 17:08:44 -05:00
a91352ffcd Make Pixel static. 2025-03-01 16:49:15 -05:00
fc0fd98426 Clean up comments. 2025-03-01 16:15:21 -05:00
1a7da67bdb Clean up flush callback. 2025-03-01 15:43:40 -05:00
00ea5dae20 Refactor ownership of draw buffer data. 2025-03-01 10:34:24 -05:00
63899a606a Clean up some comments. 2025-02-26 19:26:53 -05:00
25b4564a8b Fix ESP logging tags. 2025-02-16 14:40:53 -05:00
e2bb406139 Finish cleanup. 2025-02-16 14:32:00 -05:00
19 changed files with 808 additions and 260 deletions

View File

@@ -2,7 +2,7 @@
dependencies: dependencies:
## Required IDF version ## Required IDF version
idf: idf:
version: '>=4.1.0' version: '>=5.3.0'
# # Put list of dependencies here # # Put list of dependencies here
# # For components maintained by Espressif: # # For components maintained by Espressif:
# component: "~1.0.0" # component: "~1.0.0"

View File

@@ -2091,6 +2091,15 @@ CONFIG_MDNS_TASK_STACK_SIZE=4096
CONFIG_MDNS_TASK_AFFINITY_CPU0=y CONFIG_MDNS_TASK_AFFINITY_CPU0=y
# CONFIG_MDNS_TASK_AFFINITY_CPU1 is not set # CONFIG_MDNS_TASK_AFFINITY_CPU1 is not set
CONFIG_MDNS_TASK_AFFINITY=0x0 CONFIG_MDNS_TASK_AFFINITY=0x0
#
# MDNS Memory Configuration
#
CONFIG_MDNS_TASK_CREATE_FROM_INTERNAL=y
CONFIG_MDNS_MEMORY_ALLOC_INTERNAL=y
# CONFIG_MDNS_MEMORY_CUSTOM_IMPL is not set
# end of MDNS Memory Configuration
CONFIG_MDNS_SERVICE_ADD_TIMEOUT_MS=2000 CONFIG_MDNS_SERVICE_ADD_TIMEOUT_MS=2000
CONFIG_MDNS_TIMER_PERIOD_MS=100 CONFIG_MDNS_TIMER_PERIOD_MS=100
# CONFIG_MDNS_NETWORKING_SOCKET is not set # CONFIG_MDNS_NETWORKING_SOCKET is not set

View File

@@ -2,8 +2,6 @@
Using the ESP IDF for drawing to a LCD screen over I2C. Using the ESP IDF for drawing to a LCD screen over I2C.
For instructions on setting up the ESP-IDF see [04_-esp-idf-arduino](./../04_esp-idf-arduino)
[ESP IDF - I2C](https://docs.espressif.com/projects/esp-idf/en/v5.3.2/esp32/api-reference/peripherals/i2c.html) [ESP IDF - I2C](https://docs.espressif.com/projects/esp-idf/en/v5.3.2/esp32/api-reference/peripherals/i2c.html)
[ESP IDF - LCD](https://docs.espressif.com/projects/esp-idf/en/v5.3.2/esp32/api-reference/peripherals/lcd/index.html) [ESP IDF - LCD](https://docs.espressif.com/projects/esp-idf/en/v5.3.2/esp32/api-reference/peripherals/lcd/index.html)
@@ -12,10 +10,10 @@ For instructions on setting up the ESP-IDF see [04_-esp-idf-arduino](./../04_esp
![schematic](./schematic.png) ![schematic](./schematic.png)
Temperature and humidity sensor served on a web page within the local network.
![example](./example.gif) ![example](./example.gif)
For instructions on setting up the ESP-IDF see [04_-esp-idf-arduino](./../04_esp-idf-arduino)
To build this example run the following commands. To build this example run the following commands.
```bash ```bash

View File

@@ -1 +1,7 @@
idf_component_register(SRC_DIRS . INCLUDE_DIRS .) idf_component_register(
SRCS
main.cpp display.cpp panel_device.cpp scoped_lock.cpp
i2c.h time_keeper.h panel.h ssd1306.h
INCLUDE_DIRS .
REQUIRES driver
)

View File

@@ -1,25 +1,19 @@
/*#############################################################################
#include <esp_timer.h> ## Author: Shaun Reed ##
## Legal: All Content (c) 2025 Shaun Reed, all rights reserved ##
## ##
## Contact: shaunrd0@gmail.com | URL: www.shaunreed.com ##
##############################################################################
*/
#include <lv_init.h> #include <lv_init.h>
#include <mutex>
#include "display.h" #include "display.h"
// TODO: Remove this dependency by relocating SSD1306::oledb_buffer_
#include "ssd1306.h"
// LVGL library is not thread-safe, this example calls LVGL APIs from tasks.
// We must use a mutex to protect it.
_lock_t Display::ScopedLock::lv_lock_;
// Static TimeKeeper for managing ESP timers across all displays. // Static TimeKeeper for managing ESP timers across all displays.
TimeKeeper Display::timers_; TimeKeeper Display::timers_;
Display::Display(IPanelDevice &device) : Display::Display(IPanelDevice &device) :
panel_(device), panel_(device)
lv_buf_(nullptr)
{ {
if (!lv_is_initialized()) { if (!lv_is_initialized()) {
ESP_LOGI(TAG, "Initialize LVGL"); ESP_LOGI(TAG, "Initialize LVGL");
@@ -31,12 +25,7 @@ Display::Display(IPanelDevice &device) :
// associate the i2c panel handle to the display // associate the i2c panel handle to the display
lv_display_set_user_data(lv_display_, panel_.esp_panel_); lv_display_set_user_data(lv_display_, panel_.esp_panel_);
register_draw_buffer(); panel_.register_display_callbacks(lv_display_);
register_lvgl_tick_timer();
ESP_LOGI(TAG, "Create LVGL FreeRTOS task");
xTaskCreate(Display::lvgl_port_task, "LVGL", LVGL_TASK_STACK_SIZE,
nullptr, LVGL_TASK_PRIORITY, nullptr);
} }
void Display::set_text(const char *text, void Display::set_text(const char *text,
@@ -56,7 +45,7 @@ void Display::set_text(const char *text,
} }
auto obj = lv_objects_[name]; auto obj = lv_objects_[name];
// Circular scroll. // Set text and long mode.
lv_label_set_long_mode(obj, long_mode); lv_label_set_long_mode(obj, long_mode);
lv_label_set_text(obj, text); lv_label_set_text(obj, text);
@@ -65,112 +54,3 @@ void Display::set_text(const char *text,
lv_obj_set_width(obj, lv_display_get_horizontal_resolution(lv_display_)); lv_obj_set_width(obj, lv_display_get_horizontal_resolution(lv_display_));
lv_obj_align(obj, align, 0, 0); lv_obj_align(obj, align, 0, 0);
} }
bool Display::lvgl_flush_ready_cb(esp_lcd_panel_io_handle_t,
esp_lcd_panel_io_event_data_t *,
void *user_ctx)
{
auto *disp = (lv_display_t *) user_ctx;
lv_display_flush_ready(disp);
return false;
}
void Display::lvgl_flush_cb(lv_display_t *display, const lv_area_t *area,
uint8_t *px_map) // NOLINT(*-non-const-parameter)
{
auto panel_handle =
(esp_lcd_panel_handle_t) lv_display_get_user_data(display);
// Necessary because LVGL reserves 2x4 bytes in the buffer for a palette.
// For more information about the monochrome, please refer to:
// https://docs.lvgl.io/9.2/porting/display.html#monochrome-displays
// Skip the palette here.
px_map += LVGL_PALETTE_SIZE;
uint16_t hor_res = lv_display_get_physical_horizontal_resolution(display);
int32_t x1 = area->x1;
int32_t x2 = area->x2;
int32_t y1 = area->y1;
int32_t y2 = area->y2;
for (int32_t y = y1; y <= y2; y++) {
for (int32_t x = x1; x <= x2; x++) {
/* The order of bits is MSB first.
MSB LSB
bits 7 6 5 4 3 2 1 0
pixels 0 1 2 3 4 5 6 7
Left Right
*/
bool chroma_color = (px_map[(hor_res >> 3) * y + (x >> 3)] &
1 << (7 - x % 8));
// Write to the buffer as required for the display.
// It writes only 1-bit for monochrome displays mapped vertically.
uint8_t *buf = SSD1306::oled_buffer_ + hor_res * (y >> 3) + (x);
if (chroma_color) {
(*buf) &= ~(1 << (y % 8));
} else {
(*buf) |= (1 << (y % 8));
}
}
}
// Pass the draw buffer to the driver.
ESP_ERROR_CHECK(
esp_lcd_panel_draw_bitmap(panel_handle, x1, y1, x2 + 1, y2 + 1,
SSD1306::oled_buffer_));
}
void Display::lvgl_increase_tick_cb(void *)
{
// Tell LVGL how many milliseconds has elapsed
lv_tick_inc(LVGL_TICK_PERIOD_MS);
}
[[noreturn]] void Display::lvgl_port_task(void *)
{
ESP_LOGI(TAG, "Starting LVGL task");
for (uint32_t time_till_next_ms = 0; true;) {
_lock_acquire(&ScopedLock::lv_lock_);
time_till_next_ms = lv_timer_handler();
_lock_release(&ScopedLock::lv_lock_);
usleep(1000 * time_till_next_ms);
}
}
void Display::register_draw_buffer()
{
// Create draw buffer.
ESP_LOGI(TAG, "Allocate separate LVGL draw buffers");
lv_buf_ = heap_caps_calloc(1, panel_.device_->lv_buf_size_,
MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
assert(lv_buf_);
ESP_LOGI(TAG, "Set LVGL draw buffers");
// Color format must be set first, LVGL9 suooprt new monochromatic format.
lv_display_set_color_format(lv_display_, LV_COLOR_FORMAT_I1);
lv_display_set_buffers(lv_display_, lv_buf_, nullptr,
panel_.device_->lv_buf_size_,
LV_DISPLAY_RENDER_MODE_FULL);
lv_display_set_rotation(lv_display_, LV_DISPLAY_ROTATION_0);
ESP_LOGI(TAG, "Set LVGL callback for flushing to the display");
lv_display_set_flush_cb(lv_display_, Display::lvgl_flush_cb);
ESP_LOGI(TAG, "Register io panel callback for LVGL flush ready notification");
const esp_lcd_panel_io_callbacks_t cbs = {
.on_color_trans_done = Display::lvgl_flush_ready_cb,
};
ESP_ERROR_CHECK(
esp_lcd_panel_io_register_event_callbacks(panel_.esp_io_, &cbs,
lv_display_));
}
void Display::register_lvgl_tick_timer()
{
ESP_LOGI(TAG, "Use esp_timer to increase LVGL tick");
const esp_timer_create_args_t esp_timer_args = {
.callback = &Display::lvgl_increase_tick_cb,
.name = "lvgl_tick"
};
timers_.start_new_timer_periodic(esp_timer_args, LVGL_TICK_PERIOD_MS * 1000);
}

View File

@@ -1,22 +1,38 @@
/*#############################################################################
## Author: Shaun Reed ##
## Legal: All Content (c) 2025 Shaun Reed, all rights reserved ##
## ##
## Contact: shaunrd0@gmail.com | URL: www.shaunreed.com ##
##############################################################################
*/
#ifndef DISPLAY_H #ifndef DISPLAY_H
#define DISPLAY_H #define DISPLAY_H
#include <widgets/label/lv_label.h> #include <widgets/label/lv_label.h>
#include <unordered_map> #include <unordered_map>
#include "time_keeper.h" #include "time_keeper.h"
#include "panel.h" #include "panel.h"
#include "scoped_lock.h"
#define LVGL_TICK_PERIOD_MS 5 /**
#define LVGL_TASK_STACK_SIZE (4 * 1024) * Encapsulates lv_display handle and related LVGL operations.
#define LVGL_TASK_PRIORITY 2 * Contains helper methods that wrap basic LVGL operations such as drawing text.
* The underlying lv_display can be obtained for manual LVGL operations.
* @sa ScopedLock
* @sa Display::get()
*/
class Display { class Display {
public: public:
// /**
// CONSTRUCTORS * Construct a new Display using an object that implements IPanelDevice.
*
* @param device An object that implements the IPanelDevice interface.
*/
explicit Display(IPanelDevice &device);
~Display() = default;
Display(const Display &) = delete; Display(const Display &) = delete;
@@ -24,14 +40,7 @@ public:
Display &operator=(Display &) = delete; Display &operator=(Display &) = delete;
/** using lv_display_handle_t = lv_display_t *;
* Construct a new Display using an IPanelDevice.
*
* @param device An object that implements the IPanelDevice interface.
*/
explicit Display(IPanelDevice &device);
~Display() = default;
// //
// GETTERS // GETTERS
@@ -41,20 +50,20 @@ public:
* *
* @sa ScopedLock for calling custom LVGL API's not implemented by Display. * @sa ScopedLock for calling custom LVGL API's not implemented by Display.
*/ */
[[nodiscard]] inline const lv_display_t *get() const { return lv_display_; } [[nodiscard]] inline lv_display_handle_t get() const { return lv_display_; }
/** /**
* Getter for accessing LVGL display handle. * Getter for accessing LVGL display handle.
* *
* @sa ScopedLock for calling custom LVGL API's not implemented by Display. * @sa ScopedLock for calling custom LVGL API's not implemented by Display.
*/ */
[[nodiscard]] inline lv_display_t *get() { return lv_display_; } [[nodiscard]] inline lv_display_handle_t get() { return lv_display_; }
/// Dereference operator for accessing LVGL display handle. /// Dereference operator for accessing LVGL display handle.
[[nodiscard]] inline const lv_display_t *operator*() const { return get(); } [[nodiscard]] inline lv_display_handle_t operator*() const { return get(); }
/// Dereference operator for accessing LVGL display handle. /// Dereference operator for accessing LVGL display handle.
[[nodiscard]] inline lv_display_t *operator*() { return get(); } [[nodiscard]] inline lv_display_handle_t operator*() { return get(); }
// //
// LVGL OPERATIONS // LVGL OPERATIONS
@@ -73,23 +82,6 @@ public:
lv_label_long_mode_t long_mode = LV_LABEL_LONG_SCROLL_CIRCULAR, lv_label_long_mode_t long_mode = LV_LABEL_LONG_SCROLL_CIRCULAR,
lv_align_t align = LV_ALIGN_TOP_MID); lv_align_t align = LV_ALIGN_TOP_MID);
//
// TYPE DEFINITIONS
/**
* Obtains LVGL API mutex lock for the duration of local scope.
*
* LVGL library is not thread-safe, this example calls LVGL APIs from tasks.
*/
struct ScopedLock {
explicit ScopedLock() { _lock_acquire(&lv_lock_); }
~ScopedLock() { _lock_release(&lv_lock_); }
/// Mutex used to protect LVGL API calls.
static _lock_t lv_lock_;
};
// //
// PUBLIC STATIC MEMBERS // PUBLIC STATIC MEMBERS
@@ -97,23 +89,6 @@ public:
static TimeKeeper timers_; static TimeKeeper timers_;
private: private:
/// Registers LVGL draw buffers for this display.
void register_draw_buffer();
/// Registers LVGL ticker timer callback for rendering this display.
static void register_lvgl_tick_timer();
static bool lvgl_flush_ready_cb(esp_lcd_panel_io_handle_t panel,
esp_lcd_panel_io_event_data_t *data,
void *user_ctx);
static void lvgl_flush_cb(lv_display_t *display,
const lv_area_t *area,
uint8_t *px_map);
static void lvgl_increase_tick_cb(void *arg);
[[noreturn]] static void lvgl_port_task(void *arg);
// //
// PRIVATE MEMBERS // PRIVATE MEMBERS
@@ -122,10 +97,7 @@ private:
Panel panel_; Panel panel_;
/// LVGL display handle. /// LVGL display handle.
lv_display_t *lv_display_; lv_display_handle_t lv_display_;
/// LVGL draw buffer associated with this Display's lv_display_t.
void *lv_buf_;
/** /**
* LVGL object handles stored in the LVGL screen associated with this Display. * LVGL object handles stored in the LVGL screen associated with this Display.
@@ -134,6 +106,9 @@ private:
* @sa lv_display_get_screen_active * @sa lv_display_get_screen_active
*/ */
std::unordered_map<const char *, lv_obj_t *> lv_objects_; std::unordered_map<const char *, lv_obj_t *> lv_objects_;
/// Tag used for ESP logging.
constexpr static const char *TAG = "Display";
}; };
#endif // DISPLAY_H #endif // DISPLAY_H

View File

@@ -1,3 +1,10 @@
/*#############################################################################
## Author: Shaun Reed ##
## Legal: All Content (c) 2025 Shaun Reed, all rights reserved ##
## ##
## Contact: shaunrd0@gmail.com | URL: www.shaunreed.com ##
##############################################################################
*/
#ifndef I2C_H #ifndef I2C_H
#define I2C_H #define I2C_H
@@ -5,14 +12,20 @@
#include <driver/i2c_master.h> #include <driver/i2c_master.h>
static const char *TAG = "lcd-panel"; /**
* Encapsulates ESP I2C creation and usage.
*/
struct I2C { struct I2C {
/**
* Construct and initialize an ESP I2C master bus.
* An I2C constructor may only be called one time in any application.
*
* @param sda GPIO pin number for SDA
* @param scl GPIO pin number for SCL
* @param rst GPIO pin number for RST
*/
I2C(gpio_num_t sda, gpio_num_t scl, int rst = -1) : I2C(gpio_num_t sda, gpio_num_t scl, int rst = -1) :
esp_i2c_bus_(nullptr), I2C((i2c_master_bus_config_t) {
rst_num_(rst),
esp_bus_config_(
(i2c_master_bus_config_t) {
.i2c_port = I2C_BUS_PORT, .i2c_port = I2C_BUS_PORT,
.sda_io_num = sda, .sda_io_num = sda,
.scl_io_num = scl, .scl_io_num = scl,
@@ -21,22 +34,58 @@ struct I2C {
.flags { .flags {
.enable_internal_pullup = true, .enable_internal_pullup = true,
}, },
} },
) rst
) { }
/**
* Construct an ESP I2C master bus given a specific ESP I2C configuration.
* An I2C constructor may only be called one time in any application.
*
* @param config ESP I2C master bus configuration.
* @param rst GPIO pin number for RST
*/
explicit I2C(i2c_master_bus_config_t config, int rst = -1) :
esp_bus_config_(config),
rst_num_(rst)
{ {
i2c_master_bus_handle_t i2c;
ESP_LOGI(TAG, "Initializing new master I2C bus"); ESP_LOGI(TAG, "Initializing new master I2C bus");
ESP_ERROR_CHECK(i2c_new_master_bus(&esp_bus_config_, &esp_i2c_bus_)); ESP_ERROR_CHECK(i2c_new_master_bus(&esp_bus_config_, &i2c));
} }
~I2C() = default; ~I2C() = default;
// TODO: Can you use the I2C get_master_bus API in a static method? //
i2c_master_bus_handle_t esp_i2c_bus_; // GETTERS
/**
* ESP I2C master bus handle getter.
* This will fail if an I2C instance was never constructed.
*/
static i2c_master_bus_handle_t get()
{
i2c_master_bus_handle_t i2c = nullptr;
ESP_ERROR_CHECK(i2c_master_get_bus_handle(0, &i2c));
return i2c;
}
//
// PUBLIC MEMBERS
/// ESP I2C master bus configuration used during initialization.
i2c_master_bus_config_t esp_bus_config_;
/// RST GPIO pin number.
int rst_num_; int rst_num_;
private: private:
i2c_master_bus_config_t esp_bus_config_;
//
// PRIVATE MEMBERS
/// Tag used for ESP logging.
constexpr static const char *TAG = "I2C";
}; };
#endif //I2C_H #endif //I2C_H

View File

@@ -1,5 +1,6 @@
## IDF Component Manager Manifest File ## IDF Component Manager Manifest File
dependencies: dependencies:
idf: '>=5.3.0'
espressif/arduino-esp32: ^3.1.1 espressif/arduino-esp32: ^3.1.1
lvgl/lvgl: "9.2.0" lvgl/lvgl: "9.2.0"
esp_lcd_sh1107: "^1" esp_lcd_sh1107: "^1"

View File

@@ -1,3 +1,10 @@
/*#############################################################################
## Author: Shaun Reed ##
## Legal: All Content (c) 2025 Shaun Reed, all rights reserved ##
## ##
## Contact: shaunrd0@gmail.com | URL: www.shaunreed.com ##
##############################################################################
*/
#include "display.h" #include "display.h"
#include "ssd1306.h" #include "ssd1306.h"

View File

@@ -1,10 +1,28 @@
/*#############################################################################
## Author: Shaun Reed ##
## Legal: All Content (c) 2025 Shaun Reed, all rights reserved ##
## ##
## Contact: shaunrd0@gmail.com | URL: www.shaunreed.com ##
##############################################################################
*/
#ifndef PANEL_H #ifndef PANEL_H
#define PANEL_H #define PANEL_H
#include "panel_device.h" #include "panel_device.h"
class Panel { /**
public: * Encapsulates esp_lcd_panel handles and operations.
* The only exception is esp_lcd_panel_io_i2c_config_t owned by IPanelDevice.
* This structure requires details specific to the implementing device.
*
* Panel is an implementation detail of Display, not meant to be used directly.
*/
struct Panel {
/**
* Construct a new Panel using an object that implements IPanelDevice.
*
* @param device An object that implements the IPanelDevice interface.
*/
explicit Panel(IPanelDevice &device) : explicit Panel(IPanelDevice &device) :
device_(&device), device_(&device),
esp_io_(nullptr), esp_io_(nullptr),
@@ -31,14 +49,39 @@ public:
~Panel() = default; ~Panel() = default;
//
// PUBLIC MEMBERS
/// Pointer to object using known interface for IPanelDevice.
IPanelDevice *device_; IPanelDevice *device_;
/// ESP LCD panel IO handle.
esp_lcd_panel_io_handle_t esp_io_; esp_lcd_panel_io_handle_t esp_io_;
/// ESP LCD panel handle.
esp_lcd_panel_handle_t esp_panel_; esp_lcd_panel_handle_t esp_panel_;
private: /// ESP LCD panel configuration structure.
esp_lcd_panel_dev_config_t esp_panel_config_; esp_lcd_panel_dev_config_t esp_panel_config_;
/**
* Registers LVGL draw buffers and callbacks for rendering the display.
*
* @param display_handle Pointer to the LVGL display to use for rendering.
*/
inline void register_display_callbacks(lv_display_t *display_handle) const
{
device_->register_rendering_data(display_handle, esp_io_);
device_->register_lvgl_tick_timer();
}
private:
//
// PRIVATE MEMBERS
/// Tag used for ESP logging.
constexpr static const char *TAG = "Panel";
}; };
#endif //PANEL_H #endif //PANEL_H

View File

@@ -0,0 +1,145 @@
/*#############################################################################
## Author: Shaun Reed ##
## Legal: All Content (c) 2025 Shaun Reed, all rights reserved ##
## ##
## Contact: shaunrd0@gmail.com | URL: www.shaunreed.com ##
##############################################################################
*/
#include "panel_device.h"
#include "display.h"
bool IPanelDevice::lvgl_flush_ready_cb(esp_lcd_panel_io_handle_t,
esp_lcd_panel_io_event_data_t *,
void *user_ctx)
{
auto *disp = (lv_display_t *) user_ctx;
lv_display_flush_ready(disp);
return false;
}
void IPanelDevice::lvgl_flush_cb(lv_display_t *display, const lv_area_t *area,
uint8_t *px_map) // NOLINT(*-non-const-parameter)
{
auto panel_handle =
(esp_lcd_panel_handle_t) lv_display_get_user_data(display);
// Necessary because LVGL reserves 2x4 bytes in the buffer for a palette.
// Since we are monochrome, we don't need these additional bytes.
// For more information about the monochrome, please refer to:
// https://docs.lvgl.io/9.2/porting/display.html#monochrome-displays
// Skip the palette here.
px_map += LVGL_PALETTE_SIZE;
uint16_t hor_res = lv_display_get_physical_horizontal_resolution(display);
int32_t x1 = area->x1;
int32_t x2 = area->x2;
int32_t y1 = area->y1;
int32_t y2 = area->y2;
// As of 03/01/2025 master branch of LVGL contains this helper for the same.
// https://docs.lvgl.io/master/API/draw/sw/lv_draw_sw_utils.html
// lv_draw_sw_i1_convert_to_vtiled()
for (int32_t y = y1; y <= y2; y++) {
for (int32_t x = x1; x <= x2; x++) {
// Get the byte offset of the pixel coordinates using horizontal-mapping.
int h_offset = Pixel::horizontal_byte_offset(x, y, hor_res);
// True if the pixel is lit, else false.
bool chroma_color = px_map[h_offset] & Pixel::msb_mask(x);
// We need an additional buffer for transposing the pixel data to the
// vertical format required by the display driver.
uint8_t *buf = IPanelDevice::get_additional_draw_buffer();
// Move to the position in the auxillary buffer where the pixel is stored.
buf += Pixel::vertical_byte_offset(x, y, hor_res);
// Write the single bit to the monochrome display mapped vertically.
// Take the Least Significant Bit mask of the Y coordinate to select the
// bit representing a pixel at position y in a vertically-mapped display.
if (chroma_color) {
// Set the vertically-mapped pixel to on.
*buf &= ~Pixel::lsb_mask(y);
} else {
// Set the vertically-mapped pixel to off.
*buf |= Pixel::lsb_mask(y);
}
}
}
// Pass the draw buffer to the driver.
ESP_ERROR_CHECK(
esp_lcd_panel_draw_bitmap(panel_handle, x1, y1, x2 + 1, y2 + 1,
IPanelDevice::get_additional_draw_buffer()));
}
void IPanelDevice::lvgl_increase_tick_cb(void *)
{
// Tell LVGL how many milliseconds has elapsed
lv_tick_inc(LVGL_TICK_PERIOD_MS);
}
[[noreturn]] void IPanelDevice::lvgl_port_task(void *)
{
// Optionally initialize some LVGL objects here before entering loop below.
ESP_LOGI(TAG, "Starting LVGL task");
for (uint32_t time_to_next_ms = 0; true; usleep(1000 * time_to_next_ms)) {
// Obtain LVGL API lock before calling any LVGL methods.
ScopedLock lock;
// Optionally handle LVGL input or event logic here.
// Update LVGL periodic timers.
time_to_next_ms = lv_timer_handler();
}
}
void IPanelDevice::register_rendering_data(lv_display_t *display_handle,
esp_lcd_panel_io_handle_t io_handle)
{
// Create draw buffer.
ESP_LOGI(TAG, "Allocate separate LVGL draw buffers");
lv_buf_ = heap_caps_calloc(1, lv_buf_size_,
MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
assert(lv_buf_);
ESP_LOGI(TAG, "Set LVGL draw buffers");
// Color format must be set first, LVGL9 suooprt new monochromatic format.
lv_display_set_color_format(display_handle, LV_COLOR_FORMAT_I1);
lv_display_set_buffers(display_handle, lv_buf_, nullptr,
lv_buf_size_,
LV_DISPLAY_RENDER_MODE_FULL);
lv_display_set_rotation(display_handle, LV_DISPLAY_ROTATION_0);
ESP_LOGI(TAG, "Set LVGL callback for flushing to the display");
lv_display_set_flush_cb(display_handle, IPanelDevice::lvgl_flush_cb);
ESP_LOGI(TAG, "Register io panel callback for LVGL flush ready notification");
const esp_lcd_panel_io_callbacks_t cbs = {
.on_color_trans_done = IPanelDevice::lvgl_flush_ready_cb,
};
ESP_ERROR_CHECK(
esp_lcd_panel_io_register_event_callbacks(io_handle, &cbs,
display_handle));
}
void IPanelDevice::register_lvgl_tick_timer()
{
ESP_LOGI(TAG, "Use esp_timer to increase LVGL tick");
const esp_timer_create_args_t esp_timer_args = {
.callback = &IPanelDevice::lvgl_increase_tick_cb,
// Data to pass to the IPanelDevice::lvgl_port_task callback.
.arg = nullptr,
.name = "lvgl_tick",
};
Display::timers_.start_new_timer_periodic(esp_timer_args,
LVGL_TICK_PERIOD_MS * 1000);
// LVGL requires a FreeRTOS task for running it's event loop.
// The lvgl_port_task callback can update the UI or handle input logic.
// For this basic example we don't do either of these things.
ESP_LOGI(TAG, "Create LVGL FreeRTOS task");
// Optionally set user data to pass to LVGL's FreeRTOS task callback here.
void *user_data = nullptr;
xTaskCreate(lvgl_port_task, "LVGL", LVGL_TASK_STACK_SIZE,
user_data, LVGL_TASK_PRIORITY, nullptr);
}

View File

@@ -1,3 +1,10 @@
/*#############################################################################
## Author: Shaun Reed ##
## Legal: All Content (c) 2025 Shaun Reed, all rights reserved ##
## ##
## Contact: shaunrd0@gmail.com | URL: www.shaunreed.com ##
##############################################################################
*/
#ifndef PANEL_DEVICE_H #ifndef PANEL_DEVICE_H
#define PANEL_DEVICE_H #define PANEL_DEVICE_H
@@ -10,10 +17,131 @@
#include "i2c.h" #include "i2c.h"
// LVGL reserves 2x4 bytes in the buffer to be used as a palette.
// This additional space must be added to the IPanelDevice::buf_size_.
#define LVGL_PALETTE_SIZE 8 #define LVGL_PALETTE_SIZE 8
#define LVGL_TICK_PERIOD_MS 5
#define LVGL_TASK_STACK_SIZE (4 * 1024)
#define LVGL_TASK_PRIORITY 2
#define LCD_H_RES 128
#define LCD_V_RES 64
/**
* Wraps some foundational operations performed on pixel coordinates when
* dealing with pointer arithmetic. Most of these could be done ad-hoc as needed
* but using this helper reduces the risk of errors.
*/
struct Pixel {
/**
* Calculate byte offset for the pixel at [x,y] within a horizontally-mapped
* monochrome uint8 draw buffer, using the initialized horizontal resolution.
*
* We use `>> 3` because each pixel requires 1 bit, but each uint8 in the draw
* buffer can hold 8 bits. To find the uint8 value in our draw buffer that
* stores this pixel's value we must compensate for this when using pixel
* coordinates in byte math.
*
* Therefore, each uint8 in the draw buffer stores the state of 8 pixels.
* Below is an example of calculating for [x, y] pixel coordinates [20, 10].
*
* For the horizontal case, each row (y_) of the image is represented by
* `hor_res_ >> 3` bytes (16). The byte-offset of the first pixel in the 10th
* row for example is `16 * 10` = 160.
*
* Since the pixels are stored horizontally we must calculate the 20th pixel
* column (x_) as `160 + (20 >> 3)`, or `160 + (20 / 8)` to get a final offset
* of 162.
*
* @param x X pixel coordinate to find byte offset.
* @param y Y pixel coordinate to find byte offset.
* @return byte offset for a single-byte monochrome pixel at [x,y].
*/
[[maybe_unused]] [[nodiscard]] static ptrdiff_t
horizontal_byte_offset(const int32_t &x, const int32_t &y, const int32_t& hor_res)
{
// Convert pixel (bit) coordinates to byte coordinates in the draw buffer.
return (hor_res >> 3) * y + (x >> 3);
}
/**
* Calculate byte offset for the pixel at [x,y] within a vertically-mapped
* monochrome uint8 draw buffer, using the initialized horizontal resolution.
*
* We use `>> 3` because each pixel requires 1 bit, but each uint8 in the draw
* buffer can hold 8 bits. To find the uint8 value in our draw buffer that
* stores this pixel's value we must compensate for this when using pixel
* coordinates in byte math.
*
* Therefore, each uint8 in the draw buffer stores the state of 8 pixels.
* Below is an example of calculating for [x, y] pixel coordinates [20, 10].
*
* For the vertical case, each row (y_) of the image is represented by
* `hor_res_` bytes (128) - one for each column (x_). Because the pixels are
* stored vertically, the byte-offset of the first pixel in the 10th row is
* `128 * (10 >> 3)` or * `128 * (10 / 8)` = 128.
*
* From this location we can simply calculate the 20th pixel column (x_) as
* `128 + 20` to get a final offset of 148, because the pixels are stored in a
* columnar format.
*
* @param x X pixel coordinate to find byte offset.
* @param y Y pixel coordinate to find byte offset.
* @return byte offset for a single-byte monochrome pixel at [x,y].
*/
[[maybe_unused]] [[nodiscard]] static ptrdiff_t
vertical_byte_offset(const int32_t &x, const int32_t &y, const int32_t& hor_res)
{
// Convert pixel (bit) coordinates to byte coordinates in the draw buffer.
return hor_res * (y >> 3) + x;
}
/**
* Finds the Most Significant Bit location of bit `i` in a byte.
*
* MSB LSB
* bits 7 6 5 4 3 2 1 0
* data 8 7 6 5 4 3 2 1
* Left Right
*
* @return bitmask for MSB location of `i`.
*/
[[maybe_unused]] [[nodiscard]] static uint8_t
msb_mask(const int32_t &i) { return 1 << (7 - i % 8); }
/**
* Finds the Least Significant Bit location of bit `i` in a byte.
*
* LSB MSB
* bits 0 1 2 3 4 5 6 7
* data 1 2 3 4 5 6 7 8
* Left Right
*
* @return bitmask for LSB location of `i`.
*/
[[maybe_unused]] [[nodiscard]] static uint8_t
lsb_mask(const int32_t &i) { return 1 << (i % 8); }
};
/**
* Encapsulates vendor specific ESP LCD panel initialization logic.
* This pure virtual interface can be inherited from for using new LCD devices.
* See SSD1306 as an example to implement IPanelDevice for NT35510 or ST7789.
*
* At this time only I2C is supported.
* Classes that inherit from this interface should likely be marked final.
*/
class IPanelDevice { class IPanelDevice {
public: public:
/**
* Construct an IPanelDevice.
*
* @param i2c I2C object. Eventually this will mature to IProtocol or similar.
* @param config I2C configuration for this device.
* @param height Height of the device screen in pixels.
* @param width Width of the device screen in pixels.
*/
explicit IPanelDevice(I2C &i2c, explicit IPanelDevice(I2C &i2c,
esp_lcd_panel_io_i2c_config_t config, esp_lcd_panel_io_i2c_config_t config,
int width, int width,
@@ -21,6 +149,15 @@ public:
IPanelDevice(i2c, config, width, height, IPanelDevice(i2c, config, width, height,
width * height / 8 + LVGL_PALETTE_SIZE) { } width * height / 8 + LVGL_PALETTE_SIZE) { }
/**
* Construct an IPanelDevice.
*
* @param i2c I2C object. Eventually this will mature to IProtocol or similar.
* @param config I2C configuration for this device.
* @param height Height of the device screen in pixels.
* @param width Width of the device screen in pixels.
* @param draw_buf_size Size of the draw buffer for this device.
*/
explicit IPanelDevice(I2C &i2c, explicit IPanelDevice(I2C &i2c,
esp_lcd_panel_io_i2c_config_t io_config, esp_lcd_panel_io_i2c_config_t io_config,
int width, int width,
@@ -30,11 +167,18 @@ public:
height_(height), height_(height),
rst_num_(i2c.rst_num_), rst_num_(i2c.rst_num_),
lv_buf_size_(draw_buf_size), lv_buf_size_(draw_buf_size),
esp_i2c_bus_(i2c.esp_i2c_bus_),
esp_io_config_(io_config) { } esp_io_config_(io_config) { }
virtual ~IPanelDevice() = default; virtual ~IPanelDevice() = default;
//
// PUBLIC METHODS
/**
* Create an LVGL display using the width and height of this device.
*
* @return Handle to the created LVGL display.
*/
[[nodiscard]] lv_display_t *create_display() const [[nodiscard]] lv_display_t *create_display() const
{ {
auto display = lv_display_create(width_, height_); auto display = lv_display_create(width_, height_);
@@ -42,15 +186,28 @@ public:
return display; return display;
} }
/**
* Create an ESP LCD panel IO handle.
*
* @return The created ESP LCD panel IO handle.
*/
[[nodiscard]] esp_lcd_panel_io_handle_t create_io_handle() [[nodiscard]] esp_lcd_panel_io_handle_t create_io_handle()
{ {
ESP_LOGI(TAG, "Creating panel IO handle"); ESP_LOGI(TAG, "Creating panel IO handle");
esp_lcd_panel_io_handle_t handle = nullptr; esp_lcd_panel_io_handle_t handle = nullptr;
ESP_ERROR_CHECK( ESP_ERROR_CHECK(
esp_lcd_new_panel_io_i2c(esp_i2c_bus_, &esp_io_config_, &handle)); esp_lcd_new_panel_io_i2c(I2C::get(), &esp_io_config_, &handle));
return handle; return handle;
} }
/**
* Create and initialize an ESP panel handle.
* IPanelDevice implementors must initialize the panel within init_panel.
*
* @param config ESP LCD panel configuration.
* @param io ESP LCD panel IO handle.
* @param [out] panel ESP LCD panel handle output pointer location.
*/
void create_panel(esp_lcd_panel_dev_config_t &config, void create_panel(esp_lcd_panel_dev_config_t &config,
esp_lcd_panel_io_handle_t io, esp_lcd_panel_io_handle_t io,
esp_lcd_panel_handle_t &panel) esp_lcd_panel_handle_t &panel)
@@ -61,29 +218,211 @@ public:
esp_lcd_panel_del(panel); esp_lcd_panel_del(panel);
} }
ESP_LOGI(TAG, "Install SSD1306 panel driver"); ESP_LOGI(TAG, "Installing vendor panel driver");
// Call pure virtual method responsible for initializing the panel handle.
init_panel(config, io, panel); init_panel(config, io, panel);
} }
/**
* Retrieve the device specific vendor configuration structure.
*
* @return Address of vendor configuration structure.
* @sa SSD1306::vendor_config
*/
virtual void *vendor_config() = 0; virtual void *vendor_config() = 0;
//
// PUBLIC MEMBERS
/// Width of the device screen in pixels.
int32_t width_; int32_t width_;
/// Height of the device screen in pixels.
int32_t height_; int32_t height_;
/// RST GPIO pin number.
int rst_num_; int rst_num_;
// LVGL reserves 2x4 bytes in the buffer to be used as a palette. /// LVGL draw buffer size for the device.
size_t lv_buf_size_; size_t lv_buf_size_;
i2c_master_bus_handle_t esp_i2c_bus_; /// ESP LCD panel IO configuration.
esp_lcd_panel_io_i2c_config_t esp_io_config_; esp_lcd_panel_io_i2c_config_t esp_io_config_;
/**
* Registers LVGL draw buffers and callbacks for this display.
*
* An implementation of the interface can optionally override this method to
* provide custom LVGL callbacks and display configurations.
*
* @param display_handle LVGL display handle to use for rendering.
* @param io_handle IO handle for the ESP LCD panel.
*/
virtual void register_rendering_data(lv_display_t *display_handle,
esp_lcd_panel_io_handle_t io_handle);
/**
* Registers LVGL ticker timer callback for rendering this display.
*
* An implementation of the interface can optionally override this method to
* provide custom LVGL callbacks and tick configurations.
*/
virtual void register_lvgl_tick_timer();
protected:
/**
* Static accessor to a static buffer to store draw buffer data for the panel.
*
* This method is protected to allow an implementation to provide a custom
* callback method similar to IPanelDevice::lvgl_flush_cb.
*
* The buffer is allocated statically within the scope of this function to
* allow creating multiple panels that _each_ manage their own statically
* allocated draw buffer data. This simplifies implementing the interface by
* taking this responsibility off of the implementor. The buffer will only be
* allocated if this method is called, so the memory is only used if required.
*
* @return Pointer to uint8 draw buffer data.
* @sa register_rendering_data for overriding LVGL rendering callbacks.
*/
static uint8_t *get_additional_draw_buffer()
{
// Static to the scope of this function, not the compilation unit.
// For LV_COLOR_FORMAT_I1 we need an extra buffer to hold converted data.
static uint8_t oled_buffer[LCD_H_RES * LCD_V_RES / 8];
return oled_buffer;
}
private: private:
//
// PRIVATE METHODS
/**
* Initializes the ESP panel using vendor specific APIs and configurations.
* This method should implement any setup logic specific to the device.
*
* @param config ESP LCD panel configuration.
* @param io ESP LCD panel IO handle.
* @param [out] panel ESP LCD panel handle output pointer location.
*/
virtual void init_panel(esp_lcd_panel_dev_config_t &config, virtual void init_panel(esp_lcd_panel_dev_config_t &config,
esp_lcd_panel_io_handle_t io, esp_lcd_panel_io_handle_t io,
esp_lcd_panel_handle_t &panel) = 0; esp_lcd_panel_handle_t &panel) = 0;
//
// PRIVATE STATIC METHODS
/**
* The callback invoked when panel IO finishes transferring color data.
* This signals that the panel is ready to flush image data to the display.
*
* @param panel LCD panel IO handles.
* @param data Panel IO event data, fed by driver.
* @param user_ctx User data, passed from `esp_lcd_panel_io_xxx_config_t`.
* @return Whether a high priority task has been waken up by this function.
* @sa SSD1306::SSD1306 for setting user_ctx data passed to the callback.
* @sa register_rendering_data for overriding this callback.
*/
static bool lvgl_flush_ready_cb(esp_lcd_panel_io_handle_t panel,
esp_lcd_panel_io_event_data_t *data,
void *user_ctx);
/**
* The callback invoked for flushing the rendered image to the display.
*
* `px_map` contains the rendered image as raw pixel map and it should be
* copied to `area` on the display.
*
* The following details are crucial for understanding the logic surrounding
* flushing to the display in this example.
*
* The order of bits within the px_map from _LVGL_ is MSB first.
* MSB LSB
* bits 7 6 5 4 3 2 1 0
* pixels 0 1 2 3 4 5 6 7
* Left Right
*
* The bytes from _LVGL_ are mapped to pixel rows of the display
* 8 bits (pixels) per byte -
* [0, 0, 0, 0, 0, 0, 0, 0]
* [0, 0, 0, 0, 0, 0, 0, 0]
* [0, 0, 0, 0, 0, 0, 0, 0]
*
* The order of bits expected by the _display driver_ is LSB first.
* We must preserve pairing of each bit and pixel when writing to the display.
* LSB MSB
* bits 0 1 2 3 4 5 6 7
* pixels 7 6 5 4 3 2 1 0
* Left Right
*
* Bytes expected by the _display driver_ map to pixel columns of the display.
* 8 bits (pixels) per byte -
* [0, [0, [0, [0,
* 0, 0, 0, 0,
* 0, 0, 0, 0,
* 0, 0, 0, 0,
* 0, 0, 0, 0,
* 0, 0, 0, 0,
* 0, 0, 0, 0,
* 0] 0] 0] 0]
*
* These layouts in memory have no opinion on the shape of the image. The
* beginning and end of a row or a column for example is entirely dependent
* on how the data is accessed. The vertical and horitzontal resolution may
* vary between displays.
*
* For the LV_COLOR_FORMAT_I1 color format we are using, an additional buffer
* is needed for transposing the bits to the vertical arrangement required by
* the display driver that is outlined above.
*
* This callback implementation is an example of handling this transposition
* and flushing the data to the display in the expected format.
*
* @param display LVGL display handle to use for rendering.
* @param area Area of the display being flushed.
* @param px_map Rendered image data for writing to the display area.
* @sa register_rendering_data for overriding this callback.
* @sa get_additional_draw_buffer
*/
static void lvgl_flush_cb(lv_display_t *display,
const lv_area_t *area,
uint8_t *px_map);
/**
* Callback invoked for every period of the timer.
*
* This callback _must_ call lv_tick_inc to inform LVGL how much time has
* elapsed since the last period of the timer.
*
* @param data User data passed to the callback.
* @sa register_lvgl_tick_timer for setting user data and the tick period of
* the timer, or overriding this callback entirely.
*/
static void lvgl_increase_tick_cb(void *data);
/**
* FreeRTOS task callback invoked for handling LVGL events or updating the UI.
*
* This function is intentionally an endless loop and should never return.
* LVGL initialization logic can optionally be added before entering the loop.
* Input logic can optionally be handled within the loop.
*
* This callback _must_ call lv_timer_handler to handle LVGL periodic timers.
*
* @param data User data passed to the callback.
* @sa register_lvgl_tick_timer for overriding this callback.
*/
[[noreturn]] static void lvgl_port_task(void *data);
//
// PRIVATE MEMBERS
/// LVGL draw buffer associated with this Display's lv_display_t.
void *lv_buf_;
/// Tag used for ESP logging.
constexpr static const char *TAG = "IPanelDevice";
}; };
#endif // PANEL_DEVICE_H #endif // PANEL_DEVICE_H

View File

@@ -0,0 +1,12 @@
/*#############################################################################
## Author: Shaun Reed ##
## Legal: All Content (c) 2025 Shaun Reed, all rights reserved ##
## ##
## Contact: shaunrd0@gmail.com | URL: www.shaunreed.com ##
##############################################################################
*/
#include "scoped_lock.h"
// LVGL library is not thread-safe, this example calls LVGL APIs from tasks.
// We must use a mutex to protect it.
_lock_t ScopedLock::lv_lock_;

View File

@@ -0,0 +1,28 @@
/*#############################################################################
## Author: Shaun Reed ##
## Legal: All Content (c) 2025 Shaun Reed, all rights reserved ##
## ##
## Contact: shaunrd0@gmail.com | URL: www.shaunreed.com ##
##############################################################################
*/
#ifndef SCOPED_LOCK_H
#define SCOPED_LOCK_H
#include <mutex>
/**
* Obtains LVGL API mutex lock for the duration of local scope.
*
* LVGL library is not thread-safe, this lock should be held when making calls
* to the LVGL API, and released as soon as possible when finished.
*/
struct ScopedLock {
explicit ScopedLock() { _lock_acquire(&lv_lock_); }
~ScopedLock() { _lock_release(&lv_lock_); }
/// Mutex used to protect LVGL API calls.
static _lock_t lv_lock_;
};
#endif // SCOPED_LOCK_H

View File

@@ -1,6 +0,0 @@
#include "ssd1306.h"
// To use LV_COLOR_FORMAT_I1 we need an extra buffer to hold the converted data.
// TODO: Remove this and SSD1306 can be header only.
uint8_t SSD1306::oled_buffer_[LCD_H_RES * LCD_V_RES / 8];

View File

@@ -1,16 +1,10 @@
/* /*#############################################################################
* https://docs.espressif.com/projects/esp-idf/en/v5.3.2/esp32/api-reference/peripherals/lcd/index.html#functional-overview ## Author: Shaun Reed ##
* ## Legal: All Content (c) 2025 Shaun Reed, all rights reserved ##
* Implementing the interface draw to an LCD using various interface modes. ## ##
* I2C interface mode is SSD1306 ## Contact: shaunrd0@gmail.com | URL: www.shaunreed.com ##
* SPI interface mode is ST7789 ##############################################################################
* I80 interface mode is NT35510 or ST7789 */
*
* Actually, I think any driver can be used with any interface mode
* Along with additional third party drivers via the component manager
* https://github.com/espressif/esp-idf/tree/0d6099ec533c4b647fb7a7b0b8942bc7aeb82f90/examples/peripherals/lcd/spi_lcd_touch#spi-lcd-and-touch-panel-example
*/
#ifndef SSD1306_H #ifndef SSD1306_H
#define SSD1306_H #define SSD1306_H
@@ -25,20 +19,33 @@
// According to SSD1306 datasheet. // According to SSD1306 datasheet.
// https://cdn-shop.adafruit.com/datasheets/SSD1306.pdf // https://cdn-shop.adafruit.com/datasheets/SSD1306.pdf
#define LCD_H_RES 128
#define LCD_V_RES 64
#define I2C_HW_ADDR 0x3C #define I2C_HW_ADDR 0x3C
#define LCD_PIXEL_CLOCK_HZ (400 * 1000) #define LCD_PIXEL_CLOCK_HZ (400 * 1000)
// Bit number used to represent command and parameter // Bit number used to represent command and parameter
#define LCD_CMD_BITS 8 #define LCD_CMD_BITS 8
#define LCD_PARAM_BITS 8 #define LCD_PARAM_BITS 8
/**
* Example of implementing the IPanelDevice interface for SSD1306 LCD device.
*/
class SSD1306 final : public IPanelDevice { class SSD1306 final : public IPanelDevice {
public: public:
// Constructors allow overriding ssd1306 config. /**
* Construct a new SSD1306 device.
*
* @param i2c I2C master bus to manage this device.
*/
explicit SSD1306(I2C &i2c) : explicit SSD1306(I2C &i2c) :
SSD1306(i2c, {.height = SCREEN_HEIGHT}) { } SSD1306(i2c, {.height = SCREEN_HEIGHT}) { }
/**
* Construct a new SSD1306 device given a specific SSD1306 configuration.
*
* @param i2c I2C master bus to manage this device.
* @param config SSD1306 vendor configuration.
* @param width Width of the device screen in pixels.
* @param height Height of the device screen in pixels.
*/
SSD1306(I2C &i2c, SSD1306(I2C &i2c,
esp_lcd_panel_ssd1306_config_t config, esp_lcd_panel_ssd1306_config_t config,
int width = SCREEN_WIDTH, int width = SCREEN_WIDTH,
@@ -47,6 +54,9 @@ public:
IPanelDevice(i2c, IPanelDevice(i2c,
(esp_lcd_panel_io_i2c_config_t) { (esp_lcd_panel_io_i2c_config_t) {
.dev_addr = I2C_HW_ADDR, .dev_addr = I2C_HW_ADDR,
// User data to pass to the LVGL flush_ready callback.
// See IPanelDevice::lvgl_flush_ready_cb
.user_ctx = nullptr,
.control_phase_bytes = 1, .control_phase_bytes = 1,
.dc_bit_offset = 6, .dc_bit_offset = 6,
.lcd_cmd_bits = LCD_CMD_BITS, .lcd_cmd_bits = LCD_CMD_BITS,
@@ -60,18 +70,31 @@ public:
~SSD1306() final = default; ~SSD1306() final = default;
//
// PUBLIC METHODS
/**
* Provides the SSD1306 vendor configuration to IPanelDevice consumers.
*
* @return Address of the SSD1306 vendor configuration structure.
*/
void *vendor_config() override void *vendor_config() override
{ {
return &ssd1306_config_; return &ssd1306_config_;
} }
// The configuration structure specific to the SSD1306. //
// PUBLIC MEMBERS
/// SSD1306 configuration structure.
esp_lcd_panel_ssd1306_config_t ssd1306_config_; esp_lcd_panel_ssd1306_config_t ssd1306_config_;
// For LV_COLOR_FORMAT_I1 we need an extra buffer to hold the converted data.
static uint8_t oled_buffer_[LCD_H_RES * LCD_V_RES / 8];
private: private:
//
// PRIVATE METHODS
/// Initializes the ESP LCD panel handle for the SSD1306 device.
void init_panel(esp_lcd_panel_dev_config_t &config, void init_panel(esp_lcd_panel_dev_config_t &config,
esp_lcd_panel_io_handle_t io, esp_lcd_panel_io_handle_t io,
esp_lcd_panel_handle_t &panel) override esp_lcd_panel_handle_t &panel) override

View File

@@ -1,4 +1,10 @@
/*#############################################################################
## Author: Shaun Reed ##
## Legal: All Content (c) 2025 Shaun Reed, all rights reserved ##
## ##
## Contact: shaunrd0@gmail.com | URL: www.shaunreed.com ##
##############################################################################
*/
#ifndef TIME_KEEPER_H #ifndef TIME_KEEPER_H
#define TIME_KEEPER_H #define TIME_KEEPER_H
@@ -12,35 +18,45 @@
* In general Timers should be used via the TimeKeeper interface only. * In general Timers should be used via the TimeKeeper interface only.
* *
* Timers cannot be copied, and are only created by a TimeKeeper instance. * Timers cannot be copied, and are only created by a TimeKeeper instance.
* The public way to access a Timer is by obtaining a TimerHandle (Timer *).
* The TimeKeeper can delete existing Timers, calling it's destructor. * The TimeKeeper can delete existing Timers, calling it's destructor.
* The ESP timer will be deleted when this class desctructor is called. * The ESP timer will be deleted when this class desctructor is called.
*/ */
struct Timer { struct Timer {
explicit Timer(esp_timer_create_args_t args) :
args_(args), esp_timer_(nullptr)
{
ESP_LOGI(TAG, "Creating esp_timer with name: '%s'", args_.name);
ESP_ERROR_CHECK(esp_timer_create(&args, &esp_timer_));
}
~Timer()
{
ESP_LOGI(TAG, "Destroying esp_timer with name: '%s'", args_.name);
ESP_ERROR_CHECK(esp_timer_delete(esp_timer_));
}
Timer(const Timer &) = delete; Timer(const Timer &) = delete;
Timer(Timer &) = delete; Timer(Timer &) = delete;
Timer &operator=(Timer &) = delete; Timer &operator=(Timer &) = delete;
explicit Timer(esp_timer_create_args_t args) : //
args_(args), esp_timer_(nullptr) // PUBLIC MEMBERS
{
ESP_LOGI(TAG, "Creating esp_timer with name: %s", args_.name);
ESP_ERROR_CHECK(esp_timer_create(&args, &esp_timer_));
}
~Timer()
{
ESP_LOGI(TAG, "Destroying esp_timer with name: %s", args_.name);
ESP_ERROR_CHECK(esp_timer_delete(esp_timer_));
}
/// Arguments passed to ESP API during timer creation. /// Arguments passed to ESP API during timer creation.
esp_timer_create_args_t args_; esp_timer_create_args_t args_;
/// ESP timer handle. /// ESP timer handle.
esp_timer_handle_t esp_timer_; esp_timer_handle_t esp_timer_;
private:
//
// PRIVATE MEMBERS
/// Tag used for ESP logging.
constexpr static const char *TAG = "Timer";
}; };
/** /**
@@ -53,6 +69,9 @@ struct TimeKeeper {
/// Timer handle type used for referring to Timers. /// Timer handle type used for referring to Timers.
using TimerHandle = Timer *; using TimerHandle = Timer *;
//
// GETTERS
TimerHandle get_handle(const char *name) TimerHandle get_handle(const char *name)
{ {
return &managed_timers_.at(name); return &managed_timers_.at(name);
@@ -60,6 +79,9 @@ struct TimeKeeper {
TimerHandle operator[](const char *name) { return get_handle(name); } TimerHandle operator[](const char *name) { return get_handle(name); }
//
// PUBLIC METHODS
/** /**
* Create a new managed Timer with the provided ESP arguments. * Create a new managed Timer with the provided ESP arguments.
* The timer can be retrieved later using the args.name field value. * The timer can be retrieved later using the args.name field value.
@@ -69,11 +91,11 @@ struct TimeKeeper {
* @sa get_handle * @sa get_handle
* @sa operator[](const char*) * @sa operator[](const char*)
*/ */
TimerHandle create_timer(esp_timer_create_args_t args) [[maybe_unused]] TimerHandle create_timer(esp_timer_create_args_t args)
{ {
auto rt = managed_timers_.emplace(args.name, args); auto rt = managed_timers_.emplace(args.name, args);
if (!rt.second) { if (!rt.second) {
ESP_LOGE(TAG, "Display::Timer already exists with name %s", args.name); ESP_LOGE(TAG, "Timer already exists with name '%s'", args.name);
return nullptr; return nullptr;
} }
return &rt.first->second; return &rt.first->second;
@@ -88,7 +110,9 @@ struct TimeKeeper {
/// Delete a Timer with the given name. /// Delete a Timer with the given name.
[[maybe_unused]] void delete_timer(const char *name) [[maybe_unused]] void delete_timer(const char *name)
{ {
managed_timers_.erase(name); if (managed_timers_.erase(name) == 0) {
ESP_LOGE(TAG, "Attempt to delete timer that does not exist: '%s'", name);
}
} }
/// Create a Timer with the ESP args and call esp_timer_start_periodic. /// Create a Timer with the ESP args and call esp_timer_start_periodic.
@@ -108,9 +132,8 @@ struct TimeKeeper {
} }
/// Create a Timer with the ESP args and call esp_timer_start_once. /// Create a Timer with the ESP args and call esp_timer_start_once.
[[maybe_unused]] void [[maybe_unused]] void start_new_timer_once(esp_timer_create_args_t args,
start_new_timer_once(esp_timer_create_args_t args, uint64_t timeout_us)
uint64_t timeout_us)
{ {
start_timer_once(create_timer(args)->args_.name, timeout_us); start_timer_once(create_timer(args)->args_.name, timeout_us);
} }
@@ -124,8 +147,15 @@ struct TimeKeeper {
} }
private: private:
//
// PRIVATE MEMBERS
/// Existing ESP timers created for this TimeKeeper instance. /// Existing ESP timers created for this TimeKeeper instance.
std::unordered_map<const char *, Timer> managed_timers_; std::unordered_map<const char *, Timer> managed_timers_;
/// Tag used for ESP logging.
constexpr static const char *TAG = "TimeKeeper";
}; };
#endif // TIME_KEEPER_H #endif // TIME_KEEPER_H

View File

@@ -2091,7 +2091,15 @@ CONFIG_MDNS_TASK_STACK_SIZE=4096
CONFIG_MDNS_TASK_AFFINITY_CPU0=y CONFIG_MDNS_TASK_AFFINITY_CPU0=y
# CONFIG_MDNS_TASK_AFFINITY_CPU1 is not set # CONFIG_MDNS_TASK_AFFINITY_CPU1 is not set
CONFIG_MDNS_TASK_AFFINITY=0x0 CONFIG_MDNS_TASK_AFFINITY=0x0
#
# MDNS Memory Configuration
#
CONFIG_MDNS_TASK_CREATE_FROM_INTERNAL=y CONFIG_MDNS_TASK_CREATE_FROM_INTERNAL=y
CONFIG_MDNS_MEMORY_ALLOC_INTERNAL=y
# CONFIG_MDNS_MEMORY_CUSTOM_IMPL is not set
# end of MDNS Memory Configuration
CONFIG_MDNS_SERVICE_ADD_TIMEOUT_MS=2000 CONFIG_MDNS_SERVICE_ADD_TIMEOUT_MS=2000
CONFIG_MDNS_TIMER_PERIOD_MS=100 CONFIG_MDNS_TIMER_PERIOD_MS=100
# CONFIG_MDNS_NETWORKING_SOCKET is not set # CONFIG_MDNS_NETWORKING_SOCKET is not set

View File

@@ -8,6 +8,7 @@ shaunrd0/klips/esp/
├── 04_esp-idf-arduino # CMake example instead of Arduino IDE for ESP development. ├── 04_esp-idf-arduino # CMake example instead of Arduino IDE for ESP development.
├── 05_temp-humidity-web # Temperature and humidity sensor within a web browser. ├── 05_temp-humidity-web # Temperature and humidity sensor within a web browser.
├── 06_i2c-scanner # Simple I2C device scanner. ├── 06_i2c-scanner # Simple I2C device scanner.
├── 07_lcd-panel-i2c # Drawing to a LCD display with LVGL over I2C.
├── ESP32-basic-starter-kit.pdf # PDF for tutorials in ESP32 starter kit. ├── ESP32-basic-starter-kit.pdf # PDF for tutorials in ESP32 starter kit.
├── ESP32-dev-module.png ├── ESP32-dev-module.png
└── README.md └── README.md