↩ Alle projecten en sketches This page in English
ESP32 · TFT_eSPI · touchscreen

ESP32-3248S035: geïntegreerd display (480 × 320px)

ESP32-3248S035 met geïntegreerd 3.5 inch aanraakscherm
ESP32-3248S035 op AliExpress — 3.5 inch capacitief aanraakscherm, 480×320px

Een handige combinatie van een ESP32 en een relatief groot aanraakscherm — hier gebruikt om live dynamische elektriciteitsprijzen weer te geven.

Wat heb je nodig?

ESP32-3248S035: geïntegreerd display (480 × 320px)

Dit is een handige combinatie van een ESP32 en een relatief groot aanraakscherm. Je vindt weinig voorbeelden van deze combinatie voor de Arduino IDE.

Het touch-gedeelte gebruiken we in dit voorbeeld niet (maar dat werkt wel perfect), je kan dat gewoon laden (en testen) uit de voorbeelden van de bibliotheek "TFT_eSPI".

In deze schets halen we via de API van epexprijzen.be de dynamische all-in elektriciteitsprijzen op (Vlaanderen, Dots Energy), om ze in ct/kWh op het display weer te geven. We kunnen met de flashknop de weergave wijzigen in numerieke gegevens of grafiek.

Uiteraard is er geen verbindingsschema om weer te geven, maar het is wel een hele zoektocht als je dit systeem wil configureren voor de Arduino IDE. We gebruiken weer de bibliotheek TFT-eSPI (Bodmer). Je moet een bestand "User_Setup.h" in de map van de bibliotheek "TFT_eSPI" plaatsen.

Inhoud van het bestand "User_Setup.h" voor de ESP32-3248S035:

#define ST7796_DRIVER
#define TFT_WIDTH  320
#define TFT_HEIGHT 480 // 
#define TFT_BL   27            // LED back-light control pin
#define TFT_BACKLIGHT_ON HIGH  // Level to turn ON back-light (HIGH or LOW)

#define TFT_MISO 12
#define TFT_MOSI 13  // In some display driver board, it might be written as "SDA" and so on.
#define TFT_SCLK 14
#define TFT_CS   15  // Chip select control pin
#define TFT_DC   2   // Data Command control pin
#define TFT_RST  -1  // Reset pin (could connect to Arduino RESET pin)

#define TOUCH_CS 33     // Chip select pin (T_CS) of touch screen

#define LOAD_GLCD   // Font 1. Original Adafruit 8 pixel font needs ~1820 bytes in FLASH
#define LOAD_FONT2  // Font 2. Small 16 pixel high font, needs ~3534 bytes in FLASH, 96 characters
#define LOAD_FONT4  // Font 4. Medium 26 pixel high font, needs ~5848 bytes in FLASH, 96 characters
#define LOAD_FONT6  // Font 6. Large 48 pixel font, needs ~2666 bytes in FLASH, only characters 1234567890:-.apm
#define LOAD_FONT7  // Font 7. 7 segment 48 pixel font, needs ~2438 bytes in FLASH, only characters 1234567890:-.
#define LOAD_FONT8  // Font 8. Large 75 pixel font needs ~3256 bytes in FLASH, only characters 1234567890:-.
// #define LOAD_FONT8N // Font 8. Alternative to Font 8 above, slightly narrower, so 3 digits fit a 160 pixel TFT
#define LOAD_GFXFF  // FreeFonts. Include access to the 48 Adafruit_GFX free fonts FF1 to FF48 and custom fonts

// Comment out the #define below to stop the SPIFFS filing system and smooth font code being loaded
// this will save ~20kbytes of FLASH
#define SMOOTH_FONT

#define SPI_FREQUENCY  65000000
#define SPI_READ_FREQUENCY  20000000
#define SPI_TOUCH_FREQUENCY  2500000  //2500000
TFT_eSPI — opgelet Om hier een gemakkelijk overzicht weer te geven passen we de inhoud van het bestand "User_Setup.h" aan. Dat is een snelle oplossing als je 1 scherm aan de praat wil krijgen en vlug resultaat wil zien.

Als je meerdere displays gebruikt en/of geen gegevens wil verliezen als je een nieuwe kopij van deze bibliotheek installeert, kan je beter de tip volgen van de ontwerper van de bibliotheek: github.com/Bodmer/TFT_eSPI/#tips.

