New kernel drivers and device migrations (#563)

This commit is contained in:
Ken Van Hoeylandt
2026-07-14 20:26:57 +02:00
committed by GitHub
parent 955416dac8
commit 8af6204ba1
215 changed files with 6359 additions and 3633 deletions
-5
View File
@@ -1,5 +0,0 @@
idf_component_register(
SRC_DIRS "Source"
INCLUDE_DIRS "Source"
REQUIRES Tactility
)
-5
View File
@@ -1,5 +0,0 @@
# BQ24295
Power management: I2C-controlled 3A single cell USB charger with narrow VDC 4.5-5.5V adjustable voltage at 1.5A synchronous boost operation.
[Datasheet](https://www.ti.com/lit/ds/symlink/bq24295.pdf)
-105
View File
@@ -1,105 +0,0 @@
#include "Bq24295.h"
#include <tactility/log.h>
constexpr auto* TAG = "BQ24295";
/** Reference:
* https://www.ti.com/lit/ds/symlink/bq24295.pdf
* https://gitlab.com/hamishcunningham/unphonelibrary/-/blob/main/unPhone.h?ref_type=heads
*/
namespace registers {
static const uint8_t CHARGE_TERMINATION = 0x05U; // Datasheet page 35: Charge end/timer cntrl
static const uint8_t OPERATION_CONTROL = 0x07U; // Datasheet page 37: Misc operation control
static const uint8_t STATUS = 0x08U; // Datasheet page 38: System status
static const uint8_t VERSION = 0x0AU; // Datasheet page 38: Vendor/part/revision status
} // namespace registers
bool Bq24295::readChargeTermination(uint8_t& out) const {
return readRegister8(registers::CHARGE_TERMINATION, out);
}
// region Watchdog
bool Bq24295::getWatchDogTimer(WatchDogTimer& out) const {
uint8_t value;
if (readChargeTermination(value)) {
uint8_t relevant_bits = value & (BIT(4) | BIT(5));
switch (relevant_bits) {
case 0b000000:
out = WatchDogTimer::Disabled;
return true;
case 0b010000:
out = WatchDogTimer::Enabled40s;
return true;
case 0b100000:
out = WatchDogTimer::Enabled80s;
return true;
case 0b110000:
out = WatchDogTimer::Enabled160s;
return true;
default:
return false;
}
}
return false;
}
bool Bq24295::setWatchDogTimer(WatchDogTimer in) const {
uint8_t value;
if (readChargeTermination(value)) {
uint8_t bits_to_set = 0b00110000 & static_cast<uint8_t>(in);
uint8_t value_cleared = value & 0b11001111;
uint8_t to_set = bits_to_set | value_cleared;
LOG_I(TAG, "WatchDogTimer: %02X -> %02X", value, to_set);
return writeRegister8(registers::CHARGE_TERMINATION, to_set);
}
return false;
}
// endregoin
// region Operation Control (REG07)
bool Bq24295::setBatFetOn(bool on) const {
if (on) {
// bit 5 low means bat fet is on
return bitOff(registers::OPERATION_CONTROL, BIT(5));
} else {
// bit 5 high means bat fet is off
return bitOn(registers::OPERATION_CONTROL, BIT(5));
}
}
// endregion
// region Other
bool Bq24295::getStatus(uint8_t& value) const {
return readRegister8(registers::STATUS, value);
}
bool Bq24295::isUsbPowerConnected() const {
uint8_t status;
if (getStatus(status)) {
return (status & BIT(2)) != 0U;
} else {
return false;
}
}
bool Bq24295::getVersion(uint8_t& value) const {
return readRegister8(registers::VERSION, value);
}
void Bq24295::printInfo() const {
uint8_t version, status, charge_termination;
if (getStatus(status) && getVersion(version) && readChargeTermination(charge_termination)) {
LOG_I(TAG, "Version %d, status %02X, charge termination %02X", version, status, charge_termination);
} else {
LOG_E(TAG, "Failed to retrieve version and/or status");
}
}
// endregion
-38
View File
@@ -1,38 +0,0 @@
#pragma once
#include <Tactility/hal/i2c/I2cDevice.h>
#define BQ24295_ADDRESS 0x6BU
class Bq24295 final : public tt::hal::i2c::I2cDevice {
bool readChargeTermination(uint8_t& out) const;
public:
std::string getName() const final { return "BQ24295"; }
std::string getDescription() const final { return "I2C-controlled single cell USB charger"; }
enum class WatchDogTimer {
Disabled = 0b000000,
Enabled40s = 0b010000,
Enabled80s = 0b100000,
Enabled160s = 0b110000
};
explicit Bq24295(::Device* controller) : I2cDevice(controller, BQ24295_ADDRESS) {}
bool getWatchDogTimer(WatchDogTimer& out) const;
bool setWatchDogTimer(WatchDogTimer in) const;
bool isUsbPowerConnected() const;
bool setBatFetOn(bool on) const;
bool getStatus(uint8_t& value) const;
bool getVersion(uint8_t& value) const;
void printInfo() const;
};
-5
View File
@@ -1,5 +0,0 @@
idf_component_register(
SRC_DIRS "Source"
INCLUDE_DIRS "Source"
REQUIRES Tactility EspLcdCompat esp_lcd_touch_xpt2046
)
-3
View File
@@ -1,3 +0,0 @@
# XPT2046
A basic XPT2046 touch driver.
-57
View File
@@ -1,57 +0,0 @@
#include "Xpt2046Touch.h"
#include <Tactility/settings/TouchCalibrationSettings.h>
#include <Tactility/lvgl/LvglSync.h>
#include <algorithm>
#include <esp_err.h>
#include <esp_lcd_touch_xpt2046.h>
static void processCoordinates(esp_lcd_touch_handle_t tp, uint16_t* x, uint16_t* y, uint16_t* strength, uint8_t* pointCount, uint8_t maxPointCount) {
(void)strength;
if (tp == nullptr || x == nullptr || y == nullptr || pointCount == nullptr || *pointCount == 0) {
return;
}
auto* config = static_cast<Xpt2046Touch::Configuration*>(tp->config.user_data);
if (config == nullptr) {
return;
}
const auto settings = tt::settings::touch::getActive();
const auto points = std::min<uint8_t>(*pointCount, maxPointCount);
for (uint8_t i = 0; i < points; i++) {
tt::settings::touch::applyCalibration(settings, config->xMax, config->yMax, x[i], y[i]);
}
}
bool Xpt2046Touch::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) {
const esp_lcd_panel_io_spi_config_t io_config = ESP_LCD_TOUCH_IO_SPI_XPT2046_CONFIG(configuration->spiPinCs);
return esp_lcd_new_panel_io_spi(configuration->spiDevice, &io_config, &outHandle) == ESP_OK;
}
bool Xpt2046Touch::createTouchHandle(esp_lcd_panel_io_handle_t ioHandle, const esp_lcd_touch_config_t& config, esp_lcd_touch_handle_t& panelHandle) {
return esp_lcd_touch_new_spi_xpt2046(ioHandle, &config, &panelHandle) == ESP_OK;
}
esp_lcd_touch_config_t Xpt2046Touch::createEspLcdTouchConfig() {
return {
.x_max = configuration->xMax,
.y_max = configuration->yMax,
.rst_gpio_num = GPIO_NUM_NC,
.int_gpio_num = GPIO_NUM_NC,
.levels = {
.reset = 0,
.interrupt = 0,
},
.flags = {
.swap_xy = configuration->swapXy,
.mirror_x = configuration->mirrorX,
.mirror_y = configuration->mirrorY,
},
.process_coordinates = processCoordinates,
.interrupt_callback = nullptr,
.user_data = configuration.get(),
.driver_data = nullptr
};
}
-61
View File
@@ -1,61 +0,0 @@
#pragma once
#include <Tactility/hal/touch/TouchDevice.h>
#include <EspLcdTouch.h>
class Xpt2046Touch : public EspLcdTouch {
public:
class Configuration {
public:
Configuration(
esp_lcd_spi_bus_handle_t spiDevice,
gpio_num_t spiPinCs,
uint16_t xMax,
uint16_t yMax,
bool swapXy = false,
bool mirrorX = false,
bool mirrorY = false
) : spiDevice(spiDevice),
spiPinCs(spiPinCs),
xMax(xMax),
yMax(yMax),
swapXy(swapXy),
mirrorX(mirrorX),
mirrorY(mirrorY)
{}
esp_lcd_spi_bus_handle_t spiDevice;
gpio_num_t spiPinCs;
uint16_t xMax;
uint16_t yMax;
bool swapXy;
bool mirrorX;
bool mirrorY;
};
private:
std::unique_ptr<Configuration> configuration;
bool createIoHandle(esp_lcd_panel_io_handle_t& outHandle) override;
bool createTouchHandle(esp_lcd_panel_io_handle_t ioHandle, const esp_lcd_touch_config_t& configuration, esp_lcd_touch_handle_t& panelHandle) override;
esp_lcd_touch_config_t createEspLcdTouchConfig() override;
public:
explicit Xpt2046Touch(std::unique_ptr<Configuration> inConfiguration) : configuration(std::move(inConfiguration)) {
assert(configuration != nullptr);
}
std::string getName() const final { return "XPT2046"; }
std::string getDescription() const final { return "XPT2046 SPI touch driver"; }
bool supportsCalibration() const override { return true; }
};
-5
View File
@@ -1,5 +0,0 @@
idf_component_register(
SRC_DIRS "Source"
INCLUDE_DIRS "Source"
REQUIRES Tactility driver esp_lvgl_port
)
-4
View File
@@ -1,4 +0,0 @@
# XPT2046_SoftSPI Driver
XPT2046_SoftSPI is a driver for the XPT2046 resistive touchscreen controller that uses SoftSPI.
Inspiration from: https://github.com/ddxfish/XPT2046_Bitbang_Arduino_Library/
@@ -1,241 +0,0 @@
#include "Xpt2046SoftSpi.h"
#include <tactility/log.h>
#include <Tactility/settings/TouchCalibrationSettings.h>
#include <algorithm>
#include <driver/gpio.h>
#include <esp_err.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <rom/ets_sys.h>
constexpr auto* TAG = "Xpt2046SoftSpi";
constexpr auto CMD_READ_Y = 0x90;
constexpr auto CMD_READ_X = 0xD0;
constexpr int RAW_MIN_DEFAULT = 100;
constexpr int RAW_MAX_DEFAULT = 1900;
constexpr int RAW_VALID_MIN = 100;
constexpr int RAW_VALID_MAX = 3900;
Xpt2046SoftSpi::Xpt2046SoftSpi(std::unique_ptr<Configuration> inConfiguration)
: configuration(std::move(inConfiguration)) {
assert(configuration != nullptr);
}
bool Xpt2046SoftSpi::start() {
LOG_I(TAG, "Starting Xpt2046SoftSpi touch driver");
// Configure GPIO pins
gpio_config_t io_conf = {};
// Configure MOSI, CLK, CS as outputs
io_conf.intr_type = GPIO_INTR_DISABLE;
io_conf.mode = GPIO_MODE_OUTPUT;
io_conf.pin_bit_mask = (1ULL << configuration->mosiPin) |
(1ULL << configuration->clkPin) |
(1ULL << configuration->csPin);
io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
io_conf.pull_up_en = GPIO_PULLUP_DISABLE;
if (gpio_config(&io_conf) != ESP_OK) {
LOG_E(TAG, "Failed to configure output pins");
return false;
}
// Configure MISO as input
io_conf.mode = GPIO_MODE_INPUT;
io_conf.pin_bit_mask = (1ULL << configuration->misoPin);
io_conf.pull_up_en = GPIO_PULLUP_ENABLE;
if (gpio_config(&io_conf) != ESP_OK) {
LOG_E(TAG, "Failed to configure input pin");
return false;
}
// Initialize pin states
gpio_set_level(configuration->csPin, 1); // CS high
gpio_set_level(configuration->clkPin, 0); // CLK low
gpio_set_level(configuration->mosiPin, 0); // MOSI low
LOG_I(
TAG,
"GPIO configured: MOSI=%d, MISO=%d, CLK=%d, CS=%d",
static_cast<int>(configuration->mosiPin),
static_cast<int>(configuration->misoPin),
static_cast<int>(configuration->clkPin),
static_cast<int>(configuration->csPin)
);
return true;
}
bool Xpt2046SoftSpi::stop() {
LOG_I(TAG, "Stopping Xpt2046SoftSpi touch driver");
// Stop LVLG if needed
if (lvglDevice != nullptr) {
stopLvgl();
}
return true;
}
bool Xpt2046SoftSpi::startLvgl(lv_display_t* display) {
(void)display;
if (lvglDevice != nullptr) {
LOG_E(TAG, "LVGL was already started");
return false;
}
lvglDevice = lv_indev_create();
if (lvglDevice == nullptr) {
LOG_E(TAG, "Failed to create LVGL input device");
return false;
}
lv_indev_set_type(lvglDevice, LV_INDEV_TYPE_POINTER);
lv_indev_set_read_cb(lvglDevice, touchReadCallback);
lv_indev_set_user_data(lvglDevice, this);
LOG_I(TAG, "Xpt2046SoftSpi touch driver started successfully");
return true;
}
bool Xpt2046SoftSpi::stopLvgl() {
if (lvglDevice != nullptr) {
lv_indev_delete(lvglDevice);
lvglDevice = nullptr;
}
return true;
}
int Xpt2046SoftSpi::readSPI(uint8_t command) {
int result = 0;
// Pull CS low for this transaction
gpio_set_level(configuration->csPin, 0);
ets_delay_us(1);
// Send 8-bit command
for (int i = 7; i >= 0; i--) {
gpio_set_level(configuration->mosiPin, (command & (1 << i)) ? 1 : 0);
gpio_set_level(configuration->clkPin, 1);
ets_delay_us(1);
gpio_set_level(configuration->clkPin, 0);
ets_delay_us(1);
}
for (int i = 11; i >= 0; i--) {
gpio_set_level(configuration->clkPin, 1);
ets_delay_us(1);
if (gpio_get_level(configuration->misoPin)) {
result |= (1 << i);
}
gpio_set_level(configuration->clkPin, 0);
ets_delay_us(1);
}
// Pull CS high for this transaction
gpio_set_level(configuration->csPin, 1);
return result;
}
bool Xpt2046SoftSpi::readRawPoint(uint16_t& x, uint16_t& y) {
constexpr int sampleCount = 8;
int totalX = 0;
int totalY = 0;
int validSamples = 0;
for (int i = 0; i < sampleCount; i++) {
const int rawX = readSPI(CMD_READ_X);
const int rawY = readSPI(CMD_READ_Y);
if (rawX > RAW_VALID_MIN && rawX < RAW_VALID_MAX && rawY > RAW_VALID_MIN && rawY < RAW_VALID_MAX) {
totalX += rawX;
totalY += rawY;
validSamples++;
}
vTaskDelay(pdMS_TO_TICKS(1));
}
if (validSamples < 3) {
return false;
}
x = static_cast<uint16_t>(totalX / validSamples);
y = static_cast<uint16_t>(totalY / validSamples);
return true;
}
bool Xpt2046SoftSpi::getTouchPoint(Point& point) {
uint16_t rawX = 0;
uint16_t rawY = 0;
if (!readRawPoint(rawX, rawY)) {
return false;
}
int mappedX = (static_cast<int>(rawX) - RAW_MIN_DEFAULT) * static_cast<int>(configuration->xMax) /
(RAW_MAX_DEFAULT - RAW_MIN_DEFAULT);
int mappedY = (static_cast<int>(rawY) - RAW_MIN_DEFAULT) * static_cast<int>(configuration->yMax) /
(RAW_MAX_DEFAULT - RAW_MIN_DEFAULT);
if (configuration->swapXy) {
std::swap(mappedX, mappedY);
}
if (configuration->mirrorX) {
mappedX = static_cast<int>(configuration->xMax) - mappedX;
}
if (configuration->mirrorY) {
mappedY = static_cast<int>(configuration->yMax) - mappedY;
}
uint16_t x = static_cast<uint16_t>(std::clamp(mappedX, 0, static_cast<int>(configuration->xMax)));
uint16_t y = static_cast<uint16_t>(std::clamp(mappedY, 0, static_cast<int>(configuration->yMax)));
const auto calibration = tt::settings::touch::getActive();
tt::settings::touch::applyCalibration(calibration, configuration->xMax, configuration->yMax, x, y);
point.x = x;
point.y = y;
return true;
}
bool Xpt2046SoftSpi::isTouched() {
uint16_t x = 0;
uint16_t y = 0;
return readRawPoint(x, y);
}
void Xpt2046SoftSpi::touchReadCallback(lv_indev_t* indev, lv_indev_data_t* data) {
auto* touch = static_cast<Xpt2046SoftSpi*>(lv_indev_get_user_data(indev));
if (touch == nullptr) {
data->state = LV_INDEV_STATE_RELEASED;
return;
}
Point point;
if (touch->getTouchPoint(point)) {
data->point.x = point.x;
data->point.y = point.y;
data->state = LV_INDEV_STATE_PRESSED;
} else {
data->state = LV_INDEV_STATE_RELEASED;
}
}
// Return driver instance if any
std::shared_ptr<tt::hal::touch::TouchDriver> Xpt2046SoftSpi::getTouchDriver() {
assert(lvglDevice == nullptr); // Still attached to LVGL context. Call stopLvgl() first.
if (touchDriver == nullptr) {
touchDriver = std::make_shared<Xpt2046SoftSpiDriver>(this);
}
return touchDriver;
}
@@ -1,109 +0,0 @@
#pragma once
#include "Tactility/hal/touch/TouchDevice.h"
#include "Tactility/hal/touch/TouchDriver.h"
#include "lvgl.h"
#include <driver/gpio.h>
#include <memory>
#include <string>
#ifndef TFT_WIDTH
#define TFT_WIDTH 240
#endif
#ifndef TFT_HEIGHT
#define TFT_HEIGHT 320
#endif
struct Point {
int x;
int y;
};
class Xpt2046SoftSpi : public tt::hal::touch::TouchDevice {
public:
class Configuration {
public:
Configuration(
gpio_num_t mosiPin,
gpio_num_t misoPin,
gpio_num_t clkPin,
gpio_num_t csPin,
uint16_t xMax = TFT_WIDTH,
uint16_t yMax = TFT_HEIGHT,
bool swapXy = false,
bool mirrorX = false,
bool mirrorY = false
) : mosiPin(mosiPin),
misoPin(misoPin),
clkPin(clkPin),
csPin(csPin),
xMax(xMax),
yMax(yMax),
swapXy(swapXy),
mirrorX(mirrorX),
mirrorY(mirrorY)
{}
gpio_num_t mosiPin;
gpio_num_t misoPin;
gpio_num_t clkPin;
gpio_num_t csPin;
uint16_t xMax;
uint16_t yMax;
bool swapXy;
bool mirrorX;
bool mirrorY;
};
private:
class Xpt2046SoftSpiDriver final : public tt::hal::touch::TouchDriver {
Xpt2046SoftSpi* device;
public:
Xpt2046SoftSpiDriver(Xpt2046SoftSpi* device) : device(device) {}
bool getTouchedPoints(uint16_t* x, uint16_t* y, uint16_t* strength, uint8_t* pointCount, uint8_t maxPointCount) override {
Point point;
if (device->isTouched() && device->getTouchPoint(point)) {
*x = point.x;
*y = point.y;
*pointCount = 1;
return true;
} else {
*pointCount = 0;
return false;
}
}
};
std::unique_ptr<Configuration> configuration;
lv_indev_t* lvglDevice = nullptr;
std::shared_ptr<tt::hal::touch::TouchDriver> touchDriver;
int readSPI(uint8_t command);
bool readRawPoint(uint16_t& x, uint16_t& y);
static void touchReadCallback(lv_indev_t* indev, lv_indev_data_t* data);
public:
explicit Xpt2046SoftSpi(std::unique_ptr<Configuration> inConfiguration);
// TouchDevice interface
std::string getName() const final { return "Xpt2046SoftSpi"; }
std::string getDescription() const final { return "Xpt2046 Soft SPI touch driver"; }
bool start() override;
bool stop() override;
bool supportsLvgl() const override { return true; }
bool startLvgl(lv_display_t* display) override;
bool stopLvgl() override;
bool supportsTouchDriver() override { return true; }
bool supportsCalibration() const override { return true; }
std::shared_ptr<tt::hal::touch::TouchDriver> getTouchDriver() override;
lv_indev_t* getLvglIndev() override { return lvglDevice; }
// XPT2046-specific methods
bool getTouchPoint(Point& point);
bool isTouched();
};
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 3.20)
include("${CMAKE_CURRENT_LIST_DIR}/../../Buildscripts/module.cmake")
file(GLOB_RECURSE SOURCE_FILES "source/*.c*")
tactility_add_module(bq24295-module
SRCS ${SOURCE_FILES}
INCLUDE_DIRS include/
REQUIRES TactilityKernel
)
@@ -0,0 +1,195 @@
Apache License
==============
_Version 2.0, January 2004_
_&lt;<http://www.apache.org/licenses/>&gt;_
### Terms and Conditions for use, reproduction, and distribution
#### 1. Definitions
“License” shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
“Licensor” shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
“Legal Entity” shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, “control” means **(i)** the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
outstanding shares, or **(iii)** beneficial ownership of such entity.
“You” (or “Your”) shall mean an individual or Legal Entity exercising
permissions granted by this License.
“Source” form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
“Object” form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
“Work” shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
“Derivative Works” shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
“Contribution” shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
“submitted” means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as “Not a Contribution.”
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
#### 2. Grant of Copyright License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
#### 3. Grant of Patent License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
#### 4. Redistribution
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
* **(a)** You must give any other recipients of the Work or Derivative Works a copy of
this License; and
* **(b)** You must cause any modified files to carry prominent notices stating that You
changed the files; and
* **(c)** You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
#### 5. Submission of Contributions
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
#### 6. Trademarks
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
#### 7. Disclaimer of Warranty
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
#### 8. Limitation of Liability
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
#### 9. Accepting Warranty or Additional Liability
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
_END OF TERMS AND CONDITIONS_
### APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets `[]` replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same “printed page” as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+7
View File
@@ -0,0 +1,7 @@
# BQ24295 USB charger
A driver for the TI `BQ24295` single-cell Li-ion USB battery charger: watchdog timer
control, BATFET (battery FET) enable/disable for shipping mode, USB power-good detection,
and status/version readback.
License: [Apache v2.0](LICENSE-Apache-2.0.md)
@@ -0,0 +1,5 @@
description: TI BQ24295 single-cell USB battery charger
include: ["i2c-device.yaml"]
compatible: "ti,bq24295"
+3
View File
@@ -0,0 +1,3 @@
dependencies:
- TactilityKernel
bindings: bindings
@@ -0,0 +1,15 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <tactility/bindings/bindings.h>
#include <drivers/bq24295.h>
#ifdef __cplusplus
extern "C" {
#endif
DEFINE_DEVICETREE(bq24295, struct Bq24295Config)
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,14 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <tactility/module.h>
#ifdef __cplusplus
extern "C" {
#endif
extern struct Module bq24295_module;
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,42 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include <tactility/error.h>
struct Device;
#ifdef __cplusplus
extern "C" {
#endif
struct Bq24295Config {
/** Address on bus */
uint8_t address;
};
enum Bq24295WatchDogTimer {
BQ24295_WATCHDOG_DISABLED = 0b000000,
BQ24295_WATCHDOG_ENABLED_40S = 0b010000,
BQ24295_WATCHDOG_ENABLED_80S = 0b100000,
BQ24295_WATCHDOG_ENABLED_160S = 0b110000
};
error_t bq24295_get_watchdog_timer(struct Device* device, enum Bq24295WatchDogTimer* out);
error_t bq24295_set_watchdog_timer(struct Device* device, enum Bq24295WatchDogTimer in);
error_t bq24295_is_usb_power_connected(struct Device* device, bool* connected);
/** BATFET (battery FET): off disconnects the battery from the system (shipping mode). */
error_t bq24295_set_bat_fet_on(struct Device* device, bool on);
error_t bq24295_get_status(struct Device* device, uint8_t* value);
error_t bq24295_get_version(struct Device* device, uint8_t* value);
void bq24295_print_info(struct Device* device);
#ifdef __cplusplus
}
#endif
+270
View File
@@ -0,0 +1,270 @@
// SPDX-License-Identifier: Apache-2.0
#include <drivers/bq24295.h>
#include <bq24295_module.h>
#include <tactility/check.h>
#include <tactility/device.h>
#include <tactility/driver.h>
#include <tactility/drivers/i2c_controller.h>
#include <tactility/drivers/power_supply.h>
#include <tactility/log.h>
#include <new>
#define TAG "BQ24295"
#define GET_CONFIG(device) (static_cast<const Bq24295Config*>((device)->config))
/** Reference:
* https://www.ti.com/lit/ds/symlink/bq24295.pdf
* https://gitlab.com/hamishcunningham/unphonelibrary/-/blob/main/unPhone.h?ref_type=heads
*/
static constexpr uint8_t REG_CHARGE_TERMINATION = 0x05U; // Datasheet page 35: Charge end/timer cntrl
static constexpr uint8_t REG_OPERATION_CONTROL = 0x07U; // Datasheet page 37: Misc operation control
static constexpr uint8_t REG_STATUS = 0x08U; // Datasheet page 38: System status
static constexpr uint8_t REG_VERSION = 0x0AU; // Datasheet page 38: Vendor/part/revision status
static constexpr TickType_t TIMEOUT = pdMS_TO_TICKS(50);
extern "C" {
extern Module bq24295_module;
static error_t read_charge_termination(Device* device, uint8_t* out) {
auto* parent = device_get_parent(device);
auto address = GET_CONFIG(device)->address;
return i2c_controller_register8_get(parent, address, REG_CHARGE_TERMINATION, out, TIMEOUT);
}
error_t bq24295_get_watchdog_timer(Device* device, Bq24295WatchDogTimer* out) {
uint8_t value;
error_t err = read_charge_termination(device, &value);
if (err != ERROR_NONE) {
return err;
}
switch (value & 0b00110000) {
case BQ24295_WATCHDOG_DISABLED:
*out = BQ24295_WATCHDOG_DISABLED;
return ERROR_NONE;
case BQ24295_WATCHDOG_ENABLED_40S:
*out = BQ24295_WATCHDOG_ENABLED_40S;
return ERROR_NONE;
case BQ24295_WATCHDOG_ENABLED_80S:
*out = BQ24295_WATCHDOG_ENABLED_80S;
return ERROR_NONE;
case BQ24295_WATCHDOG_ENABLED_160S:
*out = BQ24295_WATCHDOG_ENABLED_160S;
return ERROR_NONE;
default:
return ERROR_RESOURCE;
}
}
error_t bq24295_set_watchdog_timer(Device* device, Bq24295WatchDogTimer in) {
uint8_t value;
error_t err = read_charge_termination(device, &value);
if (err != ERROR_NONE) {
return err;
}
uint8_t bits_to_set = 0b00110000 & static_cast<uint8_t>(in);
uint8_t value_cleared = value & 0b11001111;
uint8_t to_set = bits_to_set | value_cleared;
LOG_I(TAG, "WatchDogTimer: %02X -> %02X", value, to_set);
auto* parent = device_get_parent(device);
auto address = GET_CONFIG(device)->address;
return i2c_controller_register8_set(parent, address, REG_CHARGE_TERMINATION, to_set, TIMEOUT);
}
error_t bq24295_set_bat_fet_on(Device* device, bool on) {
auto* parent = device_get_parent(device);
auto address = GET_CONFIG(device)->address;
// bit 5 low means bat fet is on, bit 5 high means bat fet is off
if (on) {
return i2c_controller_register8_reset_bits(parent, address, REG_OPERATION_CONTROL, 1 << 5, TIMEOUT);
} else {
return i2c_controller_register8_set_bits(parent, address, REG_OPERATION_CONTROL, 1 << 5, TIMEOUT);
}
}
error_t bq24295_get_status(Device* device, uint8_t* value) {
auto* parent = device_get_parent(device);
auto address = GET_CONFIG(device)->address;
return i2c_controller_register8_get(parent, address, REG_STATUS, value, TIMEOUT);
}
error_t bq24295_is_usb_power_connected(Device* device, bool* connected) {
uint8_t status;
error_t err = bq24295_get_status(device, &status);
if (err != ERROR_NONE) {
return err;
}
*connected = (status & (1 << 2)) != 0U;
return ERROR_NONE;
}
error_t bq24295_get_version(Device* device, uint8_t* value) {
auto* parent = device_get_parent(device);
auto address = GET_CONFIG(device)->address;
return i2c_controller_register8_get(parent, address, REG_VERSION, value, TIMEOUT);
}
void bq24295_print_info(Device* device) {
uint8_t version, status, charge_termination;
if (bq24295_get_status(device, &status) == ERROR_NONE &&
bq24295_get_version(device, &version) == ERROR_NONE &&
read_charge_termination(device, &charge_termination) == ERROR_NONE) {
LOG_I(TAG, "Version %d, status %02X, charge termination %02X", version, status, charge_termination);
} else {
LOG_E(TAG, "Failed to retrieve version and/or status");
}
}
// region Power supply child device
static bool ps_supports_property(Device*, PowerSupplyProperty property) {
return property == POWER_SUPPLY_PROP_IS_CHARGING;
}
static error_t ps_get_property(Device* device, PowerSupplyProperty property, PowerSupplyPropertyValue* out_value) {
if (property != POWER_SUPPLY_PROP_IS_CHARGING) {
return ERROR_NOT_SUPPORTED;
}
// device_get_parent() here is the bq24295 device itself (this child's parent), not the I2C bus.
uint8_t status;
error_t error = bq24295_get_status(device_get_parent(device), &status);
if (error != ERROR_NONE) {
return error;
}
// Datasheet REG08 bits[5:4] (CHRG_STAT): 0 = not charging, 1 = pre-charge,
// 2 = fast charge, 3 = charge termination done. Only 1|2 count as actively charging.
uint8_t charge_status = (status >> 4) & 0x03;
out_value->int_value = (charge_status == 1 || charge_status == 2) ? 1 : 0;
return ERROR_NONE;
}
static bool ps_supports_charge_control(Device*) { return false; }
static bool ps_is_allowed_to_charge(Device*) { return false; }
static error_t ps_set_allowed_to_charge(Device*, bool) { return ERROR_NOT_SUPPORTED; }
static bool ps_supports_quick_charge(Device*) { return false; }
static bool ps_is_quick_charge_enabled(Device*) { return false; }
static error_t ps_set_quick_charge_enabled(Device*, bool) { return ERROR_NOT_SUPPORTED; }
static bool ps_supports_power_off(Device*) { return false; }
static error_t ps_power_off(Device*) { return ERROR_NOT_SUPPORTED; }
static constexpr PowerSupplyApi BQ24295_POWER_SUPPLY_API = {
.supports_property = ps_supports_property,
.get_property = ps_get_property,
.supports_charge_control = ps_supports_charge_control,
.is_allowed_to_charge = ps_is_allowed_to_charge,
.set_allowed_to_charge = ps_set_allowed_to_charge,
.supports_quick_charge = ps_supports_quick_charge,
.is_quick_charge_enabled = ps_is_quick_charge_enabled,
.set_quick_charge_enabled = ps_set_quick_charge_enabled,
.supports_power_off = ps_supports_power_off,
.power_off = ps_power_off,
};
// Registered (driver_construct_add() in module.cpp) so driver_bind() has a valid ->internal,
// but never matched against a devicetree node: bq24295_driver wires it up directly by pointer.
Driver bq24295_power_supply_driver = {
.name = "bq24295-power-supply",
.compatible = (const char*[]) { "bq24295-power-supply", nullptr },
.start_device = nullptr,
.stop_device = nullptr,
.api = &BQ24295_POWER_SUPPLY_API,
.device_type = &POWER_SUPPLY_TYPE,
.owner = &bq24295_module,
.internal = nullptr
};
struct Bq24295Internal {
Device* power_supply_device = nullptr;
};
static error_t create_power_supply_child(Device* parent, Device*& out_child) {
auto* child = new(std::nothrow) Device { .address = 0, .name = "bq24295-power-supply", .config = nullptr, .parent = nullptr, .internal = nullptr };
if (child == nullptr) {
return ERROR_OUT_OF_MEMORY;
}
error_t error = device_construct(child);
if (error != ERROR_NONE) {
delete child;
return error;
}
device_set_parent(child, parent);
device_set_driver(child, &bq24295_power_supply_driver);
error = device_add(child);
if (error != ERROR_NONE) {
device_destruct(child);
delete child;
return error;
}
error = device_start(child);
if (error != ERROR_NONE) {
device_remove(child);
device_destruct(child);
delete child;
return error;
}
out_child = child;
return ERROR_NONE;
}
static void destroy_power_supply_child(Device* child) {
check(device_stop(child) == ERROR_NONE);
check(device_remove(child) == ERROR_NONE);
check(device_destruct(child) == ERROR_NONE);
delete child;
}
// endregion
static error_t start(Device* device) {
auto* parent = device_get_parent(device);
check(device_get_type(parent) == &I2C_CONTROLLER_TYPE);
auto* internal = new(std::nothrow) Bq24295Internal();
if (internal == nullptr) {
return ERROR_OUT_OF_MEMORY;
}
error_t error = create_power_supply_child(device, internal->power_supply_device);
if (error != ERROR_NONE) {
delete internal;
return error;
}
device_set_driver_data(device, internal);
return ERROR_NONE;
}
static error_t stop(Device* device) {
auto* internal = static_cast<Bq24295Internal*>(device_get_driver_data(device));
destroy_power_supply_child(internal->power_supply_device);
device_set_driver_data(device, nullptr);
delete internal;
return ERROR_NONE;
}
Driver bq24295_driver = {
.name = "bq24295",
.compatible = (const char*[]) { "ti,bq24295", nullptr },
.start_device = start,
.stop_device = stop,
.api = nullptr,
.device_type = nullptr,
.owner = &bq24295_module,
.internal = nullptr
};
}
+35
View File
@@ -0,0 +1,35 @@
// SPDX-License-Identifier: Apache-2.0
#include <tactility/check.h>
#include <tactility/driver.h>
#include <tactility/module.h>
extern "C" {
extern Driver bq24295_driver;
extern Driver bq24295_power_supply_driver;
static error_t start() {
/* We crash when construct fails, because if a single driver fails to construct,
* there is no guarantee that the previously constructed drivers can be destroyed */
check(driver_construct_add(&bq24295_driver) == ERROR_NONE);
check(driver_construct_add(&bq24295_power_supply_driver) == ERROR_NONE);
return ERROR_NONE;
}
static error_t stop() {
/* We crash when destruct fails, because if a single driver fails to destruct,
* there is no guarantee that the previously destroyed drivers can be recovered */
check(driver_remove_destruct(&bq24295_power_supply_driver) == ERROR_NONE);
check(driver_remove_destruct(&bq24295_driver) == ERROR_NONE);
return ERROR_NONE;
}
Module bq24295_module = {
.name = "bq24295",
.start = start,
.stop = stop,
.symbols = nullptr,
.internal = nullptr
};
}
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 3.20)
include("${CMAKE_CURRENT_LIST_DIR}/../../Buildscripts/module.cmake")
file(GLOB_RECURSE SOURCE_FILES "source/*.c*")
tactility_add_module(hx8357-module
SRCS ${SOURCE_FILES}
INCLUDE_DIRS include/
REQUIRES TactilityKernel platform-esp32 driver
)
+195
View File
@@ -0,0 +1,195 @@
Apache License
==============
_Version 2.0, January 2004_
_&lt;<http://www.apache.org/licenses/>&gt;_
### Terms and Conditions for use, reproduction, and distribution
#### 1. Definitions
“License” shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
“Licensor” shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
“Legal Entity” shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, “control” means **(i)** the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
outstanding shares, or **(iii)** beneficial ownership of such entity.
“You” (or “Your”) shall mean an individual or Legal Entity exercising
permissions granted by this License.
“Source” form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
“Object” form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
“Work” shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
“Derivative Works” shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
“Contribution” shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
“submitted” means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as “Not a Contribution.”
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
#### 2. Grant of Copyright License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
#### 3. Grant of Patent License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
#### 4. Redistribution
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
* **(a)** You must give any other recipients of the Work or Derivative Works a copy of
this License; and
* **(b)** You must cause any modified files to carry prominent notices stating that You
changed the files; and
* **(c)** You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
#### 5. Submission of Contributions
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
#### 6. Trademarks
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
#### 7. Disclaimer of Warranty
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
#### 8. Limitation of Liability
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
#### 9. Accepting Warranty or Additional Liability
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
_END OF TERMS AND CONDITIONS_
### APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets `[]` replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same “printed page” as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+7
View File
@@ -0,0 +1,7 @@
# HX8357 Display Driver
A kernel driver for the `HX8357-D` display panel (24bpp/RGB888). No ESP-IDF `esp_lcd` component exists for this controller, so this driver speaks its raw SPI command protocol directly rather than wrapping `esp_lcd_panel_io`/`esp_lcd_panel`.
See https://cdn-shop.adafruit.com/datasheets/HX8357-D_DS_April2012.pdf
License: [Apache v2.0](LICENSE-Apache-2.0.md)
@@ -0,0 +1,64 @@
description: >
Himax HX8357-D display panel. 24bpp/RGB888 only. No ESP-IDF esp_lcd component exists for this
controller, so this driver speaks the panel's raw SPI command protocol directly (bit-banged
DC line, blocking spi_device_transmit()) rather than wrapping esp_lcd_panel_io/esp_lcd_panel.
No bgr-order property: unlike the RGB565 panels (ili9341-module, st7789-module), there is no
DISPLAY_COLOR_FORMAT_BGR888 in the kernel model, so a BGR-wired panel isn't representable here.
compatible: "himax,hx8357"
bus: spi
properties:
horizontal-resolution:
type: int
required: true
description: Horizontal resolution in pixels
vertical-resolution:
type: int
required: true
description: Vertical resolution in pixels
gap-x:
type: int
default: 0
description: X offset applied to all draw operations
gap-y:
type: int
default: 0
description: Y offset applied to all draw operations
swap-xy:
type: boolean
default: false
description: Swap the X and Y axes
mirror-x:
type: boolean
default: true
description: Mirror the X axis
mirror-y:
type: boolean
default: false
description: Mirror the Y axis
invert-color:
type: boolean
default: false
description: Invert the panel's color output
pixel-clock-hz:
type: int
default: 26000000
description: SPI pixel clock frequency in Hz
pin-dc:
type: phandles
required: true
description: Data/Command GPIO pin
pin-reset:
type: phandles
default: GPIO_PIN_SPEC_NONE
description: Reset GPIO pin
reset-active-high:
type: boolean
default: false
description: Whether the reset pin is active high
backlight:
type: phandle
default: "NULL"
description: Optional reference to this display's backlight device
+3
View File
@@ -0,0 +1,3 @@
dependencies:
- TactilityKernel
bindings: bindings
@@ -0,0 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <tactility/bindings/bindings.h>
#include <drivers/hx8357.h>
DEFINE_DEVICETREE(hx8357, struct Hx8357Config)
@@ -0,0 +1,33 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stdbool.h>
#include <tactility/device.h>
#include <tactility/drivers/gpio.h>
struct Hx8357Config {
uint16_t horizontal_resolution;
uint16_t vertical_resolution;
int32_t gap_x;
int32_t gap_y;
bool swap_xy;
bool mirror_x;
bool mirror_y;
bool invert_color;
uint32_t pixel_clock_hz;
struct GpioPinSpec pin_dc;
struct GpioPinSpec pin_reset;
bool reset_active_high;
// Optional reference to this display's backlight device, NULL if none.
struct Device* backlight;
};
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,14 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <tactility/module.h>
#ifdef __cplusplus
extern "C" {
#endif
extern struct Module hx8357_module;
#ifdef __cplusplus
}
#endif
+468
View File
@@ -0,0 +1,468 @@
// SPDX-License-Identifier: Apache-2.0
#include <drivers/hx8357.h>
#include <hx8357_module.h>
#include <tactility/check.h>
#include <tactility/device.h>
#include <tactility/driver.h>
#include <tactility/drivers/display.h>
#include <tactility/drivers/esp32_spi.h>
#include <tactility/drivers/spi_controller.h>
#include <tactility/error.h>
#include <tactility/log.h>
#include <driver/gpio.h>
#include <driver/spi_master.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <cstdlib>
#include <cstring>
#define TAG "HX8357"
#define GET_CONFIG(device) (static_cast<const Hx8357Config*>((device)->config))
namespace {
// HX8357-D command set (subset actually used). See
// https://cdn-shop.adafruit.com/datasheets/HX8357-D_DS_April2012.pdf
constexpr uint8_t HX8357_SWRESET = 0x01;
constexpr uint8_t HX8357_SLPOUT = 0x11;
constexpr uint8_t HX8357_INVOFF = 0x20;
constexpr uint8_t HX8357_INVON = 0x21;
constexpr uint8_t HX8357_DISPON = 0x29;
constexpr uint8_t HX8357_CASET = 0x2A;
constexpr uint8_t HX8357_PASET = 0x2B;
constexpr uint8_t HX8357_RAMWR = 0x2C;
constexpr uint8_t HX8357_MADCTL = 0x36;
constexpr uint8_t HX8357_COLMOD = 0x3A;
constexpr uint8_t HX8357_TEON = 0x35;
constexpr uint8_t HX8357_TEARLINE = 0x44;
constexpr uint8_t HX8357_SETOSC = 0xB0;
constexpr uint8_t HX8357_SETPWR1 = 0xB1;
constexpr uint8_t HX8357_SETRGB = 0xB3;
constexpr uint8_t HX8357D_SETCOM = 0xB6;
constexpr uint8_t HX8357D_SETCYC = 0xB4;
constexpr uint8_t HX8357D_SETC = 0xB9;
constexpr uint8_t HX8357D_SETSTBA = 0xC0;
constexpr uint8_t HX8357_SETPANEL = 0xCC;
constexpr uint8_t HX8357D_SETGAMMA = 0xE0;
// MADCTL bit indices, see the datasheet page 123.
constexpr uint8_t MADCTL_BIT_PAGE_COLUMN_ORDER = 5; // swap-xy
constexpr uint8_t MADCTL_BIT_COLUMN_ADDRESS_ORDER = 6; // mirror-x
constexpr uint8_t MADCTL_BIT_PAGE_ADDRESS_ORDER = 7; // mirror-y
// Bring-up command list, ported verbatim (byte-for-byte) from the deprecated HAL's hx8357.c
// initd[] table (Devices/unphone/Source/hx8357/hx8357.c) - the HX8357B variant (initb[]) is
// dead code there (displayType is hardcoded to HX8357D) and was not ported. Format matches the
// original: cmd, then a length byte (bit7 set means "this is actually a delay in 5ms units, no
// data follows"), then that many data bytes. A single 0 cmd byte ends the list.
constexpr uint8_t INIT_CMDS[] = {
HX8357_SWRESET, 0x80 + 100 / 5, // Soft reset, then delay 100 ms
HX8357D_SETC, 3,
0xFF, 0x83, 0x57,
0xFF, 0x80 + 500 / 5, // No command, just delay 500 ms
HX8357_SETRGB, 4,
0x80, 0x00, 0x06, 0x06, // 0x80 enables SDO pin (0x00 disables)
HX8357D_SETCOM, 1,
0x25, // -1.52V
HX8357_SETOSC, 1,
0x68, // Normal mode 70Hz, Idle mode 55 Hz
HX8357_SETPANEL, 1,
0x05, // BGR, Gate direction swapped
HX8357_SETPWR1, 6,
0x00, // Not deep standby
0x15, // BT
0x1C, // VSPR
0x1C, // VSNR
0x83, // AP
0xAA, // FS
HX8357D_SETSTBA, 6,
0x50, // OPON normal
0x50, // OPON idle
0x01, // STBA
0x3C, // STBA
0x1E, // STBA
0x08, // GEN
HX8357D_SETCYC, 7,
0x02, // NW 0x02
0x40, // RTN
0x00, // DIV
0x2A, // DUM
0x2A, // DUM
0x0D, // GDON
0x78, // GDOFF
HX8357D_SETGAMMA, 34,
0x02, 0x0A, 0x11, 0x1d, 0x23, 0x35, 0x41, 0x4b, 0x4b,
0x42, 0x3A, 0x27, 0x1B, 0x08, 0x09, 0x03, 0x02, 0x0A,
0x11, 0x1d, 0x23, 0x35, 0x41, 0x4b, 0x4b, 0x42, 0x3A,
0x27, 0x1B, 0x08, 0x09, 0x03, 0x00, 0x01,
HX8357_COLMOD, 1,
0x57, // 24bpp
HX8357_MADCTL, 1,
0xC0,
HX8357_TEON, 1,
0x00, // TW off
HX8357_TEARLINE, 2,
0x00, 0x02,
HX8357_SLPOUT, 0x80 + 150 / 5, // Exit sleep, then delay 150 ms
HX8357_DISPON, 0x80 + 50 / 5, // Main screen turn on, delay 50 ms
0, // END OF COMMAND LIST
};
} // namespace
struct Hx8357Internal {
spi_device_handle_t spi_handle;
gpio_num_t dc_pin;
size_t max_transfer_size;
// Live MADCTL orientation bits, seeded from config at start() and updated in place by
// mirror()/swap_xy() - NOT reconstructed from the static config each call. swap_xy() and
// mirror() are invoked back-to-back by lvgl_display_apply_rotation() on every rotation
// change, so rebuilding from config would silently discard whichever bit the other call
// just set.
bool swap_xy;
bool mirror_x;
bool mirror_y;
};
static int pin_or_unused(const struct GpioPinSpec& pin) {
return pin.gpio_controller == nullptr ? -1 : static_cast<int>(pin.pin);
}
// region Bring-up protocol
static void spi_send(spi_device_handle_t spi, const uint8_t* data, size_t length) {
if (length == 0) {
return;
}
spi_transaction_t transaction = {};
transaction.length = length * 8;
if (length <= 4) {
transaction.flags = SPI_TRANS_USE_TXDATA;
memcpy(transaction.tx_data, data, length);
} else {
transaction.tx_buffer = data;
}
// Blocking: physically completes before returning, unlike esp_lcd_panel_draw_bitmap() -
// no semaphore/ISR-callback dance needed to honor DisplayApi's synchronous draw_bitmap contract.
spi_device_transmit(spi, &transaction);
}
static void send_cmd(const Hx8357Internal* internal, uint8_t cmd) {
gpio_set_level(internal->dc_pin, 0);
spi_send(internal->spi_handle, &cmd, 1);
}
// Chunked to stay under the SPI bus's max single-transaction transfer size (e.g. RAMWR pixel
// bursts can be hundreds of KB). CS toggles between chunks, which the panel tolerates: it only
// resets its RAMWR auto-increment pointer on a new command byte, not on CS deselect.
static void send_data(const Hx8357Internal* internal, const uint8_t* data, size_t length) {
gpio_set_level(internal->dc_pin, 1);
while (length > 0) {
size_t chunk = length < internal->max_transfer_size ? length : internal->max_transfer_size;
spi_send(internal->spi_handle, data, chunk);
data += chunk;
length -= chunk;
}
}
static void run_init_cmds(const Hx8357Internal* internal) {
const uint8_t* addr = INIT_CMDS;
uint8_t cmd;
while ((cmd = *addr++) > 0) { // 0 command ends the list
uint8_t x = *addr++;
uint8_t num_args = x & 0x7F;
if (cmd != 0xFF) { // 0xFF is a no-op placeholder (only used to carry a delay)
send_cmd(internal, cmd);
if (!(x & 0x80)) {
send_data(internal, addr, num_args);
addr += num_args;
}
}
if (x & 0x80) { // high bit set: num_args is actually a delay, in 5ms units
vTaskDelay(pdMS_TO_TICKS(num_args * 5));
}
}
}
static void send_madctl(const Hx8357Internal* internal) {
uint8_t madctl = 0;
if (internal->swap_xy) madctl |= (1 << MADCTL_BIT_PAGE_COLUMN_ORDER);
if (internal->mirror_x) madctl |= (1 << MADCTL_BIT_COLUMN_ADDRESS_ORDER);
if (internal->mirror_y) madctl |= (1 << MADCTL_BIT_PAGE_ADDRESS_ORDER);
send_cmd(internal, HX8357_MADCTL);
send_data(internal, &madctl, 1);
}
// endregion
// region Driver lifecycle
static error_t start(Device* device) {
auto* parent = device_get_parent(device);
check(device_get_type(parent) == &SPI_CONTROLLER_TYPE);
const auto* spi_config = static_cast<const Esp32SpiConfig*>(parent->config);
const auto* config = GET_CONFIG(device);
GpioPinSpec cs_pin;
if (esp32_spi_get_cs_pin(device, &cs_pin) != ERROR_NONE) {
LOG_E(TAG, "Failed to resolve CS pin");
return ERROR_RESOURCE;
}
auto* internal = static_cast<Hx8357Internal*>(malloc(sizeof(Hx8357Internal)));
if (internal == nullptr) {
return ERROR_OUT_OF_MEMORY;
}
internal->dc_pin = static_cast<gpio_num_t>(pin_or_unused(config->pin_dc));
// Clamped below the bus's configured max_transfer_size: that value only bounds the DMA
// buffer/descriptor allocation, not the SPI peripheral's own per-transaction bit-length
// register (e.g. 18 bits = 32768 bytes on ESP32-S3, 24 bits elsewhere) - so a large
// max-transfer-size in the devicetree (sized for e.g. an SD card) can still overflow a
// single spi_device_transmit() here. 4096 is safely under that hardware limit on every
// ESP32 variant.
constexpr size_t MAX_SPI_CHUNK_SIZE = 4096;
internal->max_transfer_size = (spi_config->max_transfer_size > 0 && static_cast<size_t>(spi_config->max_transfer_size) < MAX_SPI_CHUNK_SIZE)
? static_cast<size_t>(spi_config->max_transfer_size)
: MAX_SPI_CHUNK_SIZE;
gpio_config_t dc_config = {
.pin_bit_mask = 1ULL << internal->dc_pin,
.mode = GPIO_MODE_OUTPUT,
.pull_up_en = GPIO_PULLUP_DISABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE,
};
if (gpio_config(&dc_config) != ESP_OK) {
LOG_E(TAG, "Failed to configure DC pin");
free(internal);
return ERROR_RESOURCE;
}
spi_device_interface_config_t device_config = {
.mode = 0,
.clock_speed_hz = static_cast<int>(config->pixel_clock_hz),
.spics_io_num = pin_or_unused(cs_pin),
.flags = 0,
.queue_size = 1,
};
if (spi_bus_add_device(spi_config->host, &device_config, &internal->spi_handle) != ESP_OK) {
LOG_E(TAG, "Failed to add SPI device");
free(internal);
return ERROR_RESOURCE;
}
// Hardware reset, in addition to the SWRESET the bring-up command list sends
int reset_pin = pin_or_unused(config->pin_reset);
if (reset_pin != -1) {
gpio_config_t reset_config = {
.pin_bit_mask = 1ULL << reset_pin,
.mode = GPIO_MODE_OUTPUT,
.pull_up_en = GPIO_PULLUP_DISABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE,
};
if (gpio_config(&reset_config) != ESP_OK) {
LOG_E(TAG, "Failed to configure reset pin");
spi_bus_remove_device(internal->spi_handle);
free(internal);
return ERROR_RESOURCE;
}
gpio_set_level(static_cast<gpio_num_t>(reset_pin), config->reset_active_high ? 1 : 0);
vTaskDelay(pdMS_TO_TICKS(10));
gpio_set_level(static_cast<gpio_num_t>(reset_pin), config->reset_active_high ? 0 : 1);
vTaskDelay(pdMS_TO_TICKS(120));
}
internal->swap_xy = config->swap_xy;
internal->mirror_x = config->mirror_x;
internal->mirror_y = config->mirror_y;
run_init_cmds(internal);
send_madctl(internal);
send_cmd(internal, config->invert_color ? HX8357_INVON : HX8357_INVOFF);
device_set_driver_data(device, internal);
return ERROR_NONE;
}
static error_t stop(Device* device) {
auto* internal = static_cast<Hx8357Internal*>(device_get_driver_data(device));
if (spi_bus_remove_device(internal->spi_handle) != ESP_OK) {
LOG_E(TAG, "Failed to remove SPI device");
free(internal);
return ERROR_RESOURCE;
}
free(internal);
return ERROR_NONE;
}
// endregion
// region DisplayApi
static error_t hx8357_reset(Device*) {
// No standalone reset beyond what start_device() already does; matches the deprecated HAL
// (its reset() DisplayDevice override was never wired to anything beyond initial bring-up).
return ERROR_NONE;
}
static error_t hx8357_init(Device*) {
return ERROR_NONE;
}
static error_t hx8357_draw_bitmap(Device* device, int32_t x_start, int32_t y_start, int32_t x_end, int32_t y_end, const void* color_data) {
auto* internal = static_cast<Hx8357Internal*>(device_get_driver_data(device));
const auto* config = GET_CONFIG(device);
// x_end/y_end are exclusive (see lvgl_display.c); CASET/PASET want an inclusive last pixel.
const int32_t x1 = x_start + config->gap_x;
const int32_t x2 = x_end + config->gap_x - 1;
const int32_t y1 = y_start + config->gap_y;
const int32_t y2 = y_end + config->gap_y - 1;
const uint8_t xb[4] = {
static_cast<uint8_t>((x1 >> 8) & 0xFF), static_cast<uint8_t>(x1 & 0xFF),
static_cast<uint8_t>((x2 >> 8) & 0xFF), static_cast<uint8_t>(x2 & 0xFF),
};
const uint8_t yb[4] = {
static_cast<uint8_t>((y1 >> 8) & 0xFF), static_cast<uint8_t>(y1 & 0xFF),
static_cast<uint8_t>((y2 >> 8) & 0xFF), static_cast<uint8_t>(y2 & 0xFF),
};
send_cmd(internal, HX8357_CASET);
send_data(internal, xb, 4);
send_cmd(internal, HX8357_PASET);
send_data(internal, yb, 4);
send_cmd(internal, HX8357_RAMWR);
const size_t pixel_count = static_cast<size_t>(x_end - x_start) * static_cast<size_t>(y_end - y_start);
send_data(internal, static_cast<const uint8_t*>(color_data), pixel_count * 3); // RGB888 = 3 bytes/pixel
return ERROR_NONE;
}
static error_t hx8357_mirror(Device* device, bool x_axis, bool y_axis) {
auto* internal = static_cast<Hx8357Internal*>(device_get_driver_data(device));
internal->mirror_x = x_axis;
internal->mirror_y = y_axis;
send_madctl(internal);
return ERROR_NONE;
}
static error_t hx8357_swap_xy(Device* device, bool swap_axes) {
auto* internal = static_cast<Hx8357Internal*>(device_get_driver_data(device));
internal->swap_xy = swap_axes;
send_madctl(internal);
return ERROR_NONE;
}
// Reads the devicetree-configured baseline, not live hardware state - same convention as
// ili9341-module/st7789-module: mirror()/swap_xy() calls after start_device() don't change
// what "rotation 0" means here.
static bool hx8357_get_swap_xy(Device* device) {
return GET_CONFIG(device)->swap_xy;
}
static bool hx8357_get_mirror_x(Device* device) {
return GET_CONFIG(device)->mirror_x;
}
static bool hx8357_get_mirror_y(Device* device) {
return GET_CONFIG(device)->mirror_y;
}
static error_t hx8357_set_gap(Device*, int32_t, int32_t) {
// Not supported by this controller's fixed CASET/PASET-per-draw protocol beyond the static
// gap-x/gap-y devicetree config already folded into draw_bitmap(); matches the deprecated
// HAL, which never exposed a runtime gap either.
return ERROR_NOT_SUPPORTED;
}
static error_t hx8357_invert_color(Device* device, bool invert_color_data) {
auto* internal = static_cast<Hx8357Internal*>(device_get_driver_data(device));
send_cmd(internal, invert_color_data ? HX8357_INVON : HX8357_INVOFF);
return ERROR_NONE;
}
static error_t hx8357_disp_on_off(Device* device, bool on_off) {
auto* internal = static_cast<Hx8357Internal*>(device_get_driver_data(device));
send_cmd(internal, on_off ? HX8357_DISPON : 0x28 /* HX8357_DISPOFF */);
return ERROR_NONE;
}
static error_t hx8357_disp_sleep(Device* device, bool sleep) {
auto* internal = static_cast<Hx8357Internal*>(device_get_driver_data(device));
send_cmd(internal, sleep ? 0x10 /* HX8357_SLPIN */ : HX8357_SLPOUT);
return ERROR_NONE;
}
static enum DisplayColorFormat hx8357_get_color_format(Device*) {
return DISPLAY_COLOR_FORMAT_RGB888;
}
static uint16_t hx8357_get_resolution_x(Device* device) {
return GET_CONFIG(device)->horizontal_resolution;
}
static uint16_t hx8357_get_resolution_y(Device* device) {
return GET_CONFIG(device)->vertical_resolution;
}
static void hx8357_get_frame_buffer(Device*, uint8_t, void** out_buffer) {
*out_buffer = nullptr;
}
static uint8_t hx8357_get_frame_buffer_count(Device*) {
return 0;
}
static error_t hx8357_get_backlight(Device* device, Device** backlight) {
auto* configured_backlight = GET_CONFIG(device)->backlight;
if (configured_backlight == nullptr) {
return ERROR_NOT_SUPPORTED;
}
*backlight = configured_backlight;
return ERROR_NONE;
}
// endregion
static const DisplayApi hx8357_display_api = {
.reset = hx8357_reset,
.init = hx8357_init,
.draw_bitmap = hx8357_draw_bitmap,
.mirror = hx8357_mirror,
.swap_xy = hx8357_swap_xy,
.get_swap_xy = hx8357_get_swap_xy,
.get_mirror_x = hx8357_get_mirror_x,
.get_mirror_y = hx8357_get_mirror_y,
.set_gap = hx8357_set_gap,
.invert_color = hx8357_invert_color,
.disp_on_off = hx8357_disp_on_off,
.disp_sleep = hx8357_disp_sleep,
.get_color_format = hx8357_get_color_format,
.get_resolution_x = hx8357_get_resolution_x,
.get_resolution_y = hx8357_get_resolution_y,
.get_frame_buffer = hx8357_get_frame_buffer,
.get_frame_buffer_count = hx8357_get_frame_buffer_count,
.get_backlight = hx8357_get_backlight,
};
Driver hx8357_driver = {
.name = "hx8357",
.compatible = (const char*[]) { "himax,hx8357", nullptr },
.start_device = start,
.stop_device = stop,
.api = &hx8357_display_api,
.device_type = &DISPLAY_TYPE,
.owner = &hx8357_module,
.internal = nullptr
};
+32
View File
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: Apache-2.0
#include <tactility/check.h>
#include <tactility/driver.h>
#include <tactility/module.h>
extern Driver hx8357_driver;
extern "C" {
static error_t start() {
/* We crash when construct fails, because if a single driver fails to construct,
* there is no guarantee that the previously constructed drivers can be destroyed */
check(driver_construct_add(&hx8357_driver) == ERROR_NONE);
return ERROR_NONE;
}
static error_t stop() {
/* We crash when destruct fails, because if a single driver fails to destruct,
* there is no guarantee that the previously destroyed drivers can be recovered */
check(driver_remove_destruct(&hx8357_driver) == ERROR_NONE);
return ERROR_NONE;
}
Module hx8357_module = {
.name = "hx8357",
.start = start,
.stop = stop,
.symbols = nullptr,
.internal = nullptr
};
} // extern "C"
@@ -53,6 +53,12 @@ properties:
type: int
default: 10
description: Size of the internal SPI transaction queue
gamma-curve:
type: int
default: 1
min: 0
max: 3
description: Gamma curve preset index [0,3], sent via the MIPI DCS GAMSET (0x26) command at bring-up
pin-dc:
type: phandles
required: true
@@ -67,5 +73,5 @@ properties:
description: Whether the reset pin is active high
backlight:
type: phandle
default: NULL
default: "NULL"
description: Optional reference to this display's backlight device
@@ -24,6 +24,8 @@ struct Ili9341Config {
uint32_t bits_per_pixel;
uint32_t pixel_clock_hz;
uint8_t transaction_queue_depth;
// Gamma curve preset index [0,3], sent via the MIPI DCS GAMSET (0x26) command at bring-up.
uint8_t gamma_curve;
struct GpioPinSpec pin_dc;
struct GpioPinSpec pin_reset;
bool reset_active_high;
@@ -13,6 +13,7 @@
#include <esp_err.h>
#include <esp_lcd_io_spi.h>
#include <esp_lcd_panel_commands.h>
#include <esp_lcd_panel_io.h>
#include <esp_lcd_panel_ops.h>
#include <esp_lcd_ili9341.h>
@@ -25,6 +26,11 @@
#define GET_CONFIG(device) (static_cast<const Ili9341Config*>((device)->config))
// Maps gamma-curve devicetree index [0,3] to the MIPI DCS GAMSET (0x26) parameter value. Mirrors
// the deprecated HAL's EspLcdSpiDisplay::setGammaCurve() (Drivers/EspLcdCompat) - note the
// non-linear mapping, not index+1.
static const uint8_t GAMMA_CURVE_VALUES[4] = { 0x01, 0x04, 0x02, 0x08 };
struct Ili9341Internal {
esp_lcd_panel_io_handle_t io_handle;
esp_lcd_panel_handle_t panel_handle;
@@ -140,6 +146,7 @@ static error_t start(Device* device) {
ok = ok && (!config->swap_xy || esp_lcd_panel_swap_xy(internal->panel_handle, true) == ESP_OK);
ok = ok && ((!config->mirror_x && !config->mirror_y) || esp_lcd_panel_mirror(internal->panel_handle, config->mirror_x, config->mirror_y) == ESP_OK);
ok = ok && (!config->invert_color || esp_lcd_panel_invert_color(internal->panel_handle, true) == ESP_OK);
ok = ok && (config->gamma_curve >= 4 || esp_lcd_panel_io_tx_param(internal->io_handle, LCD_CMD_GAMSET, &GAMMA_CURVE_VALUES[config->gamma_curve], 1) == ESP_OK);
ok = ok && esp_lcd_panel_disp_on_off(internal->panel_handle, true) == ESP_OK;
if (!ok) {
@@ -71,5 +71,5 @@ properties:
description: Whether the reset pin is active high
backlight:
type: phandle
default: NULL
default: "NULL"
description: Optional reference to this display's backlight device
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 3.20)
include("${CMAKE_CURRENT_LIST_DIR}/../../Buildscripts/module.cmake")
file(GLOB_RECURSE SOURCE_FILES "source/*.c*")
tactility_add_module(st7789-i8080-module
SRCS ${SOURCE_FILES}
INCLUDE_DIRS include/
REQUIRES TactilityKernel platform-esp32 esp_lcd driver
)
@@ -0,0 +1,195 @@
Apache License
==============
_Version 2.0, January 2004_
_&lt;<http://www.apache.org/licenses/>&gt;_
### Terms and Conditions for use, reproduction, and distribution
#### 1. Definitions
“License” shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
“Licensor” shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
“Legal Entity” shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, “control” means **(i)** the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
outstanding shares, or **(iii)** beneficial ownership of such entity.
“You” (or “Your”) shall mean an individual or Legal Entity exercising
permissions granted by this License.
“Source” form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
“Object” form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
“Work” shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
“Derivative Works” shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
“Contribution” shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
“submitted” means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as “Not a Contribution.”
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
#### 2. Grant of Copyright License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
#### 3. Grant of Patent License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
#### 4. Redistribution
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
* **(a)** You must give any other recipients of the Work or Derivative Works a copy of
this License; and
* **(b)** You must cause any modified files to carry prominent notices stating that You
changed the files; and
* **(c)** You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
#### 5. Submission of Contributions
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
#### 6. Trademarks
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
#### 7. Disclaimer of Warranty
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
#### 8. Limitation of Liability
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
#### 9. Accepting Warranty or Additional Liability
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
_END OF TERMS AND CONDITIONS_
### APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets `[]` replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same “printed page” as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+5
View File
@@ -0,0 +1,5 @@
# ST7789 i8080 Display Driver
A kernel driver for the `ST7789` display panel over an i8080 (parallel) bus, built on ESP-IDF's `esp_lcd` component. Child of an i8080 bus controller device (e.g. `espressif,esp32-i8080` in `Platforms/platform-esp32`) - use `st7789-module` instead for SPI-attached ST7789 panels.
License: [Apache v2.0](LICENSE-Apache-2.0.md)
@@ -0,0 +1,69 @@
description: Sitronix ST7789 display panel over an i8080 (parallel) bus
compatible: "sitronix,st7789-i8080"
bus: i8080
properties:
horizontal-resolution:
type: int
required: true
description: Horizontal resolution in pixels
vertical-resolution:
type: int
required: true
description: Vertical resolution in pixels
gap-x:
type: int
default: 0
description: X offset applied to all draw operations
gap-y:
type: int
default: 0
description: Y offset applied to all draw operations
swap-xy:
type: boolean
default: false
description: Swap the X and Y axes
mirror-x:
type: boolean
default: false
description: Mirror the X axis
mirror-y:
type: boolean
default: false
description: Mirror the Y axis
invert-color:
type: boolean
default: false
description: Invert the panel's color output
bgr-order:
type: boolean
default: false
description: Use BGR element order instead of RGB
pixel-clock-hz:
type: int
default: 16000000
description: i80 bus write-clock frequency in Hz
transaction-queue-depth:
type: int
default: 10
description: Size of the internal transaction queue
gamma-curve:
type: int
default: 1
min: 0
max: 3
description: Gamma curve preset index [0,3], sent via the MIPI DCS GAMSET (0x26) command at bring-up
pin-reset:
type: phandles
default: GPIO_PIN_SPEC_NONE
description: Reset GPIO pin
reset-active-high:
type: boolean
default: false
description: Whether the reset pin is active high
backlight:
type: phandle
default: "NULL"
description: Optional reference to this display's backlight device
@@ -0,0 +1,3 @@
dependencies:
- TactilityKernel
bindings: bindings
@@ -0,0 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <tactility/bindings/bindings.h>
#include <drivers/st7789_i8080.h>
DEFINE_DEVICETREE(st7789_i8080, struct St7789I8080Config)
@@ -0,0 +1,36 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stdbool.h>
#include <tactility/device.h>
#include <tactility/drivers/gpio.h>
struct St7789I8080Config {
uint16_t horizontal_resolution;
uint16_t vertical_resolution;
int32_t gap_x;
int32_t gap_y;
bool swap_xy;
bool mirror_x;
bool mirror_y;
bool invert_color;
bool bgr_order;
uint32_t pixel_clock_hz;
uint8_t transaction_queue_depth;
// Gamma curve preset index [0,3], sent via the MIPI DCS GAMSET (0x26) command at bring-up.
uint8_t gamma_curve;
struct GpioPinSpec pin_reset;
bool reset_active_high;
// Optional reference to this display's backlight device, NULL if none.
struct Device* backlight;
};
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,14 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <tactility/module.h>
#ifdef __cplusplus
extern "C" {
#endif
extern struct Module st7789_i8080_module;
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: Apache-2.0
#include <tactility/check.h>
#include <tactility/driver.h>
#include <tactility/module.h>
extern "C" {
extern Driver st7789_i8080_driver;
static error_t start() {
/* We crash when construct fails, because if a single driver fails to construct,
* there is no guarantee that the previously constructed drivers can be destroyed */
check(driver_construct_add(&st7789_i8080_driver) == ERROR_NONE);
return ERROR_NONE;
}
static error_t stop() {
/* We crash when destruct fails, because if a single driver fails to destruct,
* there is no guarantee that the previously destroyed drivers can be recovered */
check(driver_remove_destruct(&st7789_i8080_driver) == ERROR_NONE);
return ERROR_NONE;
}
Module st7789_i8080_module = {
.name = "st7789_i8080",
.start = start,
.stop = stop,
.symbols = nullptr,
.internal = nullptr
};
} // extern "C"
@@ -0,0 +1,356 @@
// SPDX-License-Identifier: Apache-2.0
#include <drivers/st7789_i8080.h>
#include <st7789_i8080_module.h>
#include <tactility/check.h>
#include <tactility/device.h>
#include <tactility/driver.h>
#include <tactility/drivers/display.h>
#include <tactility/drivers/esp32_i8080.h>
#include <tactility/drivers/i8080_controller.h>
#include <tactility/error.h>
#include <tactility/log.h>
#include <esp_err.h>
#include <esp_lcd_panel_commands.h>
#include <esp_lcd_panel_io.h>
#include <esp_lcd_panel_ops.h>
#include <esp_lcd_panel_st7789.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <cstdlib>
#define TAG "ST7789I8080"
#define GET_CONFIG(device) (static_cast<const St7789I8080Config*>((device)->config))
// Maps gamma-curve devicetree index [0,3] to the MIPI DCS GAMSET (0x26) parameter value. Mirrors
// the deprecated HAL's EspLcdSpiDisplay::setGammaCurve() (Drivers/EspLcdCompat) - note the
// non-linear mapping, not index+1.
static const uint8_t GAMMA_CURVE_VALUES[4] = { 0x01, 0x04, 0x02, 0x08 };
namespace {
// Panel bring-up commands beyond esp_lcd_panel_init()'s generic ST7789 sequence: gate/porch/power
// control and gamma curves. Kept from the deprecated HAL's St7789i8080Display driver verbatim -
// likely panel-specific tuning for the exact glass used on LilyGO T-HMI boards, not guaranteed
// redundant with esp_lcd's built-in defaults, so preserved rather than dropped.
struct LcdInitCmd {
uint8_t cmd;
uint8_t data[14];
uint8_t len;
};
constexpr LcdInitCmd ST7789_INIT_CMDS[] = {
{0x36, {0x08}, 1},
{0x3A, {0x05}, 1},
{0x20, {0}, 0},
{0xB2, {0x0B, 0x0B, 0x00, 0x33, 0x33}, 5},
{0xB7, {0x75}, 1},
{0xBB, {0x28}, 1},
{0xC0, {0x2C}, 1},
{0xC2, {0x01}, 1},
{0xC3, {0x1F}, 1},
{0xC6, {0x13}, 1},
{0xD0, {0xA7}, 1},
{0xD0, {0xA4, 0xA1}, 2},
{0xD6, {0xA1}, 1},
{0xE0, {0xF0, 0x05, 0x0A, 0x06, 0x06, 0x03, 0x2B, 0x32, 0x43, 0x36, 0x11, 0x10, 0x2B, 0x32}, 14},
{0xE1, {0xF0, 0x08, 0x0C, 0x0B, 0x09, 0x24, 0x2B, 0x22, 0x43, 0x38, 0x15, 0x16, 0x2F, 0x37}, 14},
};
} // namespace
struct St7789I8080Internal {
esp_lcd_panel_io_handle_t io_handle;
esp_lcd_panel_handle_t panel_handle;
// See Ili9341Internal's identical field in ili9341-module for why this exists: draw_bitmap()
// must block until the transfer physically completes (DisplayApi's synchronous contract).
SemaphoreHandle_t draw_done_semaphore;
};
static bool IRAM_ATTR on_color_trans_done(esp_lcd_panel_io_handle_t, esp_lcd_panel_io_event_data_t*, void* user_ctx) {
auto* internal = static_cast<St7789I8080Internal*>(user_ctx);
BaseType_t high_task_woken = pdFALSE;
xSemaphoreGiveFromISR(internal->draw_done_semaphore, &high_task_woken);
return high_task_woken == pdTRUE;
}
static int pin_or_unused(const struct GpioPinSpec& pin) {
return pin.gpio_controller == nullptr ? -1 : static_cast<int>(pin.pin);
}
// region Driver lifecycle
static error_t start(Device* device) {
auto* parent = device_get_parent(device);
check(device_get_type(parent) == &I8080_CONTROLLER_TYPE);
esp_lcd_i80_bus_handle_t bus_handle;
if (esp32_i8080_get_bus_handle(device, &bus_handle) != ERROR_NONE) {
LOG_E(TAG, "Failed to resolve i80 bus handle");
return ERROR_RESOURCE;
}
struct GpioPinSpec cs_pin;
if (esp32_i8080_get_cs_pin(device, &cs_pin) != ERROR_NONE) {
LOG_E(TAG, "Failed to resolve CS pin");
return ERROR_RESOURCE;
}
const auto* config = GET_CONFIG(device);
auto* internal = static_cast<St7789I8080Internal*>(malloc(sizeof(St7789I8080Internal)));
if (internal == nullptr) {
return ERROR_OUT_OF_MEMORY;
}
internal->draw_done_semaphore = xSemaphoreCreateBinary();
if (internal->draw_done_semaphore == nullptr) {
free(internal);
return ERROR_OUT_OF_MEMORY;
}
esp_lcd_panel_io_i80_config_t io_config = {
.cs_gpio_num = pin_or_unused(cs_pin),
.pclk_hz = config->pixel_clock_hz,
.trans_queue_depth = config->transaction_queue_depth,
.on_color_trans_done = on_color_trans_done,
.user_ctx = internal,
.lcd_cmd_bits = 8,
.lcd_param_bits = 8,
.dc_levels = {
.dc_idle_level = 0,
.dc_cmd_level = 0,
.dc_dummy_level = 0,
.dc_data_level = 1,
},
.flags = {
.cs_active_high = 0,
.reverse_color_bits = 0,
.swap_color_bytes = 1,
.pclk_active_neg = 0,
.pclk_idle_low = 0,
},
};
esp_err_t ret = esp_lcd_new_panel_io_i80(bus_handle, &io_config, &internal->io_handle);
if (ret != ESP_OK) {
LOG_E(TAG, "Failed to create panel IO: %s", esp_err_to_name(ret));
vSemaphoreDelete(internal->draw_done_semaphore);
free(internal);
return ERROR_RESOURCE;
}
esp_lcd_panel_dev_config_t panel_config = {
.reset_gpio_num = pin_or_unused(config->pin_reset),
.rgb_ele_order = config->bgr_order ? LCD_RGB_ELEMENT_ORDER_BGR : LCD_RGB_ELEMENT_ORDER_RGB,
.data_endian = LCD_RGB_DATA_ENDIAN_LITTLE,
.bits_per_pixel = 16,
.flags = { .reset_active_high = config->reset_active_high },
.vendor_config = nullptr,
};
ret = esp_lcd_new_panel_st7789(internal->io_handle, &panel_config, &internal->panel_handle);
if (ret != ESP_OK) {
LOG_E(TAG, "Failed to create panel: %s", esp_err_to_name(ret));
esp_lcd_panel_io_del(internal->io_handle);
vSemaphoreDelete(internal->draw_done_semaphore);
free(internal);
return ERROR_RESOURCE;
}
// Bring-up sequence, order matches the deprecated HAL's St7789i8080Display (proven correct on
// real T-HMI hardware). Every failure path below must clean up fully, same reasoning as
// ili9341-module's start().
bool ok =
esp_lcd_panel_reset(internal->panel_handle) == ESP_OK &&
esp_lcd_panel_init(internal->panel_handle) == ESP_OK;
if (ok) {
for (const auto& init_cmd : ST7789_INIT_CMDS) {
if (esp_lcd_panel_io_tx_param(internal->io_handle, init_cmd.cmd, init_cmd.data, init_cmd.len) != ESP_OK) {
ok = false;
break;
}
}
}
if (ok) {
int gap_x = config->swap_xy ? config->gap_y : config->gap_x;
int gap_y = config->swap_xy ? config->gap_x : config->gap_y;
ok = (gap_x == 0 && gap_y == 0) || esp_lcd_panel_set_gap(internal->panel_handle, gap_x, gap_y) == ESP_OK;
}
ok = ok && (!config->swap_xy || esp_lcd_panel_swap_xy(internal->panel_handle, true) == ESP_OK);
ok = ok && ((!config->mirror_x && !config->mirror_y) || esp_lcd_panel_mirror(internal->panel_handle, config->mirror_x, config->mirror_y) == ESP_OK);
ok = ok && (!config->invert_color || esp_lcd_panel_invert_color(internal->panel_handle, true) == ESP_OK);
ok = ok && (config->gamma_curve >= 4 || esp_lcd_panel_io_tx_param(internal->io_handle, LCD_CMD_GAMSET, &GAMMA_CURVE_VALUES[config->gamma_curve], 1) == ESP_OK);
ok = ok && esp_lcd_panel_disp_on_off(internal->panel_handle, true) == ESP_OK;
if (!ok) {
LOG_E(TAG, "Failed to bring up panel");
esp_lcd_panel_del(internal->panel_handle);
esp_lcd_panel_io_del(internal->io_handle);
vSemaphoreDelete(internal->draw_done_semaphore);
free(internal);
return ERROR_RESOURCE;
}
device_set_driver_data(device, internal);
return ERROR_NONE;
}
static error_t stop(Device* device) {
auto* internal = static_cast<St7789I8080Internal*>(device_get_driver_data(device));
error_t result = ERROR_NONE;
if (esp_lcd_panel_del(internal->panel_handle) != ESP_OK) {
LOG_E(TAG, "Failed to delete panel");
result = ERROR_RESOURCE;
}
if (esp_lcd_panel_io_del(internal->io_handle) != ESP_OK) {
LOG_E(TAG, "Failed to delete panel IO");
result = ERROR_RESOURCE;
}
vSemaphoreDelete(internal->draw_done_semaphore);
free(internal);
return result;
}
// endregion
// region DisplayApi
static error_t st7789_i8080_reset(Device* device) {
auto* internal = static_cast<St7789I8080Internal*>(device_get_driver_data(device));
return esp_lcd_panel_reset(internal->panel_handle) == ESP_OK ? ERROR_NONE : ERROR_RESOURCE;
}
static error_t st7789_i8080_init(Device* device) {
auto* internal = static_cast<St7789I8080Internal*>(device_get_driver_data(device));
return esp_lcd_panel_init(internal->panel_handle) == ESP_OK ? ERROR_NONE : ERROR_RESOURCE;
}
static error_t st7789_i8080_draw_bitmap(Device* device, int32_t x_start, int32_t y_start, int32_t x_end, int32_t y_end, const void* color_data) {
auto* internal = static_cast<St7789I8080Internal*>(device_get_driver_data(device));
xSemaphoreTake(internal->draw_done_semaphore, 0);
if (esp_lcd_panel_draw_bitmap(internal->panel_handle, x_start, y_start, x_end, y_end, color_data) != ESP_OK) {
return ERROR_RESOURCE;
}
xSemaphoreTake(internal->draw_done_semaphore, portMAX_DELAY);
return ERROR_NONE;
}
static error_t st7789_i8080_mirror(Device* device, bool x_axis, bool y_axis) {
auto* internal = static_cast<St7789I8080Internal*>(device_get_driver_data(device));
return esp_lcd_panel_mirror(internal->panel_handle, x_axis, y_axis) == ESP_OK ? ERROR_NONE : ERROR_RESOURCE;
}
static error_t st7789_i8080_swap_xy(Device* device, bool swap_axes) {
auto* internal = static_cast<St7789I8080Internal*>(device_get_driver_data(device));
return esp_lcd_panel_swap_xy(internal->panel_handle, swap_axes) == ESP_OK ? ERROR_NONE : ERROR_RESOURCE;
}
static bool st7789_i8080_get_swap_xy(Device* device) {
return GET_CONFIG(device)->swap_xy;
}
static bool st7789_i8080_get_mirror_x(Device* device) {
return GET_CONFIG(device)->mirror_x;
}
static bool st7789_i8080_get_mirror_y(Device* device) {
return GET_CONFIG(device)->mirror_y;
}
static error_t st7789_i8080_set_gap(Device* device, int32_t x_gap, int32_t y_gap) {
auto* internal = static_cast<St7789I8080Internal*>(device_get_driver_data(device));
return esp_lcd_panel_set_gap(internal->panel_handle, x_gap, y_gap) == ESP_OK ? ERROR_NONE : ERROR_RESOURCE;
}
static error_t st7789_i8080_invert_color(Device* device, bool invert_color_data) {
auto* internal = static_cast<St7789I8080Internal*>(device_get_driver_data(device));
return esp_lcd_panel_invert_color(internal->panel_handle, invert_color_data) == ESP_OK ? ERROR_NONE : ERROR_RESOURCE;
}
static error_t st7789_i8080_disp_on_off(Device* device, bool on_off) {
auto* internal = static_cast<St7789I8080Internal*>(device_get_driver_data(device));
return esp_lcd_panel_disp_on_off(internal->panel_handle, on_off) == ESP_OK ? ERROR_NONE : ERROR_RESOURCE;
}
static error_t st7789_i8080_disp_sleep(Device* device, bool sleep) {
auto* internal = static_cast<St7789I8080Internal*>(device_get_driver_data(device));
return esp_lcd_panel_disp_sleep(internal->panel_handle, sleep) == ESP_OK ? ERROR_NONE : ERROR_RESOURCE;
}
// swap_color_bytes=1 in the panel IO config means the i80 peripheral itself byte-swaps each
// RGB565 pixel over the parallel bus, matching how ili9341-module's SPI variant needs
// RGB565_SWAPPED - same reasoning, different transport.
static enum DisplayColorFormat st7789_i8080_get_color_format(Device*) {
return DISPLAY_COLOR_FORMAT_RGB565_SWAPPED;
}
static uint16_t st7789_i8080_get_resolution_x(Device* device) {
return GET_CONFIG(device)->horizontal_resolution;
}
static uint16_t st7789_i8080_get_resolution_y(Device* device) {
return GET_CONFIG(device)->vertical_resolution;
}
static void st7789_i8080_get_frame_buffer(Device*, uint8_t, void** out_buffer) {
*out_buffer = nullptr;
}
static uint8_t st7789_i8080_get_frame_buffer_count(Device*) {
return 0;
}
static error_t st7789_i8080_get_backlight(Device* device, Device** backlight) {
auto* configured_backlight = GET_CONFIG(device)->backlight;
if (configured_backlight == nullptr) {
return ERROR_NOT_SUPPORTED;
}
*backlight = configured_backlight;
return ERROR_NONE;
}
// endregion
static const DisplayApi st7789_i8080_display_api = {
.reset = st7789_i8080_reset,
.init = st7789_i8080_init,
.draw_bitmap = st7789_i8080_draw_bitmap,
.mirror = st7789_i8080_mirror,
.swap_xy = st7789_i8080_swap_xy,
.get_swap_xy = st7789_i8080_get_swap_xy,
.get_mirror_x = st7789_i8080_get_mirror_x,
.get_mirror_y = st7789_i8080_get_mirror_y,
.set_gap = st7789_i8080_set_gap,
.invert_color = st7789_i8080_invert_color,
.disp_on_off = st7789_i8080_disp_on_off,
.disp_sleep = st7789_i8080_disp_sleep,
.get_color_format = st7789_i8080_get_color_format,
.get_resolution_x = st7789_i8080_get_resolution_x,
.get_resolution_y = st7789_i8080_get_resolution_y,
.get_frame_buffer = st7789_i8080_get_frame_buffer,
.get_frame_buffer_count = st7789_i8080_get_frame_buffer_count,
.get_backlight = st7789_i8080_get_backlight,
};
Driver st7789_i8080_driver = {
.name = "st7789_i8080",
.compatible = (const char*[]) { "sitronix,st7789-i8080", nullptr },
.start_device = start,
.stop_device = stop,
.api = &st7789_i8080_display_api,
.device_type = &DISPLAY_TYPE,
.owner = &st7789_i8080_module,
.internal = nullptr
};
@@ -53,6 +53,12 @@ properties:
type: int
default: 10
description: Size of the internal SPI transaction queue
gamma-curve:
type: int
default: 1
min: 0
max: 3
description: Gamma curve preset index [0,3], sent via the MIPI DCS GAMSET (0x26) command at bring-up
pin-dc:
type: phandles
required: true
@@ -67,5 +73,5 @@ properties:
description: Whether the reset pin is active high
backlight:
type: phandle
default: NULL
default: "NULL"
description: Optional reference to this display's backlight device
@@ -24,6 +24,8 @@ struct St7789Config {
uint32_t bits_per_pixel;
uint32_t pixel_clock_hz;
uint8_t transaction_queue_depth;
// Gamma curve preset index [0,3], sent via the MIPI DCS GAMSET (0x26) command at bring-up.
uint8_t gamma_curve;
struct GpioPinSpec pin_dc;
struct GpioPinSpec pin_reset;
bool reset_active_high;
+7
View File
@@ -13,6 +13,7 @@
#include <esp_err.h>
#include <esp_lcd_io_spi.h>
#include <esp_lcd_panel_commands.h>
#include <esp_lcd_panel_io.h>
#include <esp_lcd_panel_ops.h>
#include <esp_lcd_panel_st7789.h>
@@ -25,6 +26,11 @@
#define GET_CONFIG(device) (static_cast<const St7789Config*>((device)->config))
// Maps gamma-curve devicetree index [0,3] to the MIPI DCS GAMSET (0x26) parameter value. Mirrors
// the deprecated HAL's EspLcdSpiDisplay::setGammaCurve() (Drivers/EspLcdCompat) - note the
// non-linear mapping, not index+1.
static const uint8_t GAMMA_CURVE_VALUES[4] = { 0x01, 0x04, 0x02, 0x08 };
struct St7789Internal {
esp_lcd_panel_io_handle_t io_handle;
esp_lcd_panel_handle_t panel_handle;
@@ -140,6 +146,7 @@ static error_t start(Device* device) {
ok = ok && (!config->swap_xy || esp_lcd_panel_swap_xy(internal->panel_handle, true) == ESP_OK);
ok = ok && ((!config->mirror_x && !config->mirror_y) || esp_lcd_panel_mirror(internal->panel_handle, config->mirror_x, config->mirror_y) == ESP_OK);
ok = ok && (!config->invert_color || esp_lcd_panel_invert_color(internal->panel_handle, true) == ESP_OK);
ok = ok && (config->gamma_curve >= 4 || esp_lcd_panel_io_tx_param(internal->io_handle, LCD_CMD_GAMSET, &GAMMA_CURVE_VALUES[config->gamma_curve], 1) == ESP_OK);
ok = ok && esp_lcd_panel_disp_on_off(internal->panel_handle, true) == ESP_OK;
if (!ok) {
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 3.20)
include("${CMAKE_CURRENT_LIST_DIR}/../../Buildscripts/module.cmake")
file(GLOB_RECURSE SOURCE_FILES "source/*.c*")
tactility_add_module(tca95xx-16bit-module
SRCS ${SOURCE_FILES}
INCLUDE_DIRS include/
REQUIRES TactilityKernel
)
@@ -0,0 +1,195 @@
Apache License
==============
_Version 2.0, January 2004_
_&lt;<http://www.apache.org/licenses/>&gt;_
### Terms and Conditions for use, reproduction, and distribution
#### 1. Definitions
“License” shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
“Licensor” shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
“Legal Entity” shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, “control” means **(i)** the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
outstanding shares, or **(iii)** beneficial ownership of such entity.
“You” (or “Your”) shall mean an individual or Legal Entity exercising
permissions granted by this License.
“Source” form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
“Object” form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
“Work” shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
“Derivative Works” shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
“Contribution” shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
“submitted” means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as “Not a Contribution.”
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
#### 2. Grant of Copyright License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
#### 3. Grant of Patent License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
#### 4. Redistribution
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
* **(a)** You must give any other recipients of the Work or Derivative Works a copy of
this License; and
* **(b)** You must cause any modified files to carry prominent notices stating that You
changed the files; and
* **(c)** You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
#### 5. Submission of Contributions
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
#### 6. Trademarks
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
#### 7. Disclaimer of Warranty
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
#### 8. Limitation of Liability
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
#### 9. Accepting Warranty or Additional Liability
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
_END OF TERMS AND CONDITIONS_
### APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets `[]` replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same “printed page” as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+11
View File
@@ -0,0 +1,11 @@
# TCA9535 / TCA9539 I/O expander
A driver for the TI `TCA9535` and `TCA9539` 16-bit I2C-bus I/O expanders. Both parts
share the same PCA9555-compatible register map (differing only in package and interrupt
pin): two 8-bit ports for input, output, polarity inversion, and direction, addressed as
pins 0-15 (port 0 = pins 0-7, port 1 = pins 8-15).
It does not support pull-up/down resistors or high-impedance outputs; requesting those
flags returns `ERROR_NOT_SUPPORTED`.
License: [Apache v2.0](LICENSE-Apache-2.0.md)
@@ -0,0 +1,5 @@
description: TI TCA9535 16-bit I2C-bus I/O expander (PCA9555-register-compatible)
include: ["i2c-device.yaml"]
compatible: "ti,tca9535"
@@ -0,0 +1,5 @@
description: TI TCA9539 16-bit I2C-bus I/O expander (PCA9555-register-compatible)
include: ["i2c-device.yaml"]
compatible: "ti,tca9539"
@@ -0,0 +1,3 @@
dependencies:
- TactilityKernel
bindings: bindings
@@ -0,0 +1,21 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <tactility/bindings/bindings.h>
#include <drivers/tca95xx.h>
#ifdef __cplusplus
extern "C" {
#endif
// One DEFINE_DEVICETREE per compatible string -- the devicetree compiler derives the
// expected config typedef name from the compatible string's suffix (e.g. "ti,tca9535"
// -> tca9535_config_dt), not from a name we choose, so each supported chip needs its own
// typedef even though they share the same underlying config layout (see dummy-i2s-amp-module's
// bindings header for the same pattern).
DEFINE_DEVICETREE(tca9535, struct Tca95xxConfig)
DEFINE_DEVICETREE(tca9539, struct Tca95xxConfig)
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
struct Tca95xxConfig {
/** Address on bus */
uint8_t address;
};
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,16 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <tactility/module.h>
#ifdef __cplusplus
extern "C" {
#endif
// The devicetree compiler derives the expected module symbol name from this component's
// folder name ("tca95xx-16bit-module" -> tca95xx_16bit_module), not from a name we choose.
extern struct Module tca95xx_16bit_module;
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: Apache-2.0
#include <tactility/check.h>
#include <tactility/driver.h>
#include <tactility/module.h>
extern "C" {
extern Driver tca95xx_driver;
static error_t start() {
/* We crash when construct fails, because if a single driver fails to construct,
* there is no guarantee that the previously constructed drivers can be destroyed */
check(driver_construct_add(&tca95xx_driver) == ERROR_NONE);
return ERROR_NONE;
}
static error_t stop() {
/* We crash when destruct fails, because if a single driver fails to destruct,
* there is no guarantee that the previously destroyed drivers can be recovered */
check(driver_remove_destruct(&tca95xx_driver) == ERROR_NONE);
return ERROR_NONE;
}
Module tca95xx_16bit_module = {
.name = "tca95xx",
.start = start,
.stop = stop,
.symbols = nullptr,
.internal = nullptr
};
}
@@ -0,0 +1,194 @@
// SPDX-License-Identifier: Apache-2.0
#include <drivers/tca95xx.h>
#include <tca95xx_module.h>
#include <tactility/device.h>
#include <tactility/driver.h>
#include <tactility/drivers/gpio_controller.h>
#include <tactility/drivers/gpio_descriptor.h>
#include <tactility/drivers/i2c_controller.h>
#include <tactility/log.h>
#define TAG "TCA95XX"
#define GET_CONFIG(device) (static_cast<const Tca95xxConfig*>((device)->config))
// PCA9555-compatible register map: one register per function per 8-pin port.
constexpr auto TCA95XX_REGISTER_INPUT_PORT0 = 0x00;
constexpr auto TCA95XX_REGISTER_OUTPUT_PORT0 = 0x02;
constexpr auto TCA95XX_REGISTER_POLARITY_PORT0 = 0x04;
constexpr auto TCA95XX_REGISTER_CONFIG_PORT0 = 0x06;
static inline uint8_t port_of(GpioDescriptor* descriptor) {
return descriptor->pin >> 3;
}
static inline uint8_t bit_of(GpioDescriptor* descriptor) {
return 1 << (descriptor->pin & 0x7);
}
static error_t start(Device* device) {
auto* parent = device_get_parent(device);
check(device_get_type(parent) == &I2C_CONTROLLER_TYPE);
return gpio_controller_init_descriptors(device, 16, nullptr);
}
static error_t stop(Device* device) {
check(gpio_controller_deinit_descriptors(device) == ERROR_NONE);
return ERROR_NONE;
}
extern "C" {
static error_t set_level(GpioDescriptor* descriptor, bool high) {
auto* device = descriptor->controller;
auto* parent = device_get_parent(device);
auto address = GET_CONFIG(device)->address;
auto reg = static_cast<uint8_t>(TCA95XX_REGISTER_OUTPUT_PORT0 + port_of(descriptor));
auto bit = bit_of(descriptor);
// i2c_controller_register8_{set,reset}_bits() do a separate read then
// write; without this lock, concurrent updates to different pins on the
// same output port register can clobber each other.
device_lock(device);
error_t err = high
? i2c_controller_register8_set_bits(parent, address, reg, bit, portMAX_DELAY)
: i2c_controller_register8_reset_bits(parent, address, reg, bit, portMAX_DELAY);
device_unlock(device);
return err;
}
static error_t get_level(GpioDescriptor* descriptor, bool* high) {
auto* device = descriptor->controller;
auto* parent = device_get_parent(device);
auto address = GET_CONFIG(device)->address;
auto reg = static_cast<uint8_t>(TCA95XX_REGISTER_INPUT_PORT0 + port_of(descriptor));
uint8_t bits;
error_t err = i2c_controller_register8_get(parent, address, reg, &bits, portMAX_DELAY);
if (err != ERROR_NONE) {
return err;
}
*high = (bits & bit_of(descriptor)) != 0;
return ERROR_NONE;
}
static error_t set_flags(GpioDescriptor* descriptor, gpio_flags_t flags) {
// The TCA95xx only supports direction and polarity inversion. Pull-up/down and
// high-impedance are not present in its PCA9555-compatible register map.
if (flags & (GPIO_FLAG_PULL_UP | GPIO_FLAG_PULL_DOWN | GPIO_FLAG_HIGH_IMPEDANCE)) {
return ERROR_NOT_SUPPORTED;
}
// The polarity register only inverts what's read back from an input pin;
// set_level() still drives outputs at the raw level. Accepting ACTIVE_LOW
// on an output would silently not do what it implies.
if ((flags & GPIO_FLAG_ACTIVE_LOW) && (flags & GPIO_FLAG_DIRECTION_OUTPUT)) {
return ERROR_NOT_SUPPORTED;
}
auto* device = descriptor->controller;
auto* parent = device_get_parent(device);
auto address = GET_CONFIG(device)->address;
auto config_reg = static_cast<uint8_t>(TCA95XX_REGISTER_CONFIG_PORT0 + port_of(descriptor));
auto polarity_reg = static_cast<uint8_t>(TCA95XX_REGISTER_POLARITY_PORT0 + port_of(descriptor));
auto bit = bit_of(descriptor);
error_t err;
// Locked as a whole: direction and polarity are two separate RMW register
// writes, and both should apply atomically with respect to other set_flags
// / set_level calls on this device.
device_lock(device);
// Direction: configuration bit is 1 for input, 0 for output.
if (flags & GPIO_FLAG_DIRECTION_OUTPUT) {
err = i2c_controller_register8_reset_bits(parent, address, config_reg, bit, portMAX_DELAY);
} else {
err = i2c_controller_register8_set_bits(parent, address, config_reg, bit, portMAX_DELAY);
}
if (err != ERROR_NONE) {
device_unlock(device);
return err;
}
// Polarity inversion (mainly relevant for active-low inputs).
if (flags & GPIO_FLAG_ACTIVE_LOW) {
err = i2c_controller_register8_set_bits(parent, address, polarity_reg, bit, portMAX_DELAY);
} else {
err = i2c_controller_register8_reset_bits(parent, address, polarity_reg, bit, portMAX_DELAY);
}
device_unlock(device);
return err;
}
static error_t get_flags(GpioDescriptor* descriptor, gpio_flags_t* flags) {
auto* device = descriptor->controller;
auto* parent = device_get_parent(device);
auto address = GET_CONFIG(device)->address;
auto config_reg = static_cast<uint8_t>(TCA95XX_REGISTER_CONFIG_PORT0 + port_of(descriptor));
auto polarity_reg = static_cast<uint8_t>(TCA95XX_REGISTER_POLARITY_PORT0 + port_of(descriptor));
auto bit = bit_of(descriptor);
uint8_t val;
error_t err;
gpio_flags_t f = GPIO_FLAG_NONE;
err = i2c_controller_register8_get(parent, address, config_reg, &val, portMAX_DELAY);
if (err != ERROR_NONE) return err;
f |= (val & bit) ? GPIO_FLAG_DIRECTION_INPUT : GPIO_FLAG_DIRECTION_OUTPUT;
err = i2c_controller_register8_get(parent, address, polarity_reg, &val, portMAX_DELAY);
if (err != ERROR_NONE) return err;
f |= (val & bit) ? GPIO_FLAG_ACTIVE_LOW : GPIO_FLAG_ACTIVE_HIGH;
*flags = f;
return ERROR_NONE;
}
static error_t get_native_pin_number(GpioDescriptor* descriptor, void* pin_number) {
return ERROR_NOT_SUPPORTED;
}
static error_t add_callback(GpioDescriptor* descriptor, void (*callback)(void*), void* arg) {
return ERROR_NOT_SUPPORTED;
}
static error_t remove_callback(GpioDescriptor* descriptor) {
return ERROR_NOT_SUPPORTED;
}
static error_t enable_interrupt(GpioDescriptor* descriptor) {
return ERROR_NOT_SUPPORTED;
}
static error_t disable_interrupt(GpioDescriptor* descriptor) {
return ERROR_NOT_SUPPORTED;
}
const static GpioControllerApi tca95xx_gpio_api = {
.set_level = set_level,
.get_level = get_level,
.set_flags = set_flags,
.get_flags = get_flags,
.get_native_pin_number = get_native_pin_number,
.add_callback = add_callback,
.remove_callback = remove_callback,
.enable_interrupt = enable_interrupt,
.disable_interrupt = disable_interrupt
};
Driver tca95xx_driver = {
.name = "tca95xx",
.compatible = (const char*[]) { "ti,tca9535", "ti,tca9539", nullptr },
.start_device = start,
.stop_device = stop,
.api = static_cast<const void*>(&tca95xx_gpio_api),
.device_type = &GPIO_CONTROLLER_TYPE,
.owner = &tca95xx_16bit_module,
.internal = nullptr
};
}
@@ -25,3 +25,11 @@ properties:
type: boolean
default: false
description: Mirror the Y axis
power-supply:
type: boolean
default: false
description: Expose a power-supply device that reports battery voltage/capacity read from the XPT2046's v-bat input
power-supply-reference-voltage-mv:
type: int
default: 4200
description: Battery voltage (in mV) considered 100% capacity, used to compute POWER_SUPPLY_PROP_CAPACITY
@@ -14,6 +14,10 @@ struct Xpt2046Config {
bool swap_xy;
bool mirror_x;
bool mirror_y;
/** Expose a power-supply child device that reads battery voltage/capacity off the chip's v-bat input */
bool power_supply;
/** Battery voltage (mV) considered 100% capacity, used to derive POWER_SUPPLY_PROP_CAPACITY */
uint32_t power_supply_reference_voltage_mv;
};
#ifdef __cplusplus
+3
View File
@@ -6,17 +6,20 @@
extern "C" {
extern Driver xpt2046_driver;
extern Driver xpt2046_power_supply_driver;
static error_t start() {
/* We crash when construct fails, because if a single driver fails to construct,
* there is no guarantee that the previously constructed drivers can be destroyed */
check(driver_construct_add(&xpt2046_driver) == ERROR_NONE);
check(driver_construct_add(&xpt2046_power_supply_driver) == ERROR_NONE);
return ERROR_NONE;
}
static error_t stop() {
/* We crash when destruct fails, because if a single driver fails to destruct,
* there is no guarantee that the previously destroyed drivers can be recovered */
check(driver_remove_destruct(&xpt2046_power_supply_driver) == ERROR_NONE);
check(driver_remove_destruct(&xpt2046_driver) == ERROR_NONE);
return ERROR_NONE;
}
+152
View File
@@ -7,6 +7,7 @@
#include <tactility/driver.h>
#include <tactility/drivers/esp32_spi.h>
#include <tactility/drivers/pointer.h>
#include <tactility/drivers/power_supply.h>
#include <tactility/drivers/spi_controller.h>
#include <tactility/error.h>
#include <tactility/log.h>
@@ -17,15 +18,149 @@
#include <esp_lcd_touch_xpt2046.h>
#include <cstdlib>
#include <new>
#define TAG "XPT2046"
#define GET_CONFIG(device) (static_cast<const Xpt2046Config*>((device)->config))
// Rough LiPo discharge curve floor, used together with the configured reference voltage
// (the 100% point) to estimate a charge percentage from the sensed v-bat voltage.
#define POWER_SUPPLY_MIN_MV 3200
struct Xpt2046Internal {
esp_lcd_panel_io_handle_t io_handle;
esp_lcd_touch_handle_t touch_handle;
Device* power_supply_device;
};
// region Power supply
static bool ps_supports_property(Device*, PowerSupplyProperty property) {
return property == POWER_SUPPLY_PROP_VOLTAGE || property == POWER_SUPPLY_PROP_CAPACITY;
}
static int estimate_capacity_from_mv(int battery_mv, uint32_t reference_mv) {
if (battery_mv <= POWER_SUPPLY_MIN_MV) return 0;
if ((uint32_t)battery_mv >= reference_mv) return 100;
return (battery_mv - POWER_SUPPLY_MIN_MV) * 100 / ((int)reference_mv - POWER_SUPPLY_MIN_MV);
}
// The v-bat reading is noisy (shared ADC, no dedicated sample/hold), so it's smoothed by
// averaging over several samples rather than trusting a single conversion.
#define POWER_SUPPLY_SAMPLE_COUNT 20
static error_t read_battery_mv(esp_lcd_touch_handle_t touch_handle, int* out_mv) {
float volts_sum = 0.0f;
for (int i = 0; i < POWER_SUPPLY_SAMPLE_COUNT; i++) {
float volts;
if (esp_lcd_touch_xpt2046_read_battery_level(touch_handle, &volts) != ESP_OK) {
return ERROR_RESOURCE;
}
volts_sum += volts;
}
*out_mv = (int)((volts_sum / POWER_SUPPLY_SAMPLE_COUNT) * 1000.0f);
return ERROR_NONE;
}
static error_t ps_get_property(Device* device, PowerSupplyProperty property, PowerSupplyPropertyValue* out_value) {
if (property != POWER_SUPPLY_PROP_VOLTAGE && property != POWER_SUPPLY_PROP_CAPACITY) {
return ERROR_NOT_SUPPORTED;
}
auto* parent = device_get_parent(device);
const auto* parent_config = GET_CONFIG(parent);
auto* parent_internal = static_cast<Xpt2046Internal*>(device_get_driver_data(parent));
int battery_mv;
error_t error = read_battery_mv(parent_internal->touch_handle, &battery_mv);
if (error != ERROR_NONE) {
return error;
}
out_value->int_value = (property == POWER_SUPPLY_PROP_VOLTAGE) ? battery_mv : estimate_capacity_from_mv(battery_mv, parent_config->power_supply_reference_voltage_mv);
return ERROR_NONE;
}
static bool ps_supports_charge_control(Device*) { return false; }
static bool ps_is_allowed_to_charge(Device*) { return false; }
static error_t ps_set_allowed_to_charge(Device*, bool) { return ERROR_NOT_SUPPORTED; }
static bool ps_supports_quick_charge(Device*) { return false; }
static bool ps_is_quick_charge_enabled(Device*) { return false; }
static error_t ps_set_quick_charge_enabled(Device*, bool) { return ERROR_NOT_SUPPORTED; }
static bool ps_supports_power_off(Device*) { return false; }
static error_t ps_power_off(Device*) { return ERROR_NOT_SUPPORTED; }
static constexpr PowerSupplyApi XPT2046_POWER_SUPPLY_API = {
.supports_property = ps_supports_property,
.get_property = ps_get_property,
.supports_charge_control = ps_supports_charge_control,
.is_allowed_to_charge = ps_is_allowed_to_charge,
.set_allowed_to_charge = ps_set_allowed_to_charge,
.supports_quick_charge = ps_supports_quick_charge,
.is_quick_charge_enabled = ps_is_quick_charge_enabled,
.set_quick_charge_enabled = ps_set_quick_charge_enabled,
.supports_power_off = ps_supports_power_off,
.power_off = ps_power_off,
};
// Registered (driver_construct_add() in module.cpp) so driver_bind() has a valid ->internal,
// but never matched against a devicetree node: xpt2046 wires it up directly by pointer.
Driver xpt2046_power_supply_driver = {
.name = "xpt2046-power-supply",
.compatible = (const char*[]) { "xpt2046-power-supply", nullptr },
.start_device = nullptr,
.stop_device = nullptr,
.api = &XPT2046_POWER_SUPPLY_API,
.device_type = &POWER_SUPPLY_TYPE,
.owner = &xpt2046_module,
.internal = nullptr
};
static error_t create_power_supply_child(Device* parent, Device*& out_child) {
auto* child = new(std::nothrow) Device { .address = 0, .name = "xpt2046-power-supply", .config = nullptr, .parent = nullptr, .internal = nullptr };
if (child == nullptr) {
return ERROR_OUT_OF_MEMORY;
}
error_t error = device_construct(child);
if (error != ERROR_NONE) {
delete child;
return error;
}
device_set_parent(child, parent);
device_set_driver(child, &xpt2046_power_supply_driver);
error = device_add(child);
if (error != ERROR_NONE) {
device_destruct(child);
delete child;
return error;
}
error = device_start(child);
if (error != ERROR_NONE) {
device_remove(child);
device_destruct(child);
delete child;
return error;
}
out_child = child;
return ERROR_NONE;
}
static void destroy_power_supply_child(Device* child) {
check(device_stop(child) == ERROR_NONE);
check(device_remove(child) == ERROR_NONE);
check(device_destruct(child) == ERROR_NONE);
delete child;
}
// endregion
// region Driver lifecycle
static error_t start(Device* device) {
@@ -82,13 +217,30 @@ static error_t start(Device* device) {
return ERROR_RESOURCE;
}
internal->power_supply_device = nullptr;
device_set_driver_data(device, internal);
if (config->power_supply) {
error_t error = create_power_supply_child(device, internal->power_supply_device);
if (error != ERROR_NONE) {
LOG_E(TAG, "Failed to create power-supply device");
esp_lcd_touch_del(internal->touch_handle);
esp_lcd_panel_io_del(internal->io_handle);
free(internal);
return error;
}
}
return ERROR_NONE;
}
static error_t stop(Device* device) {
auto* internal = static_cast<Xpt2046Internal*>(device_get_driver_data(device));
if (internal->power_supply_device != nullptr) {
destroy_power_supply_child(internal->power_supply_device);
}
bool ok = true;
// esp_lcd_touch_del() only releases the touch-side resources; the panel IO handle is owned
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 3.20)
include("${CMAKE_CURRENT_LIST_DIR}/../../Buildscripts/module.cmake")
file(GLOB_RECURSE SOURCE_FILES "source/*.c*")
tactility_add_module(xpt2046-softspi-module
SRCS ${SOURCE_FILES}
INCLUDE_DIRS include/
REQUIRES TactilityKernel platform-esp32 driver
)
@@ -0,0 +1,195 @@
Apache License
==============
_Version 2.0, January 2004_
_&lt;<http://www.apache.org/licenses/>&gt;_
### Terms and Conditions for use, reproduction, and distribution
#### 1. Definitions
“License” shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
“Licensor” shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
“Legal Entity” shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, “control” means **(i)** the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
outstanding shares, or **(iii)** beneficial ownership of such entity.
“You” (or “Your”) shall mean an individual or Legal Entity exercising
permissions granted by this License.
“Source” form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
“Object” form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
“Work” shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
“Derivative Works” shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
“Contribution” shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
“submitted” means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as “Not a Contribution.”
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
#### 2. Grant of Copyright License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
#### 3. Grant of Patent License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
#### 4. Redistribution
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
* **(a)** You must give any other recipients of the Work or Derivative Works a copy of
this License; and
* **(b)** You must cause any modified files to carry prominent notices stating that You
changed the files; and
* **(c)** You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
#### 5. Submission of Contributions
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
#### 6. Trademarks
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
#### 7. Disclaimer of Warranty
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
#### 8. Limitation of Liability
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
#### 9. Accepting Warranty or Additional Liability
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
_END OF TERMS AND CONDITIONS_
### APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets `[]` replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same “printed page” as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+9
View File
@@ -0,0 +1,9 @@
# XPT2046 Software SPI Touch Driver
A kernel driver for the `XPT2046` resistive touch controller, bit-banged over plain GPIO pins instead of a hardware SPI peripheral. Use this instead of `xpt2046-module` when no SPI host is free for touch (e.g. both `SPI2_HOST` and `SPI3_HOST` are already claimed by the display and an SD card).
No reset or interrupt pin support (matches the controller's typical wiring: polled, no dedicated IRQ line wired on most panels using it).
See https://grobotronics.com/images/datasheets/xpt2046-datasheet.pdf
License: [Apache v2.0](LICENSE-Apache-2.0.md)
@@ -0,0 +1,52 @@
description: >
XPT2046 resistive touch controller driven over bit-banged (software) SPI on plain GPIO
pins, for boards where no hardware SPI peripheral is available for touch (e.g. both
SPI2_HOST and SPI3_HOST are already claimed by the display and SD card).
compatible: "xptek,xpt2046-softspi"
properties:
pin-mosi:
type: phandles
required: true
description: MOSI (controller-out, peripheral-in) GPIO pin
pin-miso:
type: phandles
required: true
description: MISO (controller-in, peripheral-out) GPIO pin
pin-sck:
type: phandles
required: true
description: Clock GPIO pin
pin-cs:
type: phandles
required: true
description: Chip-select GPIO pin
x-max:
type: int
required: true
description: Maximum X coordinate reported by the controller (typically the panel's horizontal resolution)
y-max:
type: int
required: true
description: Maximum Y coordinate reported by the controller (typically the panel's vertical resolution)
swap-xy:
type: boolean
default: false
description: Swap the X and Y axes
mirror-x:
type: boolean
default: false
description: Mirror the X axis
mirror-y:
type: boolean
default: false
description: Mirror the Y axis
power-supply:
type: boolean
default: false
description: Expose a power-supply device that reports battery voltage/capacity read from the XPT2046's v-bat input
power-supply-reference-voltage-mv:
type: int
default: 4200
description: Battery voltage (in mV) considered 100% capacity, used to compute POWER_SUPPLY_PROP_CAPACITY
@@ -0,0 +1,3 @@
dependencies:
- TactilityKernel
bindings: bindings
@@ -0,0 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <tactility/bindings/bindings.h>
#include <drivers/xpt2046_softspi.h>
DEFINE_DEVICETREE(xpt2046_softspi, struct Xpt2046SoftSpiConfig)
@@ -0,0 +1,31 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stdbool.h>
#include <tactility/drivers/gpio.h>
struct Xpt2046SoftSpiConfig {
struct GpioPinSpec pin_mosi;
struct GpioPinSpec pin_miso;
struct GpioPinSpec pin_sck;
struct GpioPinSpec pin_cs;
uint16_t x_max;
uint16_t y_max;
bool swap_xy;
bool mirror_x;
bool mirror_y;
/** Expose a power-supply child device that reads battery voltage/capacity off the chip's v-bat input */
bool power_supply;
/** Battery voltage (mV) considered 100% capacity, used to derive POWER_SUPPLY_PROP_CAPACITY */
uint32_t power_supply_reference_voltage_mv;
};
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,14 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <tactility/module.h>
#ifdef __cplusplus
extern "C" {
#endif
extern struct Module xpt2046_softspi_module;
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,35 @@
// SPDX-License-Identifier: Apache-2.0
#include <tactility/check.h>
#include <tactility/driver.h>
#include <tactility/module.h>
extern "C" {
extern Driver xpt2046_softspi_driver;
extern Driver xpt2046_softspi_power_supply_driver;
static error_t start() {
/* We crash when construct fails, because if a single driver fails to construct,
* there is no guarantee that the previously constructed drivers can be destroyed */
check(driver_construct_add(&xpt2046_softspi_driver) == ERROR_NONE);
check(driver_construct_add(&xpt2046_softspi_power_supply_driver) == ERROR_NONE);
return ERROR_NONE;
}
static error_t stop() {
/* We crash when destruct fails, because if a single driver fails to destruct,
* there is no guarantee that the previously destroyed drivers can be recovered */
check(driver_remove_destruct(&xpt2046_softspi_power_supply_driver) == ERROR_NONE);
check(driver_remove_destruct(&xpt2046_softspi_driver) == ERROR_NONE);
return ERROR_NONE;
}
Module xpt2046_softspi_module = {
.name = "xpt2046_softspi",
.start = start,
.stop = stop,
.symbols = nullptr,
.internal = nullptr
};
} // extern "C"
@@ -0,0 +1,444 @@
// SPDX-License-Identifier: Apache-2.0
#include <drivers/xpt2046_softspi.h>
#include <xpt2046_softspi_module.h>
#include <tactility/check.h>
#include <tactility/device.h>
#include <tactility/driver.h>
#include <tactility/drivers/gpio_controller.h>
#include <tactility/drivers/pointer.h>
#include <tactility/drivers/power_supply.h>
#include <tactility/delay.h>
#include <tactility/error.h>
#include <tactility/log.h>
#include <cstdlib>
#include <new>
#define TAG "XPT2046SoftSPI"
#define GET_CONFIG(device) (static_cast<const Xpt2046SoftSpiConfig*>((device)->config))
// Rough LiPo discharge curve floor, used together with the configured reference voltage
// (the 100% point) to estimate a charge percentage from the sensed v-bat voltage.
#define POWER_SUPPLY_MIN_MV 3200
namespace {
constexpr uint8_t CMD_READ_X = 0xD0;
constexpr uint8_t CMD_READ_Y = 0x90;
// BATTERY register (start=1, addr=010, 12-bit mode, single-ended, PD1=0/PD0=1 i.e. IRQ disabled
// between conversions), same encoding as the hardware-SPI XPT2046 driver's default mode.
constexpr uint8_t CMD_READ_BATTERY = 0xA7;
constexpr int RAW_MIN_DEFAULT = 100;
constexpr int RAW_MAX_DEFAULT = 1900;
constexpr int RAW_VALID_MIN = 100;
constexpr int RAW_VALID_MAX = 3900;
constexpr int SAMPLE_COUNT = 8;
} // namespace
struct Xpt2046SoftSpiInternal {
GpioDescriptor* mosi;
GpioDescriptor* miso;
GpioDescriptor* sck;
GpioDescriptor* cs;
bool swap_xy;
bool mirror_x;
bool mirror_y;
bool touched;
uint16_t x;
uint16_t y;
Device* power_supply_device;
};
static error_t create_power_supply_child(Device* parent, Device*& out_child);
static void destroy_power_supply_child(Device* child);
// region Driver lifecycle
static void release_descriptors(Xpt2046SoftSpiInternal* internal) {
if (internal->mosi != nullptr) gpio_descriptor_release(internal->mosi);
if (internal->miso != nullptr) gpio_descriptor_release(internal->miso);
if (internal->sck != nullptr) gpio_descriptor_release(internal->sck);
if (internal->cs != nullptr) gpio_descriptor_release(internal->cs);
}
static error_t start(Device* device) {
const auto* config = GET_CONFIG(device);
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(malloc(sizeof(Xpt2046SoftSpiInternal)));
if (internal == nullptr) {
return ERROR_OUT_OF_MEMORY;
}
*internal = {};
internal->mosi = gpio_descriptor_acquire(config->pin_mosi.gpio_controller, config->pin_mosi.pin, GPIO_OWNER_GPIO);
internal->miso = gpio_descriptor_acquire(config->pin_miso.gpio_controller, config->pin_miso.pin, GPIO_OWNER_GPIO);
internal->sck = gpio_descriptor_acquire(config->pin_sck.gpio_controller, config->pin_sck.pin, GPIO_OWNER_GPIO);
internal->cs = gpio_descriptor_acquire(config->pin_cs.gpio_controller, config->pin_cs.pin, GPIO_OWNER_GPIO);
if (internal->mosi == nullptr || internal->miso == nullptr || internal->sck == nullptr || internal->cs == nullptr) {
LOG_E(TAG, "Failed to acquire GPIO descriptors");
release_descriptors(internal);
free(internal);
return ERROR_RESOURCE;
}
bool ok =
gpio_descriptor_set_flags(internal->mosi, GPIO_FLAG_DIRECTION_OUTPUT) == ERROR_NONE &&
gpio_descriptor_set_flags(internal->sck, GPIO_FLAG_DIRECTION_OUTPUT) == ERROR_NONE &&
gpio_descriptor_set_flags(internal->cs, GPIO_FLAG_DIRECTION_OUTPUT) == ERROR_NONE &&
gpio_descriptor_set_flags(internal->miso, GPIO_FLAG_DIRECTION_INPUT | GPIO_FLAG_PULL_UP) == ERROR_NONE;
// Idle state: CS high (deselected), SCK/MOSI low.
ok = ok &&
gpio_descriptor_set_level(internal->cs, true) == ERROR_NONE &&
gpio_descriptor_set_level(internal->sck, false) == ERROR_NONE &&
gpio_descriptor_set_level(internal->mosi, false) == ERROR_NONE;
if (!ok) {
LOG_E(TAG, "Failed to configure GPIO pins");
release_descriptors(internal);
free(internal);
return ERROR_RESOURCE;
}
internal->swap_xy = config->swap_xy;
internal->mirror_x = config->mirror_x;
internal->mirror_y = config->mirror_y;
device_set_driver_data(device, internal);
if (config->power_supply) {
error_t error = create_power_supply_child(device, internal->power_supply_device);
if (error != ERROR_NONE) {
LOG_E(TAG, "Failed to create power-supply device");
release_descriptors(internal);
free(internal);
return error;
}
}
return ERROR_NONE;
}
static error_t stop(Device* device) {
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
if (internal->power_supply_device != nullptr) {
destroy_power_supply_child(internal->power_supply_device);
}
release_descriptors(internal);
free(internal);
return ERROR_NONE;
}
// endregion
// region Bit-banged SPI
// XPT2046 protocol: 8-bit command out, 12-bit conversion result back (MSB first), clocked
// manually since no hardware SPI peripheral is available for this pin set (see the binding's
// description). 1us clock half-period is well within the XPT2046's timing budget (it's rated
// for a multi-MHz SPI clock; this bit-bang loop runs orders of magnitude slower).
static int read_spi_command(Xpt2046SoftSpiInternal* internal, uint8_t command) {
int result = 0;
gpio_descriptor_set_level(internal->cs, false);
delay_micros(1);
for (int i = 7; i >= 0; i--) {
gpio_descriptor_set_level(internal->mosi, (command & (1 << i)) != 0);
gpio_descriptor_set_level(internal->sck, true);
delay_micros(1);
gpio_descriptor_set_level(internal->sck, false);
delay_micros(1);
}
for (int i = 11; i >= 0; i--) {
gpio_descriptor_set_level(internal->sck, true);
delay_micros(1);
bool level = false;
gpio_descriptor_get_level(internal->miso, &level);
if (level) {
result |= (1 << i);
}
gpio_descriptor_set_level(internal->sck, false);
delay_micros(1);
}
gpio_descriptor_set_level(internal->cs, true);
return result;
}
// endregion
// region Power supply
// The v-bat reading is noisy (bit-banged SPI, no dedicated sample/hold), so it's smoothed by
// averaging over several samples rather than trusting a single conversion.
#define POWER_SUPPLY_SAMPLE_COUNT 20
// Same scaling as the hardware-SPI XPT2046 driver's esp_lcd_touch_xpt2046_read_battery_level():
// the chip halves the v-bat voltage internally, and the raw code is relative to its internal
// 2.507V reference over 12 bits.
static int read_battery_mv(Xpt2046SoftSpiInternal* internal) {
int64_t raw_sum = 0;
for (int i = 0; i < POWER_SUPPLY_SAMPLE_COUNT; i++) {
raw_sum += read_spi_command(internal, CMD_READ_BATTERY);
}
int64_t raw_avg = raw_sum / POWER_SUPPLY_SAMPLE_COUNT;
return (int)((raw_avg * 4 * 2507) / 4096);
}
static bool ps_supports_property(Device*, PowerSupplyProperty property) {
return property == POWER_SUPPLY_PROP_VOLTAGE || property == POWER_SUPPLY_PROP_CAPACITY;
}
static int estimate_capacity_from_mv(int battery_mv, uint32_t reference_mv) {
if (battery_mv <= POWER_SUPPLY_MIN_MV) return 0;
if ((uint32_t)battery_mv >= reference_mv) return 100;
return (battery_mv - POWER_SUPPLY_MIN_MV) * 100 / ((int)reference_mv - POWER_SUPPLY_MIN_MV);
}
static error_t ps_get_property(Device* device, PowerSupplyProperty property, PowerSupplyPropertyValue* out_value) {
if (property != POWER_SUPPLY_PROP_VOLTAGE && property != POWER_SUPPLY_PROP_CAPACITY) {
return ERROR_NOT_SUPPORTED;
}
auto* parent = device_get_parent(device);
const auto* parent_config = GET_CONFIG(parent);
auto* parent_internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(parent));
int battery_mv = read_battery_mv(parent_internal);
out_value->int_value = (property == POWER_SUPPLY_PROP_VOLTAGE) ? battery_mv : estimate_capacity_from_mv(battery_mv, parent_config->power_supply_reference_voltage_mv);
return ERROR_NONE;
}
static bool ps_supports_charge_control(Device*) { return false; }
static bool ps_is_allowed_to_charge(Device*) { return false; }
static error_t ps_set_allowed_to_charge(Device*, bool) { return ERROR_NOT_SUPPORTED; }
static bool ps_supports_quick_charge(Device*) { return false; }
static bool ps_is_quick_charge_enabled(Device*) { return false; }
static error_t ps_set_quick_charge_enabled(Device*, bool) { return ERROR_NOT_SUPPORTED; }
static bool ps_supports_power_off(Device*) { return false; }
static error_t ps_power_off(Device*) { return ERROR_NOT_SUPPORTED; }
static constexpr PowerSupplyApi XPT2046_SOFTSPI_POWER_SUPPLY_API = {
.supports_property = ps_supports_property,
.get_property = ps_get_property,
.supports_charge_control = ps_supports_charge_control,
.is_allowed_to_charge = ps_is_allowed_to_charge,
.set_allowed_to_charge = ps_set_allowed_to_charge,
.supports_quick_charge = ps_supports_quick_charge,
.is_quick_charge_enabled = ps_is_quick_charge_enabled,
.set_quick_charge_enabled = ps_set_quick_charge_enabled,
.supports_power_off = ps_supports_power_off,
.power_off = ps_power_off,
};
// Registered (driver_construct_add() in module.cpp) so driver_bind() has a valid ->internal,
// but never matched against a devicetree node: xpt2046_softspi wires it up directly by pointer.
Driver xpt2046_softspi_power_supply_driver = {
.name = "xpt2046-softspi-power-supply",
.compatible = (const char*[]) { "xpt2046-softspi-power-supply", nullptr },
.start_device = nullptr,
.stop_device = nullptr,
.api = &XPT2046_SOFTSPI_POWER_SUPPLY_API,
.device_type = &POWER_SUPPLY_TYPE,
.owner = &xpt2046_softspi_module,
.internal = nullptr
};
static error_t create_power_supply_child(Device* parent, Device*& out_child) {
auto* child = new(std::nothrow) Device { .address = 0, .name = "xpt2046-softspi-power-supply", .config = nullptr, .parent = nullptr, .internal = nullptr };
if (child == nullptr) {
return ERROR_OUT_OF_MEMORY;
}
error_t error = device_construct(child);
if (error != ERROR_NONE) {
delete child;
return error;
}
device_set_parent(child, parent);
device_set_driver(child, &xpt2046_softspi_power_supply_driver);
error = device_add(child);
if (error != ERROR_NONE) {
device_destruct(child);
delete child;
return error;
}
error = device_start(child);
if (error != ERROR_NONE) {
device_remove(child);
device_destruct(child);
delete child;
return error;
}
out_child = child;
return ERROR_NONE;
}
static void destroy_power_supply_child(Device* child) {
check(device_stop(child) == ERROR_NONE);
check(device_remove(child) == ERROR_NONE);
check(device_destruct(child) == ERROR_NONE);
delete child;
}
// endregion
// region PointerApi
static error_t xpt2046_softspi_enter_sleep(Device*) {
// No software-controlled power-down for this bit-banged variant; nothing to do.
return ERROR_NONE;
}
static error_t xpt2046_softspi_exit_sleep(Device*) {
return ERROR_NONE;
}
// Takes and averages several raw samples (rejecting out-of-range noise) then maps them onto
// [0, x_max]/[0, y_max], applying swap/mirror. Mirrors the deprecated HAL's Xpt2046SoftSpi driver.
static error_t xpt2046_softspi_read_data(Device* device, TickType_t timeout) {
(void)timeout;
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
const auto* config = GET_CONFIG(device);
int total_x = 0;
int total_y = 0;
int valid_samples = 0;
for (int i = 0; i < SAMPLE_COUNT; i++) {
const int raw_x = read_spi_command(internal, CMD_READ_X);
const int raw_y = read_spi_command(internal, CMD_READ_Y);
if (raw_x > RAW_VALID_MIN && raw_x < RAW_VALID_MAX && raw_y > RAW_VALID_MIN && raw_y < RAW_VALID_MAX) {
total_x += raw_x;
total_y += raw_y;
valid_samples++;
}
delay_millis(1);
}
if (valid_samples < 3) {
internal->touched = false;
return ERROR_NONE;
}
const int raw_x = total_x / valid_samples;
const int raw_y = total_y / valid_samples;
int mapped_x = (raw_x - RAW_MIN_DEFAULT) * static_cast<int>(config->x_max) / (RAW_MAX_DEFAULT - RAW_MIN_DEFAULT);
int mapped_y = (raw_y - RAW_MIN_DEFAULT) * static_cast<int>(config->y_max) / (RAW_MAX_DEFAULT - RAW_MIN_DEFAULT);
if (internal->swap_xy) {
const int swapped = mapped_x;
mapped_x = mapped_y;
mapped_y = swapped;
}
if (internal->mirror_x) {
mapped_x = static_cast<int>(config->x_max) - mapped_x;
}
if (internal->mirror_y) {
mapped_y = static_cast<int>(config->y_max) - mapped_y;
}
if (mapped_x < 0) mapped_x = 0;
if (mapped_x > static_cast<int>(config->x_max)) mapped_x = static_cast<int>(config->x_max);
if (mapped_y < 0) mapped_y = 0;
if (mapped_y > static_cast<int>(config->y_max)) mapped_y = static_cast<int>(config->y_max);
internal->x = static_cast<uint16_t>(mapped_x);
internal->y = static_cast<uint16_t>(mapped_y);
internal->touched = true;
return ERROR_NONE;
}
static bool xpt2046_softspi_get_touched_points(Device* device, uint16_t* x, uint16_t* y, uint16_t* strength, uint8_t* point_count, uint8_t max_point_count) {
(void)strength;
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
if (!internal->touched || max_point_count < 1) {
*point_count = 0;
return false;
}
*x = internal->x;
*y = internal->y;
*point_count = 1;
return true;
}
static error_t xpt2046_softspi_set_swap_xy(Device* device, bool swap) {
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
internal->swap_xy = swap;
return ERROR_NONE;
}
static error_t xpt2046_softspi_get_swap_xy(Device* device, bool* swap) {
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
*swap = internal->swap_xy;
return ERROR_NONE;
}
static error_t xpt2046_softspi_set_mirror_x(Device* device, bool mirror) {
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
internal->mirror_x = mirror;
return ERROR_NONE;
}
static error_t xpt2046_softspi_get_mirror_x(Device* device, bool* mirror) {
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
*mirror = internal->mirror_x;
return ERROR_NONE;
}
static error_t xpt2046_softspi_set_mirror_y(Device* device, bool mirror) {
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
internal->mirror_y = mirror;
return ERROR_NONE;
}
static error_t xpt2046_softspi_get_mirror_y(Device* device, bool* mirror) {
auto* internal = static_cast<Xpt2046SoftSpiInternal*>(device_get_driver_data(device));
*mirror = internal->mirror_y;
return ERROR_NONE;
}
// endregion
static const PointerApi xpt2046_softspi_pointer_api = {
.enter_sleep = xpt2046_softspi_enter_sleep,
.exit_sleep = xpt2046_softspi_exit_sleep,
.read_data = xpt2046_softspi_read_data,
.get_touched_points = xpt2046_softspi_get_touched_points,
.set_swap_xy = xpt2046_softspi_set_swap_xy,
.get_swap_xy = xpt2046_softspi_get_swap_xy,
.set_mirror_x = xpt2046_softspi_set_mirror_x,
.get_mirror_x = xpt2046_softspi_get_mirror_x,
.set_mirror_y = xpt2046_softspi_set_mirror_y,
.get_mirror_y = xpt2046_softspi_get_mirror_y,
};
Driver xpt2046_softspi_driver = {
.name = "xpt2046_softspi",
.compatible = (const char*[]) { "xptek,xpt2046-softspi", nullptr },
.start_device = start,
.stop_device = stop,
.api = &xpt2046_softspi_pointer_api,
.device_type = &POINTER_TYPE,
.owner = &xpt2046_softspi_module,
.internal = nullptr
};