Rename Boards/ to Devices/ (#414)

This commit is contained in:
Ken Van Hoeylandt
2025-11-13 23:50:43 +01:00
committed by GitHub
parent c7c9618f48
commit c1ff024657
314 changed files with 105 additions and 99 deletions
+7
View File
@@ -0,0 +1,7 @@
file(GLOB_RECURSE SOURCE_FILES Source/*.c*)
idf_component_register(
SRCS ${SOURCE_FILES}
INCLUDE_DIRS "Source"
REQUIRES Tactility esp_lvgl_port esp_io_expander esp_io_expander_tca95xx_16bit BQ24295 XPT2046
)
+85
View File
@@ -0,0 +1,85 @@
#include "UnPhoneFeatures.h"
#include "devices/Hx8357Display.h"
#include "devices/SdCard.h"
#include <Tactility/hal/Configuration.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Xpt2046Power.h>
#define UNPHONE_SPI_TRANSFER_SIZE_LIMIT (UNPHONE_LCD_HORIZONTAL_RESOLUTION * UNPHONE_LCD_SPI_TRANSFER_HEIGHT * LV_COLOR_DEPTH / 8)
bool initBoot();
static tt::hal::DeviceVector createDevices() {
return {
std::make_shared<Xpt2046Power>(),
createDisplay(),
createSdCard()
};
}
extern const tt::hal::Configuration hardwareConfiguration = {
.initBoot = initBoot,
.createDevices = createDevices,
.i2c = {
tt::hal::i2c::Configuration {
.name = "Internal",
.port = I2C_NUM_0,
.initMode = tt::hal::i2c::InitMode::ByTactility,
.isMutable = false,
.config = (i2c_config_t) {
.mode = I2C_MODE_MASTER,
.sda_io_num = GPIO_NUM_3,
.scl_io_num = GPIO_NUM_4,
.sda_pullup_en = true,
.scl_pullup_en = true,
.master = {
.clk_speed = 400000
},
.clk_flags = 0
}
},
tt::hal::i2c::Configuration {
.name = "Unused",
.port = I2C_NUM_1,
.initMode = tt::hal::i2c::InitMode::Disabled,
.isMutable = true,
.config = (i2c_config_t) {
.mode = I2C_MODE_MASTER,
.sda_io_num = GPIO_NUM_NC,
.scl_io_num = GPIO_NUM_NC,
.sda_pullup_en = false,
.scl_pullup_en = false,
.master = {
.clk_speed = 400000
},
.clk_flags = 0
}
}
},
.spi {
tt::hal::spi::Configuration {
.device = SPI2_HOST,
.dma = SPI_DMA_CH_AUTO,
.config = {
.mosi_io_num = GPIO_NUM_40,
.miso_io_num = GPIO_NUM_41,
.sclk_io_num = GPIO_NUM_39,
.quadwp_io_num = -1, // Quad SPI LCD driver is not yet supported
.quadhd_io_num = -1, // Quad SPI LCD driver is not yet supported
.data4_io_num = GPIO_NUM_NC,
.data5_io_num = GPIO_NUM_NC,
.data6_io_num = GPIO_NUM_NC,
.data7_io_num = GPIO_NUM_NC,
.data_io_default_level = false,
.max_transfer_sz = UNPHONE_SPI_TRANSFER_SIZE_LIMIT,
.flags = 0,
.isr_cpu_id = ESP_INTR_CPU_AFFINITY_AUTO,
.intr_flags = 0
},
.initMode = tt::hal::spi::InitMode::ByTactility,
.isMutable = false,
.lock = tt::lvgl::getSyncLock() // esp_lvgl_port owns the lock for the display
}
}
};
+194
View File
@@ -0,0 +1,194 @@
#include "UnPhoneFeatures.h"
#include <Tactility/Preferences.h>
#include <Tactility/TactilityCore.h>
#include <esp_sleep.h>
constexpr auto* TAG = "unPhone";
std::shared_ptr<UnPhoneFeatures> unPhoneFeatures;
static std::unique_ptr<tt::Thread> powerThread;
static const char* bootCountKey = "boot_count";
static const char* powerOffCountKey = "power_off_count";
static const char* powerSleepKey = "power_sleep_key";
class DeviceStats {
tt::Preferences preferences = tt::Preferences("unphone");
int32_t getValue(const char* key) {
int32_t value = 0;
preferences.optInt32(key, value);
return value;
}
void setValue(const char* key, int32_t value) {
preferences.putInt32(key, value);
}
void increaseValue(const char* key) {
int32_t new_value = getValue(key) + 1;
setValue(key, new_value);
}
public:
void notifyBootStart() {
increaseValue(bootCountKey);
}
void notifyPowerOff() {
increaseValue(powerOffCountKey);
}
void notifyPowerSleep() {
increaseValue(powerSleepKey);
}
void printInfo() {
TT_LOG_I("TAG", "Device stats:");
TT_LOG_I("TAG", " boot: %ld", getValue(bootCountKey));
TT_LOG_I("TAG", " power off: %ld", getValue(powerOffCountKey));
TT_LOG_I("TAG", " power sleep: %ld", getValue(powerSleepKey));
}
};
DeviceStats bootStats;
enum class PowerState {
Initial,
On,
Off
};
#define DEBUG_POWER_STATES false
#if DEBUG_POWER_STATES
/** Helper method to use the buzzer to signal the different power stages */
static void powerInfoBuzz(uint8_t count) {
if (DEBUG_POWER_STATES) {
uint8_t index = 0;
while (index < count) {
unPhoneFeatures.setVibePower(true);
tt::kernel::delayMillis(50);
unPhoneFeatures.setVibePower(false);
index++;
if (index < count) {
tt::kernel::delayMillis(100);
}
}
}
}
#endif
static void updatePowerSwitch() {
static PowerState last_state = PowerState::Initial;
if (!unPhoneFeatures->isPowerSwitchOn()) {
if (last_state != PowerState::Off) {
last_state = PowerState::Off;
TT_LOG_W(TAG, "Power off");
}
if (!unPhoneFeatures->isUsbPowerConnected()) { // and usb unplugged we go into shipping mode
TT_LOG_W(TAG, "Shipping mode until USB connects");
#if DEBUG_POWER_STATES
unPhoneFeatures.setExpanderPower(true);
powerInfoBuzz(3);
unPhoneFeatures.setExpanderPower(false);
#endif
unPhoneFeatures->turnPeripheralsOff();
bootStats.notifyPowerOff();
unPhoneFeatures->setShipping(true); // tell BM to stop supplying power until USB connects
} else { // When power switch is off, but USB is plugged in, we wait (deep sleep) until USB is unplugged.
TT_LOG_W(TAG, "Waiting for USB disconnect to power off");
#if DEBUG_POWER_STATES
powerInfoBuzz(2);
#endif
unPhoneFeatures->turnPeripheralsOff();
bootStats.notifyPowerSleep();
// Deep sleep for 1 minute, then awaken to check power state again
// GPIO trigger from power switch also awakens the device
unPhoneFeatures->wakeOnPowerSwitch();
esp_sleep_enable_timer_wakeup(60000000);
esp_deep_sleep_start();
}
} else {
if (last_state != PowerState::On) {
last_state = PowerState::On;
TT_LOG_W(TAG, "Power on");
#if DEBUG_POWER_STATES
powerInfoBuzz(1);
#endif
}
}
}
static int32_t powerSwitchMain() { // check power switch every 10th of sec
while (true) {
updatePowerSwitch();
tt::kernel::delayMillis(200);
}
}
static void startPowerSwitchThread() {
powerThread = std::make_unique<tt::Thread>(
"unphone_power_switch",
4096,
[]() { return powerSwitchMain(); }
);
powerThread->start();
}
std::shared_ptr<Bq24295> bq24295;
static bool unPhonePowerOn() {
// Print early, in case of early crash (info will be from previous boot)
bootStats.printInfo();
bootStats.notifyBootStart();
bq24295 = std::make_shared<Bq24295>(I2C_NUM_0);
unPhoneFeatures = std::make_shared<UnPhoneFeatures>(bq24295);
if (!unPhoneFeatures->init()) {
TT_LOG_E(TAG, "UnPhoneFeatures init failed");
return false;
}
unPhoneFeatures->printInfo();
unPhoneFeatures->setBacklightPower(false);
unPhoneFeatures->setVibePower(false);
unPhoneFeatures->setIrPower(false);
unPhoneFeatures->setExpanderPower(false);
// Turn off the device if power switch is on off state,
// instead of waiting for the Thread to start and continue booting
updatePowerSwitch();
startPowerSwitchThread();
return true;
}
bool initBoot() {
ESP_LOGI(TAG, LOG_MESSAGE_POWER_ON_START);
if (!unPhonePowerOn()) {
TT_LOG_E(TAG, LOG_MESSAGE_POWER_ON_FAILED);
return false;
}
return true;
}
+302
View File
@@ -0,0 +1,302 @@
#include "UnPhoneFeatures.h"
#include <Tactility/app/App.h>
#include <Tactility/Log.h>
#include <Tactility/kernel/Kernel.h>
#include <driver/gpio.h>
#include <driver/rtc_io.h>
#include <esp_sleep.h>
namespace pin {
static const gpio_num_t BUTTON1 = GPIO_NUM_45; // left button
static const gpio_num_t BUTTON2 = GPIO_NUM_0; // middle button
static const gpio_num_t BUTTON3 = GPIO_NUM_21; // right button
static const gpio_num_t IR_LEDS = GPIO_NUM_12;
static const gpio_num_t LED_RED = GPIO_NUM_13;
static const gpio_num_t POWER_SWITCH = GPIO_NUM_18;
} // namespace pin
namespace expanderpin {
static const esp_io_expander_pin_num_t BACKLIGHT = IO_EXPANDER_PIN_NUM_2;
static const esp_io_expander_pin_num_t EXPANDER_POWER = IO_EXPANDER_PIN_NUM_0; // enable exp brd if high
static const esp_io_expander_pin_num_t LED_GREEN = IO_EXPANDER_PIN_NUM_9;
static const esp_io_expander_pin_num_t LED_BLUE = IO_EXPANDER_PIN_NUM_13;
static const esp_io_expander_pin_num_t USB_VSENSE = IO_EXPANDER_PIN_NUM_14;
static const esp_io_expander_pin_num_t VIBE = IO_EXPANDER_PIN_NUM_7;
} // namespace expanderpin
#define TAG "unhpone_features"
// TODO: Make part of a new type of UnPhoneFeatures data struct that holds all the thread-related data
QueueHandle_t interruptQueue;
static void IRAM_ATTR navButtonInterruptHandler(void* args) {
int pinNumber = (int)args;
xQueueSendFromISR(interruptQueue, &pinNumber, NULL);
}
static int32_t buttonHandlingThreadMain(void* context) {
auto* interrupted = (bool*)context;
int pinNumber;
while (!*interrupted) {
if (xQueueReceive(interruptQueue, &pinNumber, portMAX_DELAY)) {
// The buttons might generate more than 1 click because of how they are built
TT_LOG_I(TAG, "Pressed button %d", pinNumber);
if (pinNumber == pin::BUTTON1) {
tt::app::stop();
}
// Debounce all events for a short period of time
// This is easier than keeping track when each button was last pressed
tt::kernel::delayMillis(50);
xQueueReset(interruptQueue);
tt::kernel::delayMillis(50);
xQueueReset(interruptQueue);
}
}
return 0;
}
UnPhoneFeatures::~UnPhoneFeatures() {
if (buttonHandlingThread.getState() != tt::Thread::State::Stopped) {
buttonHandlingThreadInterruptRequest = true;
buttonHandlingThread.join();
}
}
bool UnPhoneFeatures::initPowerSwitch() {
gpio_config_t config = {
.pin_bit_mask = BIT64(pin::POWER_SWITCH),
.mode = GPIO_MODE_INPUT,
.pull_up_en = GPIO_PULLUP_DISABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_POSEDGE,
};
if (gpio_config(&config) != ESP_OK) {
TT_LOG_E(TAG, "Power pin init failed");
return false;
}
if (rtc_gpio_pullup_en(pin::POWER_SWITCH) == ESP_OK &&
rtc_gpio_pulldown_en(pin::POWER_SWITCH) == ESP_OK) {
return true;
} else {
TT_LOG_E(TAG, "Failed to set RTC for power switch");
return false;
}
}
bool UnPhoneFeatures::initNavButtons() {
if (!initGpioExpander()) {
TT_LOG_E(TAG, "GPIO expander init failed");
return false;
}
interruptQueue = xQueueCreate(4, sizeof(int));
buttonHandlingThread.setName("unphone_buttons");
buttonHandlingThread.setPriority(tt::Thread::Priority::High);
buttonHandlingThread.setStackSize(3072);
buttonHandlingThread.setCallback(buttonHandlingThreadMain, &buttonHandlingThreadInterruptRequest);
buttonHandlingThread.start();
uint64_t pin_mask =
BIT64(pin::BUTTON1) |
BIT64(pin::BUTTON2) |
BIT64(pin::BUTTON3);
gpio_config_t config = {
.pin_bit_mask = pin_mask,
.mode = GPIO_MODE_INPUT,
.pull_up_en = GPIO_PULLUP_ENABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
/**
* We have to listen to the button release (= positive signal).
* If we listen to button press, the buttons might create more than 1 signal
* when they are continuously pressed.
*/
.intr_type = GPIO_INTR_POSEDGE,
};
if (gpio_config(&config) != ESP_OK) {
TT_LOG_E(TAG, "Nav button pin init failed");
return false;
}
if (
gpio_install_isr_service(0) != ESP_OK ||
gpio_isr_handler_add(pin::BUTTON1, navButtonInterruptHandler, (void*)pin::BUTTON1) != ESP_OK ||
gpio_isr_handler_add(pin::BUTTON2, navButtonInterruptHandler, (void*)pin::BUTTON2) != ESP_OK ||
gpio_isr_handler_add(pin::BUTTON3, navButtonInterruptHandler, (void*)pin::BUTTON3) != ESP_OK
) {
TT_LOG_E(TAG, "Nav buttons ISR init failed");
return false;
}
return true;
}
bool UnPhoneFeatures::initOutputPins() {
uint64_t output_pin_mask =
BIT64(pin::IR_LEDS) |
BIT64(pin::LED_RED);
gpio_config_t config = {
.pin_bit_mask = output_pin_mask,
.mode = GPIO_MODE_OUTPUT,
.pull_up_en = GPIO_PULLUP_DISABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE,
};
if (gpio_config(&config) != ESP_OK) {
TT_LOG_E(TAG, "Output pin init failed");
return false;
}
return true;
}
bool UnPhoneFeatures::initGpioExpander() {
// ESP_IO_EXPANDER_I2C_TCA9555_ADDRESS_110 corresponds with 0x26 from the docs at
// https://gitlab.com/hamishcunningham/unphonelibrary/-/blob/main/unPhone.h?ref_type=heads#L206
if (esp_io_expander_new_i2c_tca95xx_16bit(I2C_NUM_0, ESP_IO_EXPANDER_I2C_TCA9555_ADDRESS_110, &ioExpander) != ESP_OK) {
TT_LOG_E(TAG, "IO expander init failed");
return false;
}
assert(ioExpander != nullptr);
// Output pins
/**
* Important:
* If you clear the pins too late, the display or vibration motor might briefly turn on.
*/
esp_io_expander_set_dir(ioExpander, expanderpin::BACKLIGHT, IO_EXPANDER_OUTPUT);
esp_io_expander_set_level(ioExpander, expanderpin::BACKLIGHT, 0);
esp_io_expander_set_dir(ioExpander, expanderpin::EXPANDER_POWER, IO_EXPANDER_OUTPUT);
esp_io_expander_set_dir(ioExpander, expanderpin::LED_GREEN, IO_EXPANDER_OUTPUT);
esp_io_expander_set_level(ioExpander, expanderpin::LED_GREEN, 0);
esp_io_expander_set_dir(ioExpander, expanderpin::LED_BLUE, IO_EXPANDER_OUTPUT);
esp_io_expander_set_level(ioExpander, expanderpin::LED_BLUE, 0);
esp_io_expander_set_dir(ioExpander, expanderpin::VIBE, IO_EXPANDER_OUTPUT);
esp_io_expander_set_level(ioExpander, expanderpin::VIBE, 0);
// Input pins
esp_io_expander_set_dir(ioExpander, expanderpin::USB_VSENSE, IO_EXPANDER_INPUT);
return true;
}
bool UnPhoneFeatures::init() {
TT_LOG_I(TAG, "init");
if (!initGpioExpander()) {
TT_LOG_E(TAG, "GPIO expander init failed");
return false;
}
if (!initNavButtons()) {
TT_LOG_E(TAG, "Input pin init failed");
return false;
}
if (!initOutputPins()) {
TT_LOG_E(TAG, "Output pin init failed");
return false;
}
if (!initPowerSwitch()) {
TT_LOG_E(TAG, "Power button init failed");
return false;
}
return true;
}
void UnPhoneFeatures::printInfo() const {
esp_io_expander_print_state(ioExpander);
batteryManagement->printInfo();
bool backlight_power;
const char* backlight_power_state = getBacklightPower(backlight_power) && backlight_power ? "on" : "off";
TT_LOG_I(TAG, "Backlight: %s", backlight_power_state);
}
bool UnPhoneFeatures::setRgbLed(bool red, bool green, bool blue) const {
assert(ioExpander != nullptr);
return gpio_set_level(pin::LED_RED, red ? 1U : 0U) == ESP_OK &&
esp_io_expander_set_level(ioExpander, expanderpin::LED_GREEN, green ? 1U : 0U) == ESP_OK &&
esp_io_expander_set_level(ioExpander, expanderpin::LED_BLUE, blue ? 1U : 0U) == ESP_OK;
}
bool UnPhoneFeatures::setBacklightPower(bool on) const {
assert(ioExpander != nullptr);
return esp_io_expander_set_level(ioExpander, expanderpin::BACKLIGHT, on ? 1U : 0U) == ESP_OK;
}
bool UnPhoneFeatures::getBacklightPower(bool& on) const {
assert(ioExpander != nullptr);
uint32_t level_mask;
if (esp_io_expander_get_level(ioExpander, expanderpin::BACKLIGHT, &level_mask) == ESP_OK) {
on = level_mask != 0U;
return true;
} else {
return false;
}
}
bool UnPhoneFeatures::setIrPower(bool on) const {
assert(ioExpander != nullptr);
return gpio_set_level(pin::IR_LEDS, on ? 1U : 0U) == ESP_OK;
}
bool UnPhoneFeatures::setVibePower(bool on) const {
assert(ioExpander != nullptr);
return esp_io_expander_set_level(ioExpander, expanderpin::VIBE, on ? 1U : 0U) == ESP_OK;
}
bool UnPhoneFeatures::setExpanderPower(bool on) const {
assert(ioExpander != nullptr);
return esp_io_expander_set_level(ioExpander, expanderpin::EXPANDER_POWER, on ? 1U : 0U) == ESP_OK;
}
bool UnPhoneFeatures::isPowerSwitchOn() const {
return gpio_get_level(pin::POWER_SWITCH) > 0;
}
void UnPhoneFeatures::turnPeripheralsOff() const {
setExpanderPower(false);
setBacklightPower(false);
setIrPower(false);
setRgbLed(false, false, false);
setVibePower(false);
}
bool UnPhoneFeatures::setShipping(bool on) const {
if (on) {
TT_LOG_W(TAG, "setShipping: on");
batteryManagement->setWatchDogTimer(Bq24295::WatchDogTimer::Disabled);
batteryManagement->setBatFetOn(false);
} else {
TT_LOG_W(TAG, "setShipping: off");
batteryManagement->setWatchDogTimer(Bq24295::WatchDogTimer::Enabled40s);
batteryManagement->setBatFetOn(true);
}
return true;
}
void UnPhoneFeatures::wakeOnPowerSwitch() const {
esp_sleep_enable_ext0_wakeup(pin::POWER_SWITCH, 1);
}
bool UnPhoneFeatures::isUsbPowerConnected() const {
return batteryManagement->isUsbPowerConnected();
}
+55
View File
@@ -0,0 +1,55 @@
#pragma once
#include <Bq24295.h>
#include <Tactility/Thread.h>
#include <esp_io_expander_tca95xx_16bit.h>
/**
* Easy access to GPIO pins
*/
class UnPhoneFeatures final {
private:
esp_io_expander_handle_t ioExpander = nullptr;
tt::Thread buttonHandlingThread;
bool buttonHandlingThreadInterruptRequest = false;
bool initNavButtons();
static bool initOutputPins();
static bool initPowerSwitch();
bool initGpioExpander();
std::shared_ptr<Bq24295> batteryManagement;
public:
explicit UnPhoneFeatures(std::shared_ptr<Bq24295> bq24295) : batteryManagement(std::move(bq24295)) {
assert(batteryManagement != nullptr);
}
~UnPhoneFeatures();
bool init();
bool setBacklightPower(bool on) const;
bool getBacklightPower(bool& on) const;
bool setIrPower(bool on) const;
bool setVibePower(bool on) const;
bool setExpanderPower(bool on) const;
bool isPowerSwitchOn() const;
void turnPeripheralsOff() const;
/** Battery management (BQ24295) will stop supplying power until USB connects */
bool setShipping(bool on) const;
void wakeOnPowerSwitch() const;
bool isUsbPowerConnected() const;
bool setRgbLed(bool red, bool green, bool blue) const;
void printInfo() const;
};
@@ -0,0 +1,118 @@
#include "Hx8357Display.h"
#include "Touch.h"
#include <UnPhoneFeatures.h>
#include <Tactility/Log.h>
#include <hx8357/disp_spi.h>
#include <hx8357/hx8357.h>
constexpr auto TAG = "Hx8357Display";
constexpr auto BUFFER_SIZE = (UNPHONE_LCD_HORIZONTAL_RESOLUTION * UNPHONE_LCD_DRAW_BUFFER_HEIGHT * LV_COLOR_DEPTH / 8);
extern std::shared_ptr<UnPhoneFeatures> unPhoneFeatures;
bool Hx8357Display::start() {
TT_LOG_I(TAG, "start");
disp_spi_add_device(SPI2_HOST);
hx8357_reset(GPIO_NUM_46);
hx8357_init(UNPHONE_LCD_PIN_DC);
uint8_t madctl = (1U << MADCTL_BIT_INDEX_COLUMN_ADDRESS_ORDER);
hx8357_set_madctl(madctl);
return true;
}
bool Hx8357Display::stop() {
TT_LOG_I(TAG, "stop");
disp_spi_remove_device();
return true;
}
bool Hx8357Display::startLvgl() {
TT_LOG_I(TAG, "startLvgl");
if (lvglDisplay != nullptr) {
TT_LOG_W(TAG, "LVGL was already started");
return false;
}
lvglDisplay = lv_display_create(UNPHONE_LCD_HORIZONTAL_RESOLUTION, UNPHONE_LCD_VERTICAL_RESOLUTION);
lv_display_set_physical_resolution(lvglDisplay, UNPHONE_LCD_HORIZONTAL_RESOLUTION, UNPHONE_LCD_VERTICAL_RESOLUTION);
lv_display_set_color_format(lvglDisplay, LV_COLOR_FORMAT_NATIVE);
// TODO malloc to use SPIRAM
buffer = static_cast<uint8_t*>(heap_caps_malloc(BUFFER_SIZE, MALLOC_CAP_DMA));
assert(buffer != nullptr);
lv_display_set_buffers(
lvglDisplay,
buffer,
nullptr,
BUFFER_SIZE,
LV_DISPLAY_RENDER_MODE_PARTIAL
);
lv_display_set_flush_cb(lvglDisplay, hx8357_flush);
if (lvglDisplay == nullptr) {
TT_LOG_I(TAG, "Failed");
return false;
}
unPhoneFeatures->setBacklightPower(true);
auto touch_device = getTouchDevice();
if (touch_device != nullptr) {
touch_device->startLvgl(lvglDisplay);
}
return true;
}
bool Hx8357Display::stopLvgl() {
TT_LOG_I(TAG, "stopLvgl");
if (lvglDisplay == nullptr) {
TT_LOG_W(TAG, "LVGL was already stopped");
return false;
}
// Just in case
disp_wait_for_pending_transactions();
auto touch_device = getTouchDevice();
if (touch_device != nullptr && touch_device->getLvglIndev() != nullptr) {
TT_LOG_I(TAG, "Stopping touch device");
touch_device->stopLvgl();
}
lv_display_delete(lvglDisplay);
lvglDisplay = nullptr;
heap_caps_free(buffer);
buffer = nullptr;
return true;
}
std::shared_ptr<tt::hal::touch::TouchDevice> _Nullable Hx8357Display::getTouchDevice() {
if (touchDevice == nullptr) {
touchDevice = std::reinterpret_pointer_cast<tt::hal::touch::TouchDevice>(createTouch());
TT_LOG_I(TAG, "Created touch device");
}
return touchDevice;
}
std::shared_ptr<tt::hal::display::DisplayDevice> createDisplay() {
return std::make_shared<Hx8357Display>();
}
bool Hx8357Display::Hx8357Driver::drawBitmap(int xStart, int yStart, int xEnd, int yEnd, const void* pixelData) {
lv_area_t area = { xStart, yStart, xEnd, yEnd };
hx8357_flush(nullptr, &area, (uint8_t*)pixelData);
return true;
}
@@ -0,0 +1,70 @@
#pragma once
#include <Tactility/hal/display/DisplayDevice.h>
#include <Tactility/hal/display/DisplayDriver.h>
#include <Tactility/Mutex.h>
#include <esp_lcd_types.h>
#include <lvgl.h>
#include <Tactility/hal/spi/Spi.h>
#define UNPHONE_LCD_SPI_HOST SPI2_HOST
#define UNPHONE_LCD_PIN_CS GPIO_NUM_48
#define UNPHONE_LCD_PIN_DC GPIO_NUM_47
#define UNPHONE_LCD_PIN_RESET GPIO_NUM_46
#define UNPHONE_LCD_SPI_FREQUENCY 27000000
#define UNPHONE_LCD_HORIZONTAL_RESOLUTION 320
#define UNPHONE_LCD_VERTICAL_RESOLUTION 480
#define UNPHONE_LCD_DRAW_BUFFER_HEIGHT (UNPHONE_LCD_VERTICAL_RESOLUTION / 15)
#define UNPHONE_LCD_SPI_TRANSFER_HEIGHT (UNPHONE_LCD_VERTICAL_RESOLUTION / 15)
class Hx8357Display : public tt::hal::display::DisplayDevice {
uint8_t* _Nullable buffer = nullptr;
lv_display_t* _Nullable lvglDisplay = nullptr;
std::shared_ptr<tt::hal::touch::TouchDevice> _Nullable touchDevice;
std::shared_ptr<tt::hal::display::DisplayDriver> _Nullable nativeDisplay;
class Hx8357Driver : public tt::hal::display::DisplayDriver {
std::shared_ptr<tt::Lock> lock = tt::hal::spi::getLock(SPI2_HOST);
public:
tt::hal::display::ColorFormat getColorFormat() const override { return tt::hal::display::ColorFormat::RGB888; }
uint16_t getPixelWidth() const override { return UNPHONE_LCD_HORIZONTAL_RESOLUTION; }
uint16_t getPixelHeight() const override { return UNPHONE_LCD_VERTICAL_RESOLUTION; }
bool drawBitmap(int xStart, int yStart, int xEnd, int yEnd, const void* pixelData) override;
std::shared_ptr<tt::Lock> getLock() const override { return lock; }
};
public:
std::string getName() const final { return "HX8357"; }
std::string getDescription() const final { return "SPI display"; }
bool start() override;
bool stop() override;
bool supportsLvgl() const override { return true; }
bool startLvgl() override;
bool stopLvgl() override;
std::shared_ptr<tt::hal::touch::TouchDevice> _Nullable getTouchDevice() override;
lv_display_t* _Nullable getLvglDisplay() const override { return lvglDisplay; }
// TODO: Set to true after fixing UnPhoneDisplayDriver
bool supportsDisplayDriver() const override { return false; }
std::shared_ptr<tt::hal::display::DisplayDriver> _Nullable getDisplayDriver() override {
if (nativeDisplay == nullptr) {
nativeDisplay = std::make_shared<Hx8357Driver>();
}
assert(nativeDisplay != nullptr);
return nativeDisplay;
}
};
std::shared_ptr<tt::hal::display::DisplayDevice> createDisplay();
+31
View File
@@ -0,0 +1,31 @@
#include "SdCard.h"
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/hal/sdcard/SpiSdCardDevice.h>
#define UNPHONE_SDCARD_PIN_CS GPIO_NUM_43
#define UNPHONE_LCD_PIN_CS GPIO_NUM_48
#define UNPHONE_LORA_PIN_CS GPIO_NUM_44
#define UNPHONE_TOUCH_PIN_CS GPIO_NUM_38
using tt::hal::sdcard::SpiSdCardDevice;
std::shared_ptr<SdCardDevice> createSdCard() {
auto configuration = std::make_unique<SpiSdCardDevice::Config>(
UNPHONE_SDCARD_PIN_CS,
GPIO_NUM_NC,
GPIO_NUM_NC,
GPIO_NUM_NC,
SdCardDevice::MountBehaviour::AtBoot,
tt::lvgl::getSyncLock(),
std::vector {
UNPHONE_LORA_PIN_CS,
UNPHONE_LCD_PIN_CS,
UNPHONE_TOUCH_PIN_CS
}
);
return std::make_shared<SpiSdCardDevice>(
std::move(configuration)
);
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include "Tactility/hal/sdcard/SdCardDevice.h"
using tt::hal::sdcard::SdCardDevice;
std::shared_ptr<SdCardDevice> createSdCard();
+14
View File
@@ -0,0 +1,14 @@
#include "Touch.h"
#include <Tactility/Log.h>
std::shared_ptr<Xpt2046Touch> createTouch() {
auto configuration = std::make_unique<Xpt2046Touch::Configuration>(
SPI2_HOST,
GPIO_NUM_38,
320,
480
);
return std::make_shared<Xpt2046Touch>(std::move(configuration));
}
+8
View File
@@ -0,0 +1,8 @@
#pragma once
#include <memory>
#include <Xpt2046Touch.h>
extern std::shared_ptr<Xpt2046Touch> touchInstance;
std::shared_ptr<Xpt2046Touch> createTouch();
+4
View File
@@ -0,0 +1,4 @@
The files in this folder are from https://github.com/lvgl/lvgl_esp32_drivers
The original license is an MIT license: https://github.com/lvgl/lvgl_esp32_drivers/blob/master/LICENSE
You may use the files in this folder under the original license, or under GPL v3 from the main Tactility project.
+315
View File
@@ -0,0 +1,315 @@
#define LV_USE_PRIVATE_API 1 // For actual lv_obj_t declaration
/**
* @file disp_spi.c
*
*/
/*********************
* INCLUDES
*********************/
#include "esp_system.h"
#include "driver/gpio.h"
#include "driver/spi_master.h"
#include "esp_log.h"
#define TAG "disp_spi"
#include <string.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#ifdef LV_LVGL_H_INCLUDE_SIMPLE
#include "lvgl.h"
#else
#include "lvgl/lvgl.h"
#endif
#include "disp_spi.h"
//#include "disp_driver.h"
//#include "../lvgl_helpers.h"
#include "../lvgl_spi_conf.h"
/******************************************************************************
* Notes about DMA spi_transaction_ext_t structure pooling
*
* An xQueue is used to hold a pool of reusable SPI spi_transaction_ext_t
* structures that get used for all DMA SPI transactions. While an xQueue may
* seem like overkill it is an already built-in RTOS feature that comes at
* little cost. xQueues are also ISR safe if it ever becomes necessary to
* access the pool in the ISR callback.
*
* When a DMA request is sent, a transaction structure is removed from the
* pool, filled out, and passed off to the esp32 SPI driver. Later, when
* servicing pending SPI transaction results, the transaction structure is
* recycled back into the pool for later reuse. This matches the DMA SPI
* transaction life cycle requirements of the esp32 SPI driver.
*
* When polling or synchronously sending SPI requests, and as required by the
* esp32 SPI driver, all pending DMA transactions are first serviced. Then the
* polling SPI request takes place.
*
* When sending an asynchronous DMA SPI request, if the pool is empty, some
* small percentage of pending transactions are first serviced before sending
* any new DMA SPI transactions. Not too many and not too few as this balance
* controls DMA transaction latency.
*
* It is therefore not the design that all pending transactions must be
* serviced and placed back into the pool with DMA SPI requests - that
* will happen eventually. The pool just needs to contain enough to float some
* number of in-flight SPI requests to speed up the overall DMA SPI data rate
* and reduce transaction latency. If however a display driver uses some
* polling SPI requests or calls disp_wait_for_pending_transactions() directly,
* the pool will reach the full state more often and speed up DMA queuing.
*
*****************************************************************************/
/*********************
* DEFINES
*********************/
#define SPI_TRANSACTION_POOL_SIZE 50 /* maximum number of DMA transactions simultaneously in-flight */
/* DMA Transactions to reserve before queueing additional DMA transactions. A 1/10th seems to be a good balance. Too many (or all) and it will increase latency. */
#define SPI_TRANSACTION_POOL_RESERVE_PERCENTAGE 10
#if SPI_TRANSACTION_POOL_SIZE >= SPI_TRANSACTION_POOL_RESERVE_PERCENTAGE
#define SPI_TRANSACTION_POOL_RESERVE (SPI_TRANSACTION_POOL_SIZE / SPI_TRANSACTION_POOL_RESERVE_PERCENTAGE)
#else
#define SPI_TRANSACTION_POOL_RESERVE 1 /* defines minimum size */
#endif
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void spi_ready(spi_transaction_t*trans);
/**********************
* STATIC VARIABLES
**********************/
static spi_host_device_t spi_host;
static spi_device_handle_t spi;
static QueueHandle_t TransactionPool = NULL;
static transaction_cb_t chained_post_cb;
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void disp_spi_add_device_config(spi_host_device_t host, spi_device_interface_config_t *devcfg)
{
spi_host=host;
chained_post_cb=devcfg->post_cb;
devcfg->post_cb=spi_ready;
esp_err_t ret=spi_bus_add_device(host, devcfg, &spi);
assert(ret==ESP_OK);
}
void disp_spi_add_device(spi_host_device_t host)
{
disp_spi_add_device_with_speed(host, SPI_TFT_CLOCK_SPEED_HZ);
}
void disp_spi_add_device_with_speed(spi_host_device_t host, int clock_speed_hz)
{
ESP_LOGI(TAG, "Adding SPI device");
ESP_LOGI(TAG, "Clock speed: %dHz, mode: %d, CS pin: %d",
clock_speed_hz, SPI_TFT_SPI_MODE, DISP_SPI_CS);
spi_device_interface_config_t devcfg={
.clock_speed_hz = clock_speed_hz,
.mode = SPI_TFT_SPI_MODE,
.spics_io_num=DISP_SPI_CS, // CS pin
.input_delay_ns=DISP_SPI_INPUT_DELAY_NS,
.queue_size=SPI_TRANSACTION_POOL_SIZE,
.pre_cb=NULL,
.post_cb=NULL,
#if defined(DISP_SPI_HALF_DUPLEX)
.flags = SPI_DEVICE_NO_DUMMY | SPI_DEVICE_HALFDUPLEX, /* dummy bits should be explicitly handled via DISP_SPI_VARIABLE_DUMMY as needed */
#else
#if defined (CONFIG_LV_TFT_DISPLAY_CONTROLLER_FT81X)
.flags = 0,
#elif defined (CONFIG_LV_TFT_DISPLAY_CONTROLLER_RA8875)
.flags = SPI_DEVICE_NO_DUMMY,
#endif
#endif
};
disp_spi_add_device_config(host, &devcfg);
/* create the transaction pool and fill it with ptrs to spi_transaction_ext_t to reuse */
if(TransactionPool == NULL) {
TransactionPool = xQueueCreate(SPI_TRANSACTION_POOL_SIZE, sizeof(spi_transaction_ext_t*));
assert(TransactionPool != NULL);
for (size_t i = 0; i < SPI_TRANSACTION_POOL_SIZE; i++)
{
spi_transaction_ext_t* pTransaction = (spi_transaction_ext_t*)heap_caps_malloc(sizeof(spi_transaction_ext_t), MALLOC_CAP_DMA);
assert(pTransaction != NULL);
memset(pTransaction, 0, sizeof(spi_transaction_ext_t));
xQueueSend(TransactionPool, &pTransaction, portMAX_DELAY);
}
}
}
void disp_spi_change_device_speed(int clock_speed_hz)
{
if (clock_speed_hz <= 0) {
clock_speed_hz = SPI_TFT_CLOCK_SPEED_HZ;
}
ESP_LOGI(TAG, "Changing SPI device clock speed: %d", clock_speed_hz);
disp_spi_remove_device();
disp_spi_add_device_with_speed(spi_host, clock_speed_hz);
}
void disp_spi_remove_device()
{
/* Wait for previous pending transaction results */
disp_wait_for_pending_transactions();
esp_err_t ret=spi_bus_remove_device(spi);
assert(ret==ESP_OK);
}
void disp_spi_transaction(const uint8_t *data, size_t length,
int flags, uint8_t *out,
uint64_t addr, uint8_t dummy_bits)
{
if (0 == length) {
return;
}
spi_transaction_ext_t t = {0};
/* transaction length is in bits */
t.base.length = length * 8;
if (length <= 4 && data != NULL) {
t.base.flags = SPI_TRANS_USE_TXDATA;
memcpy(t.base.tx_data, data, length);
} else {
t.base.tx_buffer = data;
}
if (flags & DISP_SPI_RECEIVE) {
assert(out != NULL && (flags & (DISP_SPI_SEND_POLLING | DISP_SPI_SEND_SYNCHRONOUS)));
t.base.rx_buffer = out;
#if defined(DISP_SPI_HALF_DUPLEX)
t.base.rxlength = t.base.length;
t.base.length = 0; /* no MOSI phase in half-duplex reads */
#else
t.base.rxlength = 0; /* in full-duplex mode, zero means same as tx length */
#endif
}
if (flags & DISP_SPI_ADDRESS_8) {
t.address_bits = 8;
} else if (flags & DISP_SPI_ADDRESS_16) {
t.address_bits = 16;
} else if (flags & DISP_SPI_ADDRESS_24) {
t.address_bits = 24;
} else if (flags & DISP_SPI_ADDRESS_32) {
t.address_bits = 32;
}
if (t.address_bits) {
t.base.addr = addr;
t.base.flags |= SPI_TRANS_VARIABLE_ADDR;
}
#if defined(DISP_SPI_HALF_DUPLEX)
if (flags & DISP_SPI_MODE_DIO) {
t.base.flags |= SPI_TRANS_MODE_DIO;
} else if (flags & DISP_SPI_MODE_QIO) {
t.base.flags |= SPI_TRANS_MODE_QIO;
}
if (flags & DISP_SPI_MODE_DIOQIO_ADDR) {
t.base.flags |= SPI_TRANS_MODE_DIOQIO_ADDR;
}
if ((flags & DISP_SPI_VARIABLE_DUMMY) && dummy_bits) {
t.dummy_bits = dummy_bits;
t.base.flags |= SPI_TRANS_VARIABLE_DUMMY;
}
#endif
/* Save flags for pre/post transaction processing */
t.base.user = (void *) flags;
/* Poll/Complete/Queue transaction */
if (flags & DISP_SPI_SEND_POLLING) {
disp_wait_for_pending_transactions(); /* before polling, all previous pending transactions need to be serviced */
spi_device_polling_transmit(spi, (spi_transaction_t *) &t);
} else if (flags & DISP_SPI_SEND_SYNCHRONOUS) {
disp_wait_for_pending_transactions(); /* before synchronous queueing, all previous pending transactions need to be serviced */
spi_device_transmit(spi, (spi_transaction_t *) &t);
} else {
/* if necessary, ensure we can queue new transactions by servicing some previous transactions */
if(uxQueueMessagesWaiting(TransactionPool) == 0) {
spi_transaction_t *presult;
while(uxQueueMessagesWaiting(TransactionPool) < SPI_TRANSACTION_POOL_RESERVE) {
if (spi_device_get_trans_result(spi, &presult, 1) == ESP_OK) {
xQueueSend(TransactionPool, &presult, portMAX_DELAY); /* back to the pool to be reused */
}
}
}
spi_transaction_ext_t *pTransaction = NULL;
xQueueReceive(TransactionPool, &pTransaction, portMAX_DELAY);
memcpy(pTransaction, &t, sizeof(t));
if (spi_device_queue_trans(spi, (spi_transaction_t *) pTransaction, portMAX_DELAY) != ESP_OK) {
xQueueSend(TransactionPool, &pTransaction, portMAX_DELAY); /* send failed transaction back to the pool to be reused */
}
}
}
void disp_wait_for_pending_transactions(void)
{
spi_transaction_t *presult;
while(uxQueueMessagesWaiting(TransactionPool) < SPI_TRANSACTION_POOL_SIZE) { /* service until the transaction reuse pool is full again */
if (spi_device_get_trans_result(spi, &presult, 1) == ESP_OK) {
xQueueSend(TransactionPool, &presult, portMAX_DELAY);
}
}
}
void disp_spi_acquire(void)
{
esp_err_t ret = spi_device_acquire_bus(spi, portMAX_DELAY);
assert(ret == ESP_OK);
}
void disp_spi_release(void)
{
spi_device_release_bus(spi);
}
/**********************
* STATIC FUNCTIONS
**********************/
static void IRAM_ATTR spi_ready(spi_transaction_t *trans)
{
disp_spi_send_flag_t flags = (disp_spi_send_flag_t) trans->user;
if (flags & DISP_SPI_SIGNAL_FLUSH) {
lv_disp_t* disp = lv_refr_get_disp_refreshing();
lv_disp_flush_ready(disp);
}
if (chained_post_cb) {
chained_post_cb(trans);
}
}
+81
View File
@@ -0,0 +1,81 @@
/**
* @file disp_spi.h
*
*/
#ifndef DISP_SPI_H
#define DISP_SPI_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include <stdint.h>
#include <stdbool.h>
#include <driver/spi_master.h>
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
typedef enum _disp_spi_send_flag_t {
DISP_SPI_SEND_QUEUED = 0x00000000,
DISP_SPI_SEND_POLLING = 0x00000001,
DISP_SPI_SEND_SYNCHRONOUS = 0x00000002,
DISP_SPI_SIGNAL_FLUSH = 0x00000004,
DISP_SPI_RECEIVE = 0x00000008,
DISP_SPI_CMD_8 = 0x00000010, /* Reserved */
DISP_SPI_CMD_16 = 0x00000020, /* Reserved */
DISP_SPI_ADDRESS_8 = 0x00000040,
DISP_SPI_ADDRESS_16 = 0x00000080,
DISP_SPI_ADDRESS_24 = 0x00000100,
DISP_SPI_ADDRESS_32 = 0x00000200,
DISP_SPI_MODE_DIO = 0x00000400,
DISP_SPI_MODE_QIO = 0x00000800,
DISP_SPI_MODE_DIOQIO_ADDR = 0x00001000,
DISP_SPI_VARIABLE_DUMMY = 0x00002000,
} disp_spi_send_flag_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
void disp_spi_add_device(spi_host_device_t host);
void disp_spi_add_device_config(spi_host_device_t host, spi_device_interface_config_t *devcfg);
void disp_spi_add_device_with_speed(spi_host_device_t host, int clock_speed_hz);
void disp_spi_change_device_speed(int clock_speed_hz);
void disp_spi_remove_device();
/* Important!
All buffers should also be 32-bit aligned and DMA capable to prevent extra allocations and copying.
When DMA reading (even in polling mode) the ESP32 always read in 4-byte chunks even if less is requested.
Extra space will be zero filled. Always ensure the out buffer is large enough to hold at least 4 bytes!
*/
void disp_spi_transaction(const uint8_t *data, size_t length,
int flags, uint8_t *out, uint64_t addr, uint8_t dummy_bits);
void disp_wait_for_pending_transactions(void);
void disp_spi_acquire(void);
void disp_spi_release(void);
static inline void disp_spi_send_data(uint8_t *data, size_t length) {
disp_spi_transaction(data, length, DISP_SPI_SEND_POLLING, NULL, 0, 0);
}
static inline void disp_spi_send_colors(uint8_t *data, size_t length) {
disp_spi_transaction(data, length,
DISP_SPI_SEND_QUEUED | DISP_SPI_SIGNAL_FLUSH,
NULL, 0, 0);
}
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /*DISP_SPI_H*/
+292
View File
@@ -0,0 +1,292 @@
/**
* @file HX8357.c
*
* Roughly based on the Adafruit_HX8357_Library
*
* This library should work with:
* Adafruit 3.5" TFT 320x480 + Touchscreen Breakout
* http://www.adafruit.com/products/2050
*
* Adafruit TFT FeatherWing - 3.5" 480x320 Touchscreen for Feathers
* https://www.adafruit.com/product/3651
*
*/
/*********************
* INCLUDES
*********************/
#include "hx8357.h"
#include "disp_spi.h"
#include "driver/gpio.h"
#include <esp_log.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
/*********************
* DEFINES
*********************/
#define TAG "HX8357"
/**********************
* TYPEDEFS
**********************/
static gpio_num_t dcPin = GPIO_NUM_NC;
/*The LCD needs a bunch of command/argument values to be initialized. They are stored in this struct. */
typedef struct {
uint8_t cmd;
uint8_t data[16];
uint8_t databytes; //No of data in data; bit 7 = delay after set; 0xFF = end of cmds.
} lcd_init_cmd_t;
/**********************
* STATIC PROTOTYPES
**********************/
static void hx8357_send_cmd(uint8_t cmd);
static void hx8357_send_data(void * data, uint16_t length);
static void hx8357_send_color(void * data, uint16_t length);
/**********************
* INITIALIZATION ARRAYS
**********************/
// Taken from the Adafruit driver
static const uint8_t
initb[] = {
HX8357B_SETPOWER, 3,
0x44, 0x41, 0x06,
HX8357B_SETVCOM, 2,
0x40, 0x10,
HX8357B_SETPWRNORMAL, 2,
0x05, 0x12,
HX8357B_SET_PANEL_DRIVING, 5,
0x14, 0x3b, 0x00, 0x02, 0x11,
HX8357B_SETDISPLAYFRAME, 1,
0x0c, // 6.8mhz
HX8357B_SETPANELRELATED, 1,
0x01, // BGR
0xEA, 3, // seq_undefined1, 3 args
0x03, 0x00, 0x00,
0xEB, 4, // undef2, 4 args
0x40, 0x54, 0x26, 0xdb,
HX8357B_SETGAMMA, 12,
0x00, 0x15, 0x00, 0x22, 0x00, 0x08, 0x77, 0x26, 0x66, 0x22, 0x04, 0x00,
HX8357_MADCTL, 1,
0xC0,
HX8357_COLMOD, 1,
0x55,
HX8357_PASET, 4,
0x00, 0x00, 0x01, 0xDF,
HX8357_CASET, 4,
0x00, 0x00, 0x01, 0x3F,
HX8357B_SETDISPMODE, 1,
0x00, // CPU (DBI) and internal oscillation ??
HX8357_SLPOUT, 0x80 + 120/5, // Exit sleep, then delay 120 ms
HX8357_DISPON, 0x80 + 10/5, // Main screen turn on, delay 10 ms
0 // END OF COMMAND LIST
}, initd[] = {
HX8357_SWRESET, 0x80 + 100/5, // Soft reset, then delay 10 ms
HX8357D_SETC, 3,
0xFF, 0x83, 0x57,
0xFF, 0x80 + 500/5, // No command, just delay 300 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, // 0x55 = 16 bit, 0x57 = 24bit
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
};
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
static uint8_t displayType = HX8357D;
void hx8357_reset(gpio_num_t resetPin) {
if (resetPin != GPIO_NUM_NC) {
esp_rom_gpio_pad_select_gpio(resetPin);
gpio_set_direction(resetPin, GPIO_MODE_OUTPUT);
//Reset the display
gpio_set_level(resetPin, 0);
vTaskDelay(10 / portTICK_PERIOD_MS);
gpio_set_level(resetPin, 1);
vTaskDelay(120 / portTICK_PERIOD_MS);
}
}
void hx8357_init(gpio_num_t newDcPin) {
ESP_LOGI(TAG, "Initialization.");
dcPin = newDcPin;
//Initialize non-SPI GPIOs
esp_rom_gpio_pad_select_gpio(dcPin);
gpio_set_direction(dcPin, GPIO_MODE_OUTPUT);
//Send all the commands
const uint8_t *addr = (displayType == HX8357B) ? initb : initd;
uint8_t cmd, x, numArgs;
while((cmd = *addr++) > 0) { // '0' command ends list
x = *addr++;
numArgs = x & 0x7F;
if (cmd != 0xFF) { // '255' is ignored
if (x & 0x80) { // If high bit set, numArgs is a delay time
hx8357_send_cmd(cmd);
} else {
hx8357_send_cmd(cmd);
hx8357_send_data((void *) addr, numArgs);
addr += numArgs;
}
}
if (x & 0x80) { // If high bit set...
vTaskDelay(numArgs * 5 / portTICK_PERIOD_MS); // numArgs is actually a delay time (5ms units)
}
}
#if HX8357_INVERT_COLORS
hx8357_send_cmd(HX8357_INVON);
#else
hx8357_send_cmd(HX8357_INVOFF);
#endif
}
//(lv_display_t * disp, const lv_area_t * area, uint8_t * px_map);
void hx8357_flush(lv_disp_t* drv, const lv_area_t * area, uint8_t * color_map)
{
uint32_t size = lv_area_get_width(area) * lv_area_get_height(area);
/* Column addresses */
uint8_t xb[] = {
(uint8_t) (area->x1 >> 8) & 0xFF,
(uint8_t) (area->x1) & 0xFF,
(uint8_t) (area->x2 >> 8) & 0xFF,
(uint8_t) (area->x2) & 0xFF,
};
/* Page addresses */
uint8_t yb[] = {
(uint8_t) (area->y1 >> 8) & 0xFF,
(uint8_t) (area->y1) & 0xFF,
(uint8_t) (area->y2 >> 8) & 0xFF,
(uint8_t) (area->y2) & 0xFF,
};
/*Column addresses*/
hx8357_send_cmd(HX8357_CASET);
hx8357_send_data(xb, 4);
/*Page addresses*/
hx8357_send_cmd(HX8357_PASET);
hx8357_send_data(yb, 4);
/*Memory write*/
hx8357_send_cmd(HX8357_RAMWR);
hx8357_send_color((void*)color_map, size * (LV_COLOR_DEPTH / 8));
}
void hx8357_set_madctl(uint8_t value) {
hx8357_send_cmd(HX8357_MADCTL);
hx8357_send_data(&value, 1);
}
/**********************
* STATIC FUNCTIONS
**********************/
static void hx8357_send_cmd(uint8_t cmd)
{
disp_wait_for_pending_transactions();
gpio_set_level(dcPin, 0); /*Command mode*/
disp_spi_send_data(&cmd, 1);
}
static void hx8357_send_data(void * data, uint16_t length)
{
disp_wait_for_pending_transactions();
gpio_set_level(dcPin, 1); /*Data mode*/
disp_spi_send_data(data, length);
}
static void hx8357_send_color(void * data, uint16_t length)
{
disp_wait_for_pending_transactions();
gpio_set_level(dcPin, 1); /*Data mode*/
disp_spi_send_colors(data, length);
}
uint8_t hx8357d_get_gamma_curve_count() {
return 4;
}
void hx8357d_set_gamme_curve(uint8_t index) {
uint8_t curve = 1;
switch (index) {
case 0:
curve = 0x01;
break;
case 1:
curve = 0x02;
break;
case 2:
curve = 0x04;
break;
case 3:
curve = 0x08;
break;
}
hx8357_send_cmd(HX8357D_SETGAMMA_BY_ID);
hx8357_send_data(&curve, 1);
}
+133
View File
@@ -0,0 +1,133 @@
/**
* @file hx8357.h
*
* Roughly based on the Adafruit_HX8357_Library
*
* This library should work with:
* Adafruit 3.5" TFT 320x480 + Touchscreen Breakout
* http://www.adafruit.com/products/2050
*
* Adafruit TFT FeatherWing - 3.5" 480x320 Touchscreen for Feathers
* https://www.adafruit.com/product/3651
*
* Datasheet:
* https://cdn-shop.adafruit.com/datasheets/HX8357-D_DS_April2012.pdf
*/
#ifndef HX8357_H
#define HX8357_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include <stdbool.h>
#include <stdint.h>
#include <lvgl.h>
#include <soc/gpio_num.h>
#define HX8357D 0xD ///< Our internal const for D type
#define HX8357B 0xB ///< Our internal const for B type
#define HX8357_TFTWIDTH 320 ///< 320 pixels wide
#define HX8357_TFTHEIGHT 480 ///< 480 pixels tall
#define HX8357_NOP 0x00 ///< No op
#define HX8357_SWRESET 0x01 ///< software reset
#define HX8357_RDDID 0x04 ///< Read ID
#define HX8357_RDDST 0x09 ///< (unknown)
#define HX8357_RDPOWMODE 0x0A ///< Read power mode Read power mode
#define HX8357_RDMADCTL 0x0B ///< Read MADCTL
#define HX8357_RDCOLMOD 0x0C ///< Column entry mode
#define HX8357_RDDIM 0x0D ///< Read display image mode
#define HX8357_RDDSDR 0x0F ///< Read dosplay signal mode
#define HX8357_SLPIN 0x10 ///< Enter sleep mode
#define HX8357_SLPOUT 0x11 ///< Exit sleep mode
#define HX8357B_PTLON 0x12 ///< Partial mode on
#define HX8357B_NORON 0x13 ///< Normal mode
#define HX8357_INVOFF 0x20 ///< Turn off invert
#define HX8357_INVON 0x21 ///< Turn on invert
#define HX8357_DISPOFF 0x28 ///< Display on
#define HX8357_DISPON 0x29 ///< Display off
#define HX8357_CASET 0x2A ///< Column addr set
#define HX8357_PASET 0x2B ///< Page addr set
#define HX8357_RAMWR 0x2C ///< Write VRAM
#define HX8357_RAMRD 0x2E ///< Read VRAm
#define HX8357B_PTLAR 0x30 ///< (unknown)
#define HX8357_TEON 0x35 ///< Tear enable on
#define HX8357_TEARLINE 0x44 ///< (unknown)
#define HX8357_MADCTL 0x36 ///< Memory access control
#define HX8357_COLMOD 0x3A ///< Color mode
#define HX8357_SETOSC 0xB0 ///< Set oscillator
#define HX8357_SETPWR1 0xB1 ///< Set power control
#define HX8357B_SETDISPLAY 0xB2 ///< Set display mode
#define HX8357_SETRGB 0xB3 ///< Set RGB interface
#define HX8357D_SETCOM 0xB6 ///< Set VCOM voltage
#define HX8357B_SETDISPMODE 0xB4 ///< Set display mode
#define HX8357D_SETCYC 0xB4 ///< Set display cycle reg
#define HX8357B_SETOTP 0xB7 ///< Set OTP memory
#define HX8357D_SETC 0xB9 ///< Enable extension command
#define HX8357B_SET_PANEL_DRIVING 0xC0 ///< Set panel drive mode
#define HX8357D_SETSTBA 0xC0 ///< Set source option
#define HX8357B_SETDGC 0xC1 ///< Set DGC settings
#define HX8357B_SETID 0xC3 ///< Set ID
#define HX8357B_SETDDB 0xC4 ///< Set DDB
#define HX8357B_SETDISPLAYFRAME 0xC5 ///< Set display frame
#define HX8357B_GAMMASET 0xC8 ///< Set Gamma correction
#define HX8357B_SETCABC 0xC9 ///< Set CABC
#define HX8357_SETPANEL 0xCC ///< Set Panel
#define HX8357B_SETPOWER 0xD0 ///< Set power control
#define HX8357B_SETVCOM 0xD1 ///< Set VCOM
#define HX8357B_SETPWRNORMAL 0xD2 ///< Set power normal
#define HX8357B_RDID1 0xDA ///< Read ID #1
#define HX8357B_RDID2 0xDB ///< Read ID #2
#define HX8357B_RDID3 0xDC ///< Read ID #3
#define HX8357B_RDID4 0xDD ///< Read ID #4
#define HX8357D_SETGAMMA 0xE0 ///< Set Gamma curve data
#define HX8357D_SETGAMMA_BY_ID 0x26 ///< Set Gamma curve by curve identifier (0x01, 0x02, 0x04, 0x08)
#define HX8357B_SETGAMMA 0xC8 ///< Set Gamma
#define HX8357B_SETPANELRELATED 0xE9 ///< Set panel related
// MADCTL
// See datasheet page 123: https://cdn-shop.adafruit.com/datasheets/HX8357-D_DS_April2012.pdf
#define MADCTL_BIT_INDEX_COMMON_OUTPUTS_RAM 0 // N/A - set to 0
#define MADCTL_BIT_INDEX_SEGMENT_OUTPUTS_RAM 1 // N/A - set to 0
#define MADCTL_BIT_INDEX_DATA_LATCH_ORDER 2 // 0 = left-to-right refresh, 1 = right-to-left
#define MADCTL_BIT_INDEX_RGB_BGR_ORDER 3 // 0 = RGB, 1 = BGR
#define MADCTL_BIT_INDEX_LINE_ADDRESS_ORDER 4 // 0 = top-to-bottom refresh, 1 = bottom-to-top
#define MADCTL_BIT_INDEX_PAGE_COLUMN_ORDER 5 // 0 = normal, 1 = reverse
#define MADCTL_BIT_INDEX_COLUMN_ADDRESS_ORDER 6 // 0 = left-to-right, 1 = right-to-left
#define MADCTL_BIT_INDEX_PAGE_ADDRESS_ORDER 7 // 0 = top-to-bottom, 1 = bottom-to-top
void hx8357_reset(gpio_num_t resetPin);
void hx8357_init(gpio_num_t dcPin);
void hx8357_set_madctl(uint8_t value);
void hx8357_flush(lv_disp_t* drv, const lv_area_t* area, uint8_t* color_map);
uint8_t hx8357d_get_gamma_curve_count();
/**
* Note: this doesn't work, even though the manual says it should
* Page 141: https://cdn-shop.adafruit.com/datasheets/HX8357-D_DS_April2012.pdf
*/
void hx8357d_set_gamme_curve(uint8_t index);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /*HX8357_H*/
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#define SPI_TFT_CLOCK_SPEED_HZ (26*1000*1000)
#define SPI_TFT_SPI_MODE (0)
#define DISP_SPI_CS GPIO_NUM_48
#define DISP_SPI_INPUT_DELAY_NS 0
+21
View File
@@ -0,0 +1,21 @@
[general]
vendor=unPhone
name=unPhone
[hardware]
target=ESP32S3
flashSize=8MB
spiRam=true
spiRamMode=OCT
spiRamSpeed=80M
[display]
size=3.5"
shape=rectangle
dpi=165
[cdn]
warningMessage=Put the device into bootloader mode by pressing the center nav button and reset for 2-3 seconds, then release reset, then release the nav button.<br/>After flashing is finished, press the reset button to reboot.
[lvgl]
colorDepth=24