Je kan de volledige inhoud van "User_Setup.h" uitcommenten als je zo werkt.

Live elektriciteitsprijzen op het scherm

De sketch verbindt via WiFiManager en haalt de dynamische all-in elektriciteitsprijzen (inclusief energiebelasting en leverancierstoeslag) van vandaag en morgen op via de API van epexprijzen.be. Die worden in ct/kWh getoond als grafiek of als cijfers in twee kolommen — te wisselen met de flash-knop. De grafiek schaalt automatisch mee: ze toont minstens 0 tot 50 ct/kWh, maar rekt uit bij hogere prijzen, en bij negatieve prijzen schuift de nullijn omhoog zodat die balken naar beneden lopen. Zodra er minder dan 12 uur aan toekomstige prijzen over is, probeert het script elk uur de prijzen van morgen op te halen (die komen meestal rond 13:00 beschikbaar). Mislukt een oproep, dan blijven de oude prijzen staan en volgt na 10 minuten een nieuwe poging; het label "VL" rechtsboven wordt dan rood.

Andere leverancier of regio? Pas de constante API_URL aan: vervang dots-energy door je eigen leverancier (bv. bolt, ebem, ecopower, eneco, engie, frank-energie, luminus, mega, octaplus, totalenergies) en vlaanderen eventueel door wallonie of brussel. De kleurgrenzen stel je in met VALUE_GREEN en VALUE_RED (ct/kWh).
/*==========================================================================================
This sketch was written for the ESP32-3248S035 with integrated display (480 * 320 pixels).
If a WiFi connection cannot be made, a web server is started to store the WiFi credentials.
Dynamic electricity prices (Flanders, Dots Energy, all-in) are retrieved via the API of
epexprijzen.be and displayed on the screen in ct/kWh.
The flash button switches the display between figures in two columns or graph.
The chart scales automatically (at least 0 - 50 ct/kWh, also for negative prices).
The API returns the prices of today and (from roughly 13:00 CET) tomorrow.
As soon as less than 12 hours of future prices are left, the script tries every hour
(at minute 2) to retrieve tomorrow's prices, until it succeeds. If a request fails,
the old data is kept on screen and a new attempt is made every 10 minutes.
=============================================================================================
Arduino IDE - board: ESP32 Dev Module or DOIT ESP32 DEVKIT V1
https://nl.aliexpress.com/item/1005006398547061.html
https://nl.aliexpress.com/item/1005005900820162.html
==========================================================================================*/

#include <WiFiManager.h>       // https://github.com/tzapu/WiFiManager/
#include <TFT_eSPI.h>          // https://github.com/Bodmer/TFT_eSPI
#include <ArduinoJson.h>       // https://github.com/bblanchon/ArduinoJson (version 7)
#include <HTTPClient.h>        // for API connection
#include <WiFiClientSecure.h>  // https

TFT_eSPI tft = TFT_eSPI();  // User_Setup.h settings available on: https://espgo.be/esp32-3248s035-en.html
WiFiManager myWiFi;

#define SHOW_ITEMS 34  // number of bars / records on the display
#define MAX_ITEMS 60   // today + tomorrow = 48 (50 on a DST day) + margin
#define this_Ssid "S035_ESP"

const char* API_URL = "https://epexprijzen.be/api/v1/prices/dots-energy/hourly?region=vlaanderen";
const char* REGION_LABEL = "VL";

constexpr float VALUE_GREEN = 20.0;    // price (ct/kWh) below this value: green
constexpr float VALUE_RED = 30.0;      // price (ct/kWh) from this value: red (in between: cyan)
constexpr uint8_t FLASH_BUTTON = 0;
constexpr int PLOT_TOP = 30;           // top of the chart area (y)
constexpr int PLOT_BOTTOM = 304;       // bottom of the chart area (y), hour labels below
constexpr float SCALE_MIN_TOP = 50.0;  // the chart always shows at least 0 .. 50 ct/kWh
constexpr unsigned long RETRY_MS = 10UL * 60 * 1000;  // retry interval after a failed request

