luego modificar el fichero User_Setup.h C:\Users\phari\Documents\Arduino\libraries\TFT_eSPI
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #define ILI9341_DRIVER // Pines reales del Solo Miner #define TFT_MISO -1 // No existe, pantalla write-only #define TFT_MOSI 13 #define TFT_SCLK 14 #define TFT_CS 15 #define TFT_DC 2 #define TFT_RST 4 // Fuentes #define LOAD_GLCD #define LOAD_FONT2 #define LOAD_FONT4 #define LOAD_FONT6 #define LOAD_FONT7 #define LOAD_FONT8 #define LOAD_GFXFF // Frecuencias seguras #define SPI_FREQUENCY 40000000 #define SPI_READ_FREQUENCY 20000000 |
A continuación os dejamos el código completo del correspondiente .INO, con comentarios suficientes como para que podáis usarlo de referencia y, con suerte, ahorraros una parte del tiempo que a nosotros nos ha costado conseguir que todo funcione como debería.

Uno de los momentos “divertidos” del proyecto ha sido el autodiscovery MQTT: en teoría, Home Assistant debería crear automáticamente los sensores definidos desde Arduino… pero en la práctica nos encontramos con un error tan críptico como inútil. Tras varias horas de depuración, logs, pruebas y algún que otro suspiro existencial, descubrimos que el problema no era la lógica, ni el formato JSON, ni el topic… sino algo mucho más prosaico: el tamaño máximo del payload.
Uno de nuestros sensores generaba en su definición un mensaje que excedía los 128 bytes por defecto, así que Home Assistant simplemente ignoraba la creación del sensor. La “solución”, por llamarla de alguna manera, fue ampliar ese límite a 1024 bytes en el fichero PubSubClient.h de la correspondiente librería PubSubClient.
.
Un cambio trivial que, por supuesto, tardamos más de lo que nos gustaría admitir en encontrar.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 | /* ============================================================ IMPORTANT NOTE ABOUT PUBSUBCLIENT.H (MODIFICATION APPLIED) ============================================================ Modified file: C:\Users\phari\Documents\Arduino\libraries\PubSubClient\src\PubSubClient.h Original line: #define MQTT_MAX_PACKET_SIZE 128 Final line (modified by Pharizna on 05/07/2026): #define MQTT_MAX_PACKET_SIZE 1024 Reason: The MQTT autodiscovery payload is approximately 350–450 bytes. PubSubClient, with the original 128‑byte limit, rejected large messages and returned "FAIL" when publishing autodiscovery topics. Increasing the limit to 1024 bytes allows the ESP32 to send full autodiscovery messages successfully, and Mosquitto accepts them without any issues. ============================================================ */ #include <TFT_eSPI.h> #include <SPI.h> #include <WiFi.h> #include <Wire.h> #include <Adafruit_Sensor.h> #include <Adafruit_BME280.h> #include "DHT.h" #include <time.h> #include <PubSubClient.h> #include "secrets.h" #include "logo_small.h" TFT_eSPI tft = TFT_eSPI(); /******************************************************* * USER CONFIGURABLE TIMING (GLOBAL SETTINGS) *******************************************************/ #define READ_INTERVAL 10000 // Sensor read interval (ms) #define MQTT_INTERVAL 15000 // MQTT publish interval (ms) #define HEARTBEAT_INTERVAL 1000 // Heartbeat blink interval (ms) /******************************************************* * HEARTBEAT VARIABLES *******************************************************/ bool heartbeatState = false; unsigned long lastHeartbeat = 0; /******************************************************* * MQTT CLIENT SETUP *******************************************************/ WiFiClient espClient; PubSubClient client(espClient); const char* mqtt_server = MQTT_SERVER; const int mqtt_port = MQTT_PORT; const char* mqtt_user = MQTT_USER; const char* mqtt_pass = MQTT_PASS; const char* device_id = "cydstation_103"; const char* client_id = "cydstation_103_esp32"; const char* availability_topic = "homeassistant/sensor/cydstation_103/availability"; /******************************************************* * SENSOR DEFINITIONS (v1.0.3) *******************************************************/ struct SensorDef { const char* id; const char* name; const char* topic; const char* unit; const char* device_class; }; SensorDef sensors[] = { { "cyd_temp_103", "CYD Temperature v1.0.3", "pcdemano/temperatura", "\xC2\xB0""C", "temperature" }, { "cyd_hum_103", "CYD Humidity v1.0.3", "pcdemano/humedad", "%", "humidity" }, { "cyd_pres_103", "CYD Pressure v1.0.3", "pcdemano/presion", "hPa", "pressure" } }; /******************************************************* * MQTT AUTODISCOVERY (DOUBLE PUBLISH METHOD) *******************************************************/ void sendDiscovery() { Serial.println("sendDiscovery() called"); client.publish(availability_topic, (uint8_t*)"online", 6, true); for (auto &s : sensors) { String cfgTopic = "homeassistant/sensor/" + String(device_id) + "/" + String(s.id) + "/config"; String payload = "{" "\"name\":\"" + String(s.name) + "\"," "\"state_topic\":\"" + String(s.topic) + "\"," "\"unit_of_measurement\":\"" + String(s.unit) + "\"," "\"device_class\":\"" + String(s.device_class) + "\"," "\"unique_id\":\"" + String(s.id) + "\"," "\"object_id\":\"" + String(s.id) + "\"," "\"availability_topic\":\"" + String(availability_topic) + "\"," "\"device\":{" "\"identifiers\":[\"" + String(device_id) + "\"]," "\"name\":\"CYD Station v1.0.3\"," "\"manufacturer\":\"CYD Studio\"," "\"model\":\"CYD Station v1.0.3\"" "}" "}"; Serial.println("--------------------------------"); Serial.print("Topic: "); Serial.println(cfgTopic); Serial.print("Payload length: "); Serial.println(payload.length()); Serial.println(payload); bool ok = client.publish(cfgTopic.c_str(), (uint8_t*)payload.c_str(), payload.length(), true); Serial.print("Autodiscovery sent: "); Serial.print(s.id); Serial.print(" → "); Serial.println(ok ? "OK" : "FAIL"); } } void mqttCallback(char* topic, byte* payload, unsigned int length) {} /******************************************************* * MQTT RECONNECTION LOGIC *******************************************************/ void reconnect() { while (!client.connected()) { Serial.println("Trying to connect to MQTT..."); if (client.connect(client_id, mqtt_user, mqtt_pass)) { Serial.println("MQTT connected. Sending autodiscovery..."); sendDiscovery(); } else { Serial.print("MQTT error: "); Serial.println(client.state()); delay(1000); } } } /******************************************************* * SENSOR VALUES (SLOW UPDATE) *******************************************************/ float dhtHum = 0; float dhtTemp = 0; float bmePres = 0; /******************************************************* * MQTT DATA PUBLISHING *******************************************************/ void publishData() { Serial.println("Publishing sensor data..."); char buf[16]; sprintf(buf, "%.1f", dhtTemp); client.publish("pcdemano/temperatura", buf, true); sprintf(buf, "%.1f", dhtHum); client.publish("pcdemano/humedad", buf, true); sprintf(buf, "%.0f", bmePres); client.publish("pcdemano/presion", buf, true); } /******************************************************* * SENSOR HARDWARE SETUP *******************************************************/ #define SDA_PIN 22 #define SCL_PIN 21 #define DHTPIN 25 #define DHTTYPE DHT22 Adafruit_BME280 bme; DHT dht(DHTPIN, DHTTYPE); /******************************************************* * UI LAYOUT POSITIONS *******************************************************/ const int TITLE_Y = 18; const int HORA_Y = 53; const int TEMP_Y = 110; const int HUM_Y = 160; const int PRES_Y = 210; const int ICON_X = 60; const int TEMP_ICON_Y = 120; const int HUM_ICON_Y = 170; const int PRES_ICON_Y = 220; /******************************************************* * SMALL ICON DRAWING ROUTINES *******************************************************/ void drawSunSmall(int x, int y) { x -= 5; tft.fillCircle(x, y, 8, TFT_YELLOW); for (int i = 0; i < 360; i += 45) { float rad = i * 0.0174533; int x2 = x + cos(rad) * 12; int y2 = y + sin(rad) * 12; tft.drawLine(x, y, x2, y2, TFT_YELLOW); } } void drawDropSmall(int x, int y) { y -= 4; x -= 5; tft.fillCircle(x, y + 6, 8, TFT_CYAN); tft.fillTriangle(x - 8, y + 6, x + 8, y + 6, x, y - 6, TFT_CYAN); } void drawPressureSmall(int x, int y) { y -= 2; x -= 3; tft.drawCircle(x, y+5, 10, TFT_ORANGE); tft.drawCircle(x, y+5, 5, TFT_ORANGE); } /******************************************************* * FRAME DRAWING *******************************************************/ void drawFrame(int w, int h) { tft.drawRect(5, 5, w - 10, h - 10, TFT_DARKGREY); tft.drawRect(7, 7, w - 14, h - 14, TFT_DARKGREY); tft.drawLine(5, h - 5, w - 5, h - 5, TFT_DARKGREY); } /******************************************************* * TIME STRING (HH:MM) *******************************************************/ String getTimeString() { struct tm timeinfo; if (!getLocalTime(&timeinfo)) return "--:--"; char buffer[6]; sprintf(buffer, "%02d:%02d", timeinfo.tm_hour, timeinfo.tm_min); return String(buffer); } /******************************************************* * STATIC UI (DRAW ONCE) *******************************************************/ void drawStaticUI() { int screenW = tft.width(); int screenH = tft.height(); tft.fillScreen(TFT_BLACK); drawFrame(screenW, screenH); tft.setTextColor(TFT_RED); tft.setTextSize(3); String titulo = "CYD Station"; int titleX = (screenW - tft.textWidth(titulo)) / 2; tft.setCursor(titleX, TITLE_Y); tft.print(titulo); drawSunSmall(ICON_X, TEMP_ICON_Y); drawDropSmall(ICON_X, HUM_ICON_Y); drawPressureSmall(ICON_X, PRES_ICON_Y); int logoW = 184; int logoH = 50; int logoX = (screenW - logoW) / 2; int logoY = screenH - logoH - 13; tft.setSwapBytes(true); tft.pushImage(logoX, logoY, logoW, logoH, logo_scaled); } /******************************************************* * HEARTBEAT DRAWING (inside frame corner) *******************************************************/ void drawHeartbeat() { int x = 12; // posición final solicitada int y = 12; // posición final solicitada if (heartbeatState) { tft.fillCircle(x, y, 2, TFT_RED); } else { tft.fillCircle(x, y, 2, TFT_BLACK); } } /******************************************************* * SMOOTH TEXT UPDATE (SAFE RECTANGLE) *******************************************************/ String lastTemp = ""; String lastHum = ""; String lastPres = ""; // SAFE: does NOT erase icons or borders void smoothUpdate(int x, int y, String oldVal, String newVal, uint16_t color) { if (oldVal == newVal) return; int maxWidth = max(tft.textWidth(oldVal), tft.textWidth(newVal)); // Ajuste especial para la presión if (y == PRES_Y) { if (maxWidth > 110) maxWidth = 110; } else { if (maxWidth > 150) maxWidth = 150; } int rectX = x - 5; if (rectX < 100) rectX = 100; // nunca borrar iconos tft.fillRect(rectX, y - 5, maxWidth + 10, 40, TFT_BLACK); tft.setTextColor(color); tft.setCursor(x, y); tft.print(newVal); } /******************************************************* * SENSOR UI UPDATE (FIXED POSITIONS) *******************************************************/ void updateSensorUI() { tft.setTextSize(3); // FIXED X POSITIONS (safe, aligned, no icon overlap) const int VALUE_X = 85; // posición final solicitada // Temperature String tempStr = String(dhtTemp, 1) + " C"; smoothUpdate(VALUE_X, TEMP_Y, lastTemp, tempStr, TFT_YELLOW); lastTemp = tempStr; // Humidity String humStr = String(dhtHum, 1) + " %"; smoothUpdate(VALUE_X, HUM_Y, lastHum, humStr, TFT_CYAN); lastHum = humStr; // Pressure String presStr = String((int)bmePres) + " hPa"; smoothUpdate(VALUE_X, PRES_Y, lastPres, presStr, TFT_ORANGE); lastPres = presStr; } /******************************************************* * TIME UI UPDATE (EVERY MINUTE) *******************************************************/ void updateTimeUI() { static String lastHora = ""; String hora = getTimeString(); if (hora == lastHora) return; tft.setTextColor(0x8410); tft.setTextSize(2); int horaX = (tft.width() - tft.textWidth(hora)) / 2; tft.fillRect(horaX - 5, HORA_Y - 2, tft.textWidth(hora) + 10, 20, TFT_BLACK); tft.setCursor(horaX, HORA_Y); tft.print(hora); lastHora = hora; } /******************************************************* * CLOCK INITIALIZATION (NTP) *******************************************************/ void initClock(){ configTime(0,0,"pool.ntp.org","time.nist.gov"); setenv("TZ","CET-1CEST,M3.5.0/2,M10.5.0/3",1); tzset(); struct tm t; while(!getLocalTime(&t)){delay(200);} } /******************************************************* * SETUP ROUTINE *******************************************************/ void setup() { Serial.begin(115200); delay(2000); Serial.println("Starting CYD Station v1.0.3..."); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); while (WiFi.status() != WL_CONNECTED) { Serial.println("Connecting to WiFi..."); delay(500); } Serial.println("WiFi connected."); initClock(); Wire.begin(SDA_PIN, SCL_PIN); bme.begin(0x77); dht.begin(); tft.init(); tft.setRotation(0); pinMode(27, OUTPUT); digitalWrite(27, HIGH); drawStaticUI(); client.setServer(mqtt_server, mqtt_port); client.setCallback(mqttCallback); reconnect(); } /******************************************************* * MAIN LOOP *******************************************************/ void loop() { unsigned long now = millis(); updateTimeUI(); // Heartbeat blink if (now - lastHeartbeat > HEARTBEAT_INTERVAL) { lastHeartbeat = now; heartbeatState = !heartbeatState; drawHeartbeat(); } static unsigned long lastRead = 0; static unsigned long lastPub = 0; // Read sensors every READ_INTERVAL if (now - lastRead > READ_INTERVAL) { lastRead = now; dhtHum = dht.readHumidity(); dhtTemp = dht.readTemperature(); bmePres = bme.readPressure() / 100.0; updateSensorUI(); } if (!client.connected()) reconnect(); client.loop(); // Publish MQTT data every MQTT_INTERVAL if (now - lastPub > MQTT_INTERVAL) { lastPub = now; publishData(); } } |
Tampoco fue precisamente un paseo convertir nuestro logo en PNG a un fichero .h sin halos blancos, sin transparencias traicioneras y sin que la pantalla TFT pareciera recién salida de un paintball. La teoría decía que bastaba con aplicar un simple rgb888_to_rgb565 y listo; la práctica, en cambio, nos recordó que nada es “simple” cuando se mezclan PNGs, canales alfa y librerías de terceros. Al final lo resolvimos escribiendo un programita en Python que, sobre el papel, era “sencillo”… aunque nos llevó más iteraciones de las que nos gustaría admitir. Pero bueno, esa historia merece capítulo propio, así que la dejamos para otro día.
Otra de las cosas que no nos ha dejado del todo satisfechos es el comportamiento de la CYD cuando, por arte de magia o por capricho del router, se pierde la conexión con Home Assistant. En la versión actual del software que hemos hecho, la placa solo comprueba la conexión al inicio, como si la WiFi fuese una entidad estable, fiable y digna de confianza. La realidad, por supuesto, es que la WiFi y MQTT tienen la mala costumbre de desconectarse justo cuando más los necesitas, y nuestra CYD —muy obediente ella— se queda mirando al vacío sin intentar reconectar. Lo ideal sería añadir una comprobación periódica de estado, tanto de la WiFi como del cliente MQTT, y relanzar la conexión cuando toque. Nada dramático, pero sí una mejora necesaria para que la estación no se convierta en un adorno cuando el router decide echarse la siesta.
103
Otro de los errores que nos ha hecho perder mucho tiempo en esta revisión fue causada por el «autodiscovery» para MQTT… que no funcionaba para crear la variable de temperatur y que iba bien para humedad y presión.
SensorDef sensors[] = {
{ «cyd_temp_103», «CYD Temperature v1.0.3», «pcdemano/temperatura», «\xC2\xB0″»C», «temperature» },
{ «cyd_hum_103», «CYD Humidity v1.0.3», «pcdemano/humedad», «%», «humidity» },
{ «cyd_pres_103», «CYD Pressure v1.0.3», «pcdemano/presion», «hPa», «pressure» }
};
Después de muchas pruebas vimos que como unidad en el .INO habíamos utilizado C en lugar de ºC… lo que no gustaba al compilador.
Tampoco aceptaba poner «ºC» por lo que finalmente tuvimos que usar «\xC2\xB0″»C» que, como todo el mundo sabe es equivalente pero que sí parece gustar al compilador