1
0
mirror of https://github.com/esphome/esphome.git synced 2025-10-29 22:24:26 +00:00

[qspi_dbi] Rename from qspi_amoled, add features (#7594)

Co-authored-by: clydeps <U5yx99dok9>
This commit is contained in:
Clyde Stubbs
2024-10-16 14:26:50 +11:00
committed by GitHub
parent 6a86d92781
commit 254522dd93
12 changed files with 385 additions and 207 deletions

View File

@@ -0,0 +1 @@
CODEOWNERS = ["@clydebarrow"]

View File

@@ -0,0 +1,185 @@
from esphome import pins
import esphome.codegen as cg
from esphome.components import display, spi
import esphome.config_validation as cv
from esphome.const import (
CONF_BRIGHTNESS,
CONF_COLOR_ORDER,
CONF_DIMENSIONS,
CONF_ENABLE_PIN,
CONF_HEIGHT,
CONF_ID,
CONF_INIT_SEQUENCE,
CONF_INVERT_COLORS,
CONF_LAMBDA,
CONF_MIRROR_X,
CONF_MIRROR_Y,
CONF_MODEL,
CONF_OFFSET_HEIGHT,
CONF_OFFSET_WIDTH,
CONF_RESET_PIN,
CONF_SWAP_XY,
CONF_TRANSFORM,
CONF_WIDTH,
)
from esphome.core import TimePeriod
from .models import DriverChip
DEPENDENCIES = ["spi"]
qspi_dbi_ns = cg.esphome_ns.namespace("qspi_dbi")
QSPI_DBI = qspi_dbi_ns.class_(
"QspiDbi", display.Display, display.DisplayBuffer, cg.Component, spi.SPIDevice
)
ColorOrder = display.display_ns.enum("ColorMode")
Model = qspi_dbi_ns.enum("Model")
COLOR_ORDERS = {
"RGB": ColorOrder.COLOR_ORDER_RGB,
"BGR": ColorOrder.COLOR_ORDER_BGR,
}
DATA_PIN_SCHEMA = pins.internal_gpio_output_pin_schema
CONF_DRAW_FROM_ORIGIN = "draw_from_origin"
DELAY_FLAG = 0xFF
def validate_dimension(value):
value = cv.positive_int(value)
if value % 2 != 0:
raise cv.Invalid("Width/height/offset must be divisible by 2")
return value
def map_sequence(value):
"""
The format is a repeated sequence of [CMD, <data>] where <data> is s a sequence of bytes. The length is inferred
from the length of the sequence and should not be explicit.
A delay can be inserted by specifying "- delay N" where N is in ms
"""
if isinstance(value, str) and value.lower().startswith("delay "):
value = value.lower()[6:]
delay = cv.All(
cv.positive_time_period_milliseconds,
cv.Range(TimePeriod(milliseconds=1), TimePeriod(milliseconds=255)),
)(value)
return [delay, DELAY_FLAG]
value = cv.Length(min=1, max=254)(value)
params = value[1:]
return [value[0], len(params)] + list(params)
def _validate(config):
chip = DriverChip.chips[config[CONF_MODEL]]
if not chip.initsequence:
if CONF_INIT_SEQUENCE not in config:
raise cv.Invalid(f"{chip.name} model requires init_sequence")
return config
CONFIG_SCHEMA = cv.All(
display.FULL_DISPLAY_SCHEMA.extend(
cv.Schema(
{
cv.GenerateID(): cv.declare_id(QSPI_DBI),
cv.Required(CONF_MODEL): cv.one_of(
*DriverChip.chips.keys(), upper=True
),
cv.Optional(CONF_INIT_SEQUENCE): cv.ensure_list(map_sequence),
cv.Required(CONF_DIMENSIONS): cv.Any(
cv.dimensions,
cv.Schema(
{
cv.Required(CONF_WIDTH): validate_dimension,
cv.Required(CONF_HEIGHT): validate_dimension,
cv.Optional(
CONF_OFFSET_HEIGHT, default=0
): validate_dimension,
cv.Optional(
CONF_OFFSET_WIDTH, default=0
): validate_dimension,
}
),
),
cv.Optional(CONF_TRANSFORM): cv.Schema(
{
cv.Optional(CONF_MIRROR_X, default=False): cv.boolean,
cv.Optional(CONF_MIRROR_Y, default=False): cv.boolean,
cv.Optional(CONF_SWAP_XY, default=False): cv.boolean,
}
),
cv.Optional(CONF_COLOR_ORDER, default="RGB"): cv.enum(
COLOR_ORDERS, upper=True
),
cv.Optional(CONF_INVERT_COLORS, default=False): cv.boolean,
cv.Optional(CONF_RESET_PIN): pins.gpio_output_pin_schema,
cv.Optional(CONF_ENABLE_PIN): pins.gpio_output_pin_schema,
cv.Optional(CONF_BRIGHTNESS, default=0xD0): cv.int_range(
0, 0xFF, min_included=True, max_included=True
),
cv.Optional(CONF_DRAW_FROM_ORIGIN, default=False): cv.boolean,
}
).extend(
spi.spi_device_schema(
cs_pin_required=False,
default_mode="MODE0",
default_data_rate=10e6,
quad=True,
)
)
),
cv.only_with_esp_idf,
)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
await display.register_display(var, config)
await spi.register_spi_device(var, config)
chip = DriverChip.chips[config[CONF_MODEL]]
if chip.initsequence:
cg.add(var.add_init_sequence(chip.initsequence))
if init_sequences := config.get(CONF_INIT_SEQUENCE):
sequence = []
for seq in init_sequences:
sequence.extend(seq)
cg.add(var.add_init_sequence(sequence))
cg.add(var.set_color_mode(config[CONF_COLOR_ORDER]))
cg.add(var.set_invert_colors(config[CONF_INVERT_COLORS]))
cg.add(var.set_brightness(config[CONF_BRIGHTNESS]))
cg.add(var.set_model(config[CONF_MODEL]))
cg.add(var.set_draw_from_origin(config[CONF_DRAW_FROM_ORIGIN]))
if enable_pin := config.get(CONF_ENABLE_PIN):
enable = await cg.gpio_pin_expression(enable_pin)
cg.add(var.set_enable_pin(enable))
if reset_pin := config.get(CONF_RESET_PIN):
reset = await cg.gpio_pin_expression(reset_pin)
cg.add(var.set_reset_pin(reset))
if transform := config.get(CONF_TRANSFORM):
cg.add(var.set_mirror_x(transform[CONF_MIRROR_X]))
cg.add(var.set_mirror_y(transform[CONF_MIRROR_Y]))
cg.add(var.set_swap_xy(transform[CONF_SWAP_XY]))
if CONF_DIMENSIONS in config:
dimensions = config[CONF_DIMENSIONS]
if isinstance(dimensions, dict):
cg.add(var.set_dimensions(dimensions[CONF_WIDTH], dimensions[CONF_HEIGHT]))
cg.add(
var.set_offsets(
dimensions[CONF_OFFSET_WIDTH], dimensions[CONF_OFFSET_HEIGHT]
)
)
else:
(width, height) = dimensions
cg.add(var.set_dimensions(width, height))
if lamb := config.get(CONF_LAMBDA):
lambda_ = await cg.process_lambda(
lamb, [(display.DisplayRef, "it")], return_type=cg.void
)
cg.add(var.set_writer(lambda_))

View File

@@ -0,0 +1,64 @@
# Commands
SW_RESET_CMD = 0x01
SLEEP_OUT = 0x11
INVERT_OFF = 0x20
INVERT_ON = 0x21
ALL_ON = 0x23
WRAM = 0x24
MIPI = 0x26
DISPLAY_OFF = 0x28
DISPLAY_ON = 0x29
RASET = 0x2B
CASET = 0x2A
WDATA = 0x2C
TEON = 0x35
MADCTL_CMD = 0x36
PIXFMT = 0x3A
BRIGHTNESS = 0x51
SWIRE1 = 0x5A
SWIRE2 = 0x5B
PAGESEL = 0xFE
class DriverChip:
chips = {}
def __init__(self, name: str):
name = name.upper()
self.name = name
self.chips[name] = self
self.initsequence = []
def cmd(self, c, *args):
"""
Add a command sequence to the init sequence
:param c: The command (8 bit)
:param args: zero or more arguments (8 bit values)
"""
self.initsequence.extend([c, len(args)] + list(args))
def delay(self, ms):
self.initsequence.extend([ms, 0xFF])
chip = DriverChip("RM67162")
chip.cmd(PIXFMT, 0x55)
chip.cmd(BRIGHTNESS, 0)
chip = DriverChip("RM690B0")
chip.cmd(PAGESEL, 0x20)
chip.cmd(MIPI, 0x0A)
chip.cmd(WRAM, 0x80)
chip.cmd(SWIRE1, 0x51)
chip.cmd(SWIRE2, 0x2E)
chip.cmd(PAGESEL, 0x00)
chip.cmd(0xC2, 0x00)
chip.delay(10)
chip.cmd(TEON, 0x00)
chip = DriverChip("AXS15231")
chip.cmd(0xBB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5A, 0xA5)
chip.cmd(0xC1, 0x33)
chip.cmd(0xBB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
DriverChip("Custom")

View File

@@ -0,0 +1,230 @@
#ifdef USE_ESP_IDF
#include "qspi_dbi.h"
#include "esphome/core/log.h"
namespace esphome {
namespace qspi_dbi {
void QspiDbi::setup() {
ESP_LOGCONFIG(TAG, "Setting up QSPI_DBI");
this->spi_setup();
if (this->enable_pin_ != nullptr) {
this->enable_pin_->setup();
this->enable_pin_->digital_write(true);
}
if (this->reset_pin_ != nullptr) {
this->reset_pin_->setup();
this->reset_pin_->digital_write(true);
delay(5);
this->reset_pin_->digital_write(false);
delay(5);
this->reset_pin_->digital_write(true);
}
this->set_timeout(120, [this] { this->write_command_(SLEEP_OUT); });
this->set_timeout(240, [this] { this->write_init_sequence_(); });
if (this->draw_from_origin_)
check_buffer_();
}
void QspiDbi::update() {
if (!this->setup_complete_) {
return;
}
this->do_update_();
if (this->buffer_ == nullptr || this->x_low_ > this->x_high_ || this->y_low_ > this->y_high_)
return;
// Start addresses and widths/heights must be divisible by 2 (CASET/RASET restriction in datasheet)
if (this->x_low_ % 2 == 1) {
this->x_low_--;
}
if (this->x_high_ % 2 == 0) {
this->x_high_++;
}
if (this->y_low_ % 2 == 1) {
this->y_low_--;
}
if (this->y_high_ % 2 == 0) {
this->y_high_++;
}
if (this->draw_from_origin_) {
this->x_low_ = 0;
this->y_low_ = 0;
this->x_high_ = this->width_ - 1;
}
int w = this->x_high_ - this->x_low_ + 1;
int h = this->y_high_ - this->y_low_ + 1;
this->write_to_display_(this->x_low_, this->y_low_, w, h, this->buffer_, this->x_low_, this->y_low_,
this->width_ - w - this->x_low_);
// invalidate watermarks
this->x_low_ = this->width_;
this->y_low_ = this->height_;
this->x_high_ = 0;
this->y_high_ = 0;
}
void QspiDbi::draw_absolute_pixel_internal(int x, int y, Color color) {
if (x >= this->get_width_internal() || x < 0 || y >= this->get_height_internal() || y < 0) {
return;
}
if (this->is_failed())
return;
check_buffer_();
uint32_t pos = (y * this->width_) + x;
bool updated = false;
pos = pos * 2;
uint16_t new_color = display::ColorUtil::color_to_565(color, display::ColorOrder::COLOR_ORDER_RGB);
if (this->buffer_[pos] != static_cast<uint8_t>(new_color >> 8)) {
this->buffer_[pos] = static_cast<uint8_t>(new_color >> 8);
updated = true;
}
pos = pos + 1;
new_color = new_color & 0xFF;
if (this->buffer_[pos] != new_color) {
this->buffer_[pos] = new_color;
updated = true;
}
if (updated) {
// low and high watermark may speed up drawing from buffer
if (x < this->x_low_)
this->x_low_ = x;
if (y < this->y_low_)
this->y_low_ = y;
if (x > this->x_high_)
this->x_high_ = x;
if (y > this->y_high_)
this->y_high_ = y;
}
}
void QspiDbi::reset_params_(bool ready) {
if (!ready && !this->is_ready())
return;
this->write_command_(this->invert_colors_ ? INVERT_ON : INVERT_OFF);
// custom x/y transform and color order
uint8_t mad = this->color_mode_ == display::COLOR_ORDER_BGR ? MADCTL_BGR : MADCTL_RGB;
if (this->swap_xy_)
mad |= MADCTL_MV;
if (this->mirror_x_)
mad |= MADCTL_MX;
if (this->mirror_y_)
mad |= MADCTL_MY;
this->write_command_(MADCTL_CMD, mad);
this->write_command_(BRIGHTNESS, this->brightness_);
this->write_command_(NORON);
this->write_command_(DISPLAY_ON);
}
void QspiDbi::write_init_sequence_() {
for (const auto &seq : this->init_sequences_) {
this->write_sequence_(seq);
}
this->reset_params_(true);
this->setup_complete_ = true;
ESP_LOGCONFIG(TAG, "QSPI_DBI setup complete");
}
void QspiDbi::set_addr_window_(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2) {
ESP_LOGVV(TAG, "Set addr %d/%d, %d/%d", x1, y1, x2, y2);
uint8_t buf[4];
x1 += this->offset_x_;
x2 += this->offset_x_;
y1 += this->offset_y_;
y2 += this->offset_y_;
put16_be(buf, y1);
put16_be(buf + 2, y2);
this->write_command_(RASET, buf, sizeof buf);
put16_be(buf, x1);
put16_be(buf + 2, x2);
this->write_command_(CASET, buf, sizeof buf);
}
void QspiDbi::draw_pixels_at(int x_start, int y_start, int w, int h, const uint8_t *ptr, display::ColorOrder order,
display::ColorBitness bitness, bool big_endian, int x_offset, int y_offset, int x_pad) {
if (!this->setup_complete_ || this->is_failed())
return;
if (w <= 0 || h <= 0)
return;
if (bitness != display::COLOR_BITNESS_565 || order != this->color_mode_ ||
big_endian != (this->bit_order_ == spi::BIT_ORDER_MSB_FIRST)) {
return Display::draw_pixels_at(x_start, y_start, w, h, ptr, order, bitness, big_endian, x_offset, y_offset, x_pad);
} else if (this->draw_from_origin_) {
auto stride = x_offset + w + x_pad;
for (int y = 0; y != h; y++) {
memcpy(this->buffer_ + ((y + y_start) * this->width_ + x_start) * 2,
ptr + ((y + y_offset) * stride + x_offset) * 2, w * 2);
}
ptr = this->buffer_;
w = this->width_;
h += y_start;
x_start = 0;
y_start = 0;
x_offset = 0;
y_offset = 0;
}
this->write_to_display_(x_start, y_start, w, h, ptr, x_offset, y_offset, x_pad);
}
void QspiDbi::write_to_display_(int x_start, int y_start, int w, int h, const uint8_t *ptr, int x_offset, int y_offset,
int x_pad) {
this->set_addr_window_(x_start, y_start, x_start + w - 1, y_start + h - 1);
this->enable();
// x_ and y_offset are offsets into the source buffer, unrelated to our own offsets into the display.
if (x_offset == 0 && x_pad == 0 && y_offset == 0) {
// we could deal here with a non-zero y_offset, but if x_offset is zero, y_offset probably will be so don't bother
this->write_cmd_addr_data(8, 0x32, 24, 0x2C00, ptr, w * h * 2, 4);
} else {
auto stride = x_offset + w + x_pad;
uint16_t cmd = 0x2C00;
for (int y = 0; y != h; y++) {
this->write_cmd_addr_data(8, 0x32, 24, cmd, ptr + ((y + y_offset) * stride + x_offset) * 2, w * 2, 4);
cmd = 0x3C00;
}
}
this->disable();
}
void QspiDbi::write_command_(uint8_t cmd, const uint8_t *bytes, size_t len) {
ESP_LOGV(TAG, "Command %02X, length %d, bytes %s", cmd, len, format_hex_pretty(bytes, len).c_str());
this->enable();
this->write_cmd_addr_data(8, 0x02, 24, cmd << 8, bytes, len);
this->disable();
}
void QspiDbi::write_sequence_(const std::vector<uint8_t> &vec) {
size_t index = 0;
while (index != vec.size()) {
if (vec.size() - index < 2) {
ESP_LOGE(TAG, "Malformed init sequence");
return;
}
uint8_t cmd = vec[index++];
uint8_t x = vec[index++];
if (x == DELAY_FLAG) {
ESP_LOGV(TAG, "Delay %dms", cmd);
delay(cmd);
} else {
uint8_t num_args = x & 0x7F;
if (vec.size() - index < num_args) {
ESP_LOGE(TAG, "Malformed init sequence");
return;
}
const auto *ptr = vec.data() + index;
this->write_command_(cmd, ptr, num_args);
index += num_args;
}
}
}
void QspiDbi::dump_config() {
ESP_LOGCONFIG("", "QSPI_DBI Display");
ESP_LOGCONFIG("", "Model: %s", this->model_);
ESP_LOGCONFIG(TAG, " Height: %u", this->height_);
ESP_LOGCONFIG(TAG, " Width: %u", this->width_);
LOG_PIN(" CS Pin: ", this->cs_);
LOG_PIN(" Reset Pin: ", this->reset_pin_);
ESP_LOGCONFIG(TAG, " SPI Data rate: %dMHz", (unsigned) (this->data_rate_ / 1000000));
}
} // namespace qspi_dbi
} // namespace esphome
#endif

View File

@@ -0,0 +1,173 @@
//
// Created by Clyde Stubbs on 29/10/2023.
//
#pragma once
#ifdef USE_ESP_IDF
#include "esphome/core/component.h"
#include "esphome/components/spi/spi.h"
#include "esphome/components/display/display.h"
#include "esphome/components/display/display_buffer.h"
#include "esphome/components/display/display_color_utils.h"
#include "esp_lcd_panel_ops.h"
#include "esp_lcd_panel_rgb.h"
namespace esphome {
namespace qspi_dbi {
constexpr static const char *const TAG = "display.qspi_dbi";
static const uint8_t SW_RESET_CMD = 0x01;
static const uint8_t SLEEP_OUT = 0x11;
static const uint8_t NORON = 0x13;
static const uint8_t INVERT_OFF = 0x20;
static const uint8_t INVERT_ON = 0x21;
static const uint8_t ALL_ON = 0x23;
static const uint8_t WRAM = 0x24;
static const uint8_t MIPI = 0x26;
static const uint8_t DISPLAY_ON = 0x29;
static const uint8_t RASET = 0x2B;
static const uint8_t CASET = 0x2A;
static const uint8_t WDATA = 0x2C;
static const uint8_t TEON = 0x35;
static const uint8_t MADCTL_CMD = 0x36;
static const uint8_t PIXFMT = 0x3A;
static const uint8_t BRIGHTNESS = 0x51;
static const uint8_t SWIRE1 = 0x5A;
static const uint8_t SWIRE2 = 0x5B;
static const uint8_t PAGESEL = 0xFE;
static const uint8_t MADCTL_MY = 0x80; ///< Bit 7 Bottom to top
static const uint8_t MADCTL_MX = 0x40; ///< Bit 6 Right to left
static const uint8_t MADCTL_MV = 0x20; ///< Bit 5 Reverse Mode
static const uint8_t MADCTL_RGB = 0x00; ///< Bit 3 Red-Green-Blue pixel order
static const uint8_t MADCTL_BGR = 0x08; ///< Bit 3 Blue-Green-Red pixel order
static const uint8_t DELAY_FLAG = 0xFF;
// store a 16 bit value in a buffer, big endian.
static inline void put16_be(uint8_t *buf, uint16_t value) {
buf[0] = value >> 8;
buf[1] = value;
}
enum Model {
CUSTOM,
RM690B0,
RM67162,
};
class QspiDbi : public display::DisplayBuffer,
public spi::SPIDevice<spi::BIT_ORDER_MSB_FIRST, spi::CLOCK_POLARITY_LOW, spi::CLOCK_PHASE_LEADING,
spi::DATA_RATE_1MHZ> {
public:
void set_model(const char *model) { this->model_ = model; }
void update() override;
void setup() override;
display::ColorOrder get_color_mode() { return this->color_mode_; }
void set_color_mode(display::ColorOrder color_mode) { this->color_mode_ = color_mode; }
void set_reset_pin(GPIOPin *reset_pin) { this->reset_pin_ = reset_pin; }
void set_enable_pin(GPIOPin *enable_pin) { this->enable_pin_ = enable_pin; }
void set_dimensions(uint16_t width, uint16_t height) {
this->width_ = width;
this->height_ = height;
}
void set_invert_colors(bool invert_colors) {
this->invert_colors_ = invert_colors;
this->reset_params_();
}
void set_mirror_x(bool mirror_x) {
this->mirror_x_ = mirror_x;
this->reset_params_();
}
void set_mirror_y(bool mirror_y) {
this->mirror_y_ = mirror_y;
this->reset_params_();
}
void set_swap_xy(bool swap_xy) {
this->swap_xy_ = swap_xy;
this->reset_params_();
}
void set_brightness(uint8_t brightness) {
this->brightness_ = brightness;
this->reset_params_();
}
void set_offsets(int16_t offset_x, int16_t offset_y) {
this->offset_x_ = offset_x;
this->offset_y_ = offset_y;
}
void set_draw_from_origin(bool draw_from_origin) { this->draw_from_origin_ = draw_from_origin; }
display::DisplayType get_display_type() override { return display::DisplayType::DISPLAY_TYPE_COLOR; }
void dump_config() override;
int get_width_internal() override { return this->width_; }
int get_height_internal() override { return this->height_; }
bool can_proceed() override { return this->setup_complete_; }
void add_init_sequence(const std::vector<uint8_t> &sequence) { this->init_sequences_.push_back(sequence); }
protected:
void check_buffer_() {
if (this->buffer_ == nullptr)
this->init_internal_(this->width_ * this->height_ * 2);
}
void write_sequence_(const std::vector<uint8_t> &vec);
void draw_absolute_pixel_internal(int x, int y, Color color) override;
void draw_pixels_at(int x_start, int y_start, int w, int h, const uint8_t *ptr, display::ColorOrder order,
display::ColorBitness bitness, bool big_endian, int x_offset, int y_offset, int x_pad) override;
void write_to_display_(int x_start, int y_start, int w, int h, const uint8_t *ptr, int x_offset, int y_offset,
int x_pad);
/**
* the RM67162 in quad SPI mode seems to work like this (not in the datasheet, this is deduced from the
* sample code.)
*
* Immediately after enabling /CS send 4 bytes in single-dataline SPI mode:
* 0: either 0x2 or 0x32. The first indicates that any subsequent data bytes after the initial 4 will be
* sent in 1-dataline SPI. The second indicates quad mode.
* 1: 0x00
* 2: The command (register address) byte.
* 3: 0x00
*
* This is followed by zero or more data bytes in either 1-wire or 4-wire mode, depending on the first byte.
* At the conclusion of the write, de-assert /CS.
*
* @param cmd
* @param bytes
* @param len
*/
void write_command_(uint8_t cmd, const uint8_t *bytes, size_t len);
void write_command_(uint8_t cmd, uint8_t data) { this->write_command_(cmd, &data, 1); }
void write_command_(uint8_t cmd) { this->write_command_(cmd, &cmd, 0); }
void reset_params_(bool ready = false);
void write_init_sequence_();
void set_addr_window_(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2);
GPIOPin *reset_pin_{nullptr};
GPIOPin *enable_pin_{nullptr};
uint16_t x_low_{1};
uint16_t y_low_{1};
uint16_t x_high_{0};
uint16_t y_high_{0};
bool setup_complete_{};
bool invert_colors_{};
display::ColorOrder color_mode_{display::COLOR_ORDER_BGR};
size_t width_{};
size_t height_{};
int16_t offset_x_{0};
int16_t offset_y_{0};
bool swap_xy_{};
bool mirror_x_{};
bool mirror_y_{};
bool draw_from_origin_{false};
uint8_t brightness_{0xD0};
const char *model_{"Unknown"};
std::vector<std::vector<uint8_t>> init_sequences_{};
esp_lcd_panel_handle_t handle_{};
};
} // namespace qspi_dbi
} // namespace esphome
#endif