struct tm tInfo;  // https://cplusplus.com/reference/ctime/tm/
bool chart = true, freshStart = true, lastFetchOk = false;
unsigned long lastAction, lastFetchMillis;
int lastSec = -1, lastFetchHour = -1, lastDrawHour = -1;
float prijzen[SHOW_ITEMS];  // prices shown on the display (ct/kWh)
time_t epo[SHOW_ITEMS];     // epoch times shown on the display
float prices[MAX_ITEMS];    // all prices returned by the API (ct/kWh)
time_t epoc[MAX_ITEMS];     // all epoch times returned by the API (UTC)
uint8_t apiItems = 0;       // number of valid records returned by the API
float priceNow = NAN;       // price of current hour

void setup() {
  const char* time_Zone = "CET-1CEST,M3.5.0,M10.5.0/3";  // https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv
  Serial.begin(115200);
  pinMode(FLASH_BUTTON, INPUT_PULLUP);
  for (const uint8_t& pin : { 4, 16, 17 }) pinMode(pin, OUTPUT), digitalWrite(pin, HIGH);  // red, green & blue LEDs off
  tft_Setup();
  myWiFi.setAPCallback(messageNoConnection);
  myWiFi.autoConnect(this_Ssid);
  configTzTime(time_Zone, "be.pool.ntp.org");
  showStartupData();
}

void loop() {
  display_Time();
  if (!digitalRead(FLASH_BUTTON)) changeView();  // flash button changes between chart or list of figures
  // if (priceNow < 0) start_Energy-Guzzling_device();  // priceNow = current electricity price (ct/kWh)
  // else stop_Energy-Guzzling_device();
}

void tft_Setup() {  // no sprites because the data on the screen is rather static
  tft.init();
  tft.setRotation(3);
  tft.setTextWrap(false);
  tft.fillScreen(TFT_BLACK);  // delete output from previous sessions
  tft.drawCentreString("Connecting to WiFi", 240, 160, 4);
}

bool timeElapsed(unsigned long myMillis) {  // avoid blocking task "delay(millisec)"
  return millis() - lastAction >= myMillis;
}

void showStartupData() {
  tft.fillScreen(TFT_BLACK);
  tft.drawCentreString("Retrieving SNTP time", 240, 160, 4);
  getLocalTime(&tInfo);
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_ORANGE);
  tft.drawCentreString("Retrieving Json Data", 240, 160, 4);
}

void changeView() {
  if (timeElapsed(800)) {  // UI debouncing (flash button)
    chart = !chart;
    redraw();
    lastAction = millis();
  }
}

void redraw() {
  selectWindow();
  chart ? show_Chart() : show_Data();
  showCurrentPrice();
  lastDrawHour = tInfo.tm_hour;
}

bool needNewData(time_t now) {
  if (freshStart) return true;
  if (!lastFetchOk) return millis() - lastFetchMillis >= RETRY_MS;  // previous attempt failed
  bool tomorrowMissing = (apiItems == 0) || (epoc[apiItems - 1] - now < 12 * 3600);
  return tomorrowMissing && (tInfo.tm_hour != lastFetchHour) && (tInfo.tm_min >= 2);
}

void display_Time() {
  if (!getLocalTime(&tInfo, 10)) return;  // SNTP sync at startup and every 3 hours thereafter (ESP32)
  if (tInfo.tm_sec == lastSec) return;    // update the screen only once per second
  lastSec = tInfo.tm_sec;
  char theDate[11], theTime[9];
  time_t now;
  time(&now);  // assign current epoch time (UTC) to "now"
  tft.drawRect(-1, 26, 482, 2, WiFi.isConnected() ? TFT_GREEN : TFT_RED);
  strftime(theDate, sizeof(theDate), "%d-%m-%Y", &tInfo);  // https://cplusplus.com/reference/ctime/strftime/
  strftime(theTime, sizeof(theTime), "%T", &tInfo);
  tft.setTextColor(TFT_GREEN, TFT_BLACK), tft.drawString(theDate, 2, 0, 4);
  tft.setTextColor(TFT_WHITE, TFT_BLACK), tft.drawString(theTime, 139, 0, 4);
  tft.setTextColor(lastFetchOk ? TFT_GREEN : TFT_RED, TFT_BLACK);  // region label: red if last API call failed
  tft.drawRightString(REGION_LABEL, 480, 8, 2);
  if (needNewData(now) && WiFi.isConnected()) {
    lastFetchOk = get_JsonData();
    freshStart = false;
    redraw();
  } else if (tInfo.tm_hour != lastDrawHour) redraw();  // new hour: move the cursor / current price
}

void selectWindow() {  // copy SHOW_ITEMS records around the current hour to the display arrays
  time_t now;
  time(&now);
  memset(prijzen, 0, sizeof(prijzen));
  memset(epo, 0, sizeof(epo));
  priceNow = NAN;
  if (!apiItems) return;
  int cur = -1;
  for (int i = 0; i < apiItems; i++)
    if (epoc[i] <= now) cur = i;
  if (cur >= 0 && now < epoc[cur] + 3600) priceNow = prices[cur];
  int start = cur - 3;                                         // show a few past hours
  if (start > apiItems - SHOW_ITEMS) start = apiItems - SHOW_ITEMS;  // but fill the screen with future hours
  if (start < 0) start = 0;
  for (int i = 0; i < SHOW_ITEMS && start + i < apiItems; i++) {
    prijzen[i] = prices[start + i];
    epo[i] = epoc[start + i];
  }
}

uint16_t priceColor(float p) {
  if (p < 0) return TFT_YELLOW;
  if (p < VALUE_GREEN) return TFT_GREEN;
  if (p < VALUE_RED) return TFT_CYAN;
  return TFT_RED;
}

bool isCurrent(time_t t, time_t now) {
  return t && now >= t && now < t + 3600;
}

float chartLo, chartScale;  // lowest value on the axis (ct) and pixels per ct
int yOf(float v) { return lroundf(PLOT_BOTTOM - (v - chartLo) * chartScale); }

void show_Chart() {  // auto-scaling bar chart: range follows the prices in the window
  time_t now;
  time(&now);
  tft.fillRect(0, 28, 480, 292, TFT_BLACK);  // erase any previous graphic data
  float vmin = 0, vmax = SCALE_MIN_TOP;      // determine the range of the visible prices
  for (uint8_t i = 0; i < SHOW_ITEMS; i++)
    if (epo[i]) vmin = min(vmin, prijzen[i]), vmax = max(vmax, prijzen[i]);
  float range = vmax - vmin;  // grid step: max. 6 to 7 grid lines
  int step = range <= 60 ? 10 : range <= 120 ? 20 : range <= 300 ? 50 : 100;
  int lo = (int)floorf(vmin / step) * step;
  int hi = (int)ceilf(vmax / step) * step;
  chartLo = lo;
  chartScale = float(PLOT_BOTTOM - PLOT_TOP) / (hi - lo);
  int zeroY = yOf(0);
  tft.setTextColor(tft.color565(160, 160, 160));
  for (int v = lo; v <= hi; v += step) {  // horizontal grid lines and value labels
    int y = yOf(v);
    tft.drawFastHLine(0, y, 480, v == 0 ? tft.color565(110, 110, 110) : tft.color565(48, 48, 48));
    int ly = (y - 4 < 29) ? y + 2 : y - 4;  // keep the top label below the header line
    for (uint8_t j = 0; j < 4; j++) tft.drawRightString(String(v), j * 150 + 23, ly, 1);
  }
  if (!apiItems) {
    tft.setTextColor(TFT_ORANGE);
    tft.drawCentreString("No price data", 240, 150, 4);
    return;
  }
  for (uint8_t i = 0; i < SHOW_ITEMS; i++) {
    if (!epo[i]) continue;  // only process if there is valid data
    int x = i * 14;
    uint8_t hr = localtime(&epo[i])->tm_hour;  // convert epoch to local time
    bool cur = isCurrent(epo[i], now);
    if (cur) {
      tft.drawFastVLine(x + 6, 28, PLOT_BOTTOM - 28, TFT_MAGENTA);
      tft.fillTriangle(x - 4, 293, x - 4, 303, x + 6, 298, TFT_MAGENTA);
      tft.fillTriangle(x - 4, 31, x - 4, 41, x + 6, 36, TFT_MAGENTA);
    }
    int y = yOf(prijzen[i]);  // bar from the zero line up (positive) or down (negative)
    int top = min(y, zeroY), h = abs(y - zeroY);
    if (h == 0) h = 1;        // show at least a thin line for 0 ct
    tft.fillRect(x, top, 13, h, priceColor(prijzen[i]));
    tft.setTextColor(cur ? TFT_MAGENTA : TFT_RED);  // hour label at the bottom of the chart
    tft.setCursor(x + 1, 310, 1);
    tft.printf("%02d", hr);
  }
}

void show_Data() {  // display Json data in 2 columns (time / price)
  time_t now;
  time(&now);
  tft.fillRect(0, 28, 480, 292, TFT_BLACK);
  tft.drawRect(240, 26, 2, 292, WiFi.isConnected() ? TFT_GREEN : TFT_RED);
  for (uint8_t i = 0; i < SHOW_ITEMS; i++) {
    if (!epo[i]) continue;  // check for valid data
    struct tm* cor = localtime(&epo[i]);  // convert epoch to local time
    uint16_t xPos = (i < 18) ? 0 : 260;    // calculate position for cursor
    uint16_t yPos = 33 + (i % 18) * 16;
    tft.setTextColor(TFT_LIGHTGREY, TFT_BLACK);  // display index number
    tft.setCursor(xPos, yPos, 2);
    tft.printf(" %02d. ", i + 1);
    tft.setTextColor(isCurrent(epo[i], now) ? TFT_MAGENTA : TFT_WHITE, TFT_BLACK);
    tft.printf("%02d-%02d-%04d %02d:%02d", cor->tm_mday, cor->tm_mon + 1, cor->tm_year + 1900, cor->tm_hour, cor->tm_min);
    tft.setTextColor(priceColor(prijzen[i]), TFT_BLACK);
    tft.drawRightString(String(prijzen[i], 2), (i < 18 ? 220 : 480), yPos, 2);  // price on the right
  }
}

void showCurrentPrice() {  // price (upper right corner of display)
  tft.fillRect(252, 0, 200, 24, TFT_BLACK);
  tft.setTextColor(TFT_SILVER, TFT_BLACK);
  tft.drawString("ct/kWh:", 252, 0, 4);
  tft.setCursor(338, 0, 4);
  if (isnan(priceNow)) {
    tft.setTextColor(TFT_DARKGREY, TFT_BLACK);
    tft.print("--");
  } else {
    tft.setTextColor(priceColor(priceNow), TFT_BLACK);
    tft.printf("%.2f", priceNow);
  }
}

// ---------- API ----------------------------------------------------------------------------

long daysFromCivil(int y, unsigned m, unsigned d) {  // days since 1970-01-01 (no time zone involved)
  y -= m <= 2;
  const long era = (y >= 0 ? y : y - 399) / 400;
  const unsigned yoe = (unsigned)(y - era * 400);
  const unsigned doy = (153 * (m > 2 ? m - 3 : m + 9) + 2) / 5 + d - 1;
  const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
  return era * 146097 + (long)doe - 719468;
}

time_t parseTime(JsonVariantConst v) {  // ISO 8601 string (with Z, +hh:mm or local) or epoch (s / ms)
  if (v.is<long long>() || v.is<double>()) {
    double x = v.as<double>();
    if (x > 1e11) x /= 1000;  // milliseconds
    return (time_t)x;
  }
  const char* s = v.as<const char*>();
  if (!s || strlen(s) < 10) return 0;
  int Y, M, D, h = 0, m = 0, sec = 0;
  if (sscanf(s, "%d-%d-%d%*c%d:%d:%d", &Y, &M, &D, &h, &m, &sec) < 3) return 0;
  const char* tz = nullptr;
  for (const char* c = s + 10; *c; c++)
    if (*c == 'Z' || *c == '+' || *c == '-') {
      tz = c;
      break;
    }
  if (!tz) {  // no offset: interpret as Belgian local time
    struct tm lt = {};
    lt.tm_year = Y - 1900, lt.tm_mon = M - 1, lt.tm_mday = D;
    lt.tm_hour = h, lt.tm_min = m, lt.tm_sec = sec, lt.tm_isdst = -1;
    return mktime(&lt);
  }
  time_t t = (time_t)daysFromCivil(Y, M, D) * 86400 + h * 3600 + m * 60 + sec;
  if (*tz == 'Z') return t;
  int oh = 0, om = 0;
  sscanf(tz + 1, "%2d%*[:]%2d", &oh, &om);
  int offset = oh * 3600 + om * 60;
  return (*tz == '+') ? t - offset : t + offset;
}

JsonVariantConst pick(JsonObjectConst o, std::initializer_list<const char*> keys) {  // first existing key
  for (const char* k : keys) {
    JsonVariantConst v = o[k];
    if (!v.isNull()) return v;
  }
  return JsonVariantConst();
}

uint8_t addItems(JsonArrayConst arr, uint8_t n, float* p, time_t* e) {
  for (JsonObjectConst it : arr) {
    if (n >= MAX_ITEMS) break;
    JsonVariantConst tv = pick(it, { "t", "time", "datetime", "timestamp", "start" });
    JsonVariantConst pv = pick(it, { "price", "total" });
    if (tv.isNull() || pv.isNull()) continue;
    time_t t = parseTime(tv);
    if (t <= 0) continue;
    e[n] = t;
    p[n] = pv.is<const char*>() ? atof(pv.as<const char*>()) : pv.as<float>();
    n++;
  }
  return n;
}

bool get_JsonData() {
  lastFetchMillis = millis();
  lastFetchHour = tInfo.tm_hour;
  WiFiClientSecure client;
  client.setInsecure();  // no certificate check (same as before)
  HTTPClient http;
  http.setUserAgent("espgo.be-S035");
  http.setTimeout(10000);
  if (!http.begin(client, API_URL)) return false;
  int code = http.GET();  // only one request
  if (code != HTTP_CODE_OK) {
    Serial.printf("HTTP error: %d\n", code);
    http.end();
    return false;  // keep the old data, retry in 10 minutes
  }
  String json = http.getString();
  http.end();
  Serial.println(json.substring(0, 400));  // first part of the answer, handy for checking the format

  JsonDocument doc;
  DeserializationError error = deserializeJson(doc, json);
  if (error) {
    Serial.printf("deserializeJson() failed: %s\n", error.c_str());
    return false;
  }
  JsonVariantConst root = doc["data"].isNull() ? doc.as<JsonVariantConst>() : doc["data"].as<JsonVariantConst>();
  float p[MAX_ITEMS];
  time_t e[MAX_ITEMS];
  uint8_t n = addItems(root["today"], 0, p, e);
  n = addItems(root["tomorrow"], n, p, e);
  if (n == 0) n = addItems(root["prices"], 0, p, e);  // fallback for a flat list
  if (n == 0) {
    Serial.println("No usable prices in the API response");
    return false;
  }
  for (uint8_t i = 1; i < n; i++) {  // sort by time (insertion sort)
    for (uint8_t j = i; j > 0 && e[j - 1] > e[j]; j--) {
      std::swap(e[j - 1], e[j]);
      std::swap(p[j - 1], p[j]);
    }
  }
  float maxAbs = 0;  // determine the unit and convert to ct/kWh
  for (uint8_t i = 0; i < n; i++) maxAbs = max(maxAbs, fabsf(p[i]));
  float factor = 1.0;                  // already ct/kWh
  if (maxAbs < 5) factor = 100.0;      // EUR/kWh
  else if (maxAbs > 200) factor = 0.1; // EUR/MWh
  for (uint8_t i = 0; i < n; i++) {
    prices[i] = p[i] * factor;
    epoc[i] = e[i];
  }
  apiItems = n;
  Serial.printf("%d prices received, last one: %s", n, ctime(&epoc[n - 1]));
  return true;
}

void messageNoConnection(WiFiManager* myWiFi) {
  const char* connect[] = { "WiFi: no connection", "Connect to hotspot", this_Ssid, "Start a browser - address",
                            "192.168.4.1", "to save network", "and password" };
  tft.fillScreen(TFT_NAVY), tft.setTextColor(TFT_YELLOW);
  for (uint8_t i = 0; i < 7; i++) tft.drawCentreString(connect[i], 240, 40 + i * 30, 4);
}

Meer displays met de ESP8266 / ESP32

Benieuwd naar andere displays? Bekijk het volledige overzicht met o.a. TM1637, SSD1306, SH1106, ST7735, ST7789, e-paper en geïntegreerde displays zoals de Lilygo T-Display en de Waveshare ESP32-S3.