Skip to content

Instantly share code, notes, and snippets.

@HDRobotica
Created September 20, 2025 11:42
Show Gist options
  • Select an option

  • Save HDRobotica/0b331bbe5caf1f78a18697e1bcc4e061 to your computer and use it in GitHub Desktop.

Select an option

Save HDRobotica/0b331bbe5caf1f78a18697e1bcc4e061 to your computer and use it in GitHub Desktop.
✨ Smart Home Projekt: ESP32 Touchscreen Control Panel für 4-Kanal-Relais | WLAN + Webinterface
#include <TFT_eSPI.h>
#include <SPI.h>
#include <WiFi.h>
#include <Preferences.h>
#include <time.h>
#include <TJpg_Decoder.h>
#define FS_NO_GLOBALS
#include <FS.h>
#ifdef ESP32
#include "SPIFFS.h"
#endif
#include <SD.h>
#include <HTTPClient.h> // Für HTTP-Requests
#include <ArduinoJson.h> // Für JSON-Parsing
// TFT instance and colors
TFT_eSPI tft = TFT_eSPI();
#define BLACK 0x0000
#define WHITE 0xFFFF
#define RED 0xF800
#define GREEN 0x07E0
#define BLUE 0x001F
#define PURPLE 0x781F
#define LIGHT_GREY 0xC618
#define DARK_GREY 0x7BEF
#define TITLE_BG 0x03EF // Helleres Blau für Titel
#define ORANGE_TOP 0xFD20 // Orange für Hauptmenü-Buttons, Einstellungen, SD Bilder, Back
#define ORANGE_BOT 0xF800
#define BLUE_TOP 0x1C9F // Blau für Button 6 und WiFi
#define BLUE_BOT 0x001F
#define GREEN_TOP 0x1FE0 // Grün für Grün-Button in LED Settings
#define GREEN_BOT 0x07E0
#define PURPLE_TOP 0xA81F // Lila für Info
#define PURPLE_BOT 0x781F
#define RED_TOP 0xF820 // Rot für Back in anderen Bildschirmen
#define RED_BOT 0xF800
#define BOX_WIDTH 110
#define BOX_HEIGHT 66
#define SCREEN_WIDTH 240
#define SCREEN_HEIGHT 320
#define ROUND_RADIUS 8
#define MARGIN 8
#define KB_KEY_WIDTH 22
#define KB_KEY_HEIGHT 35
#define KB_START_Y 120
// Touch calibration
#define TOUCH_X_MIN 580
#define TOUCH_X_MAX 3470
#define TOUCH_Y_MIN 400
#define TOUCH_Y_MAX 3720
#define TOUCH_THRESHOLD 100
// RGB LED Pins
#define LED_R 17
#define LED_G 4
#define LED_B 16
// Backlight Pin
#define BACKLIGHT_PIN 27
// SD CS Pin
#define SD_CS 5
// Preferences
Preferences prefs;
String savedSSID = "";
String savedPassword = "";
// LED settings - ALL OFF BY DEFAULT
bool enableLEDR = false;
bool enableLEDG = false;
bool enableLEDB = false;
bool highBrightness = true; // true = full (255), false = half (128)
bool blinkingEnabled = false; // Blinking mode
unsigned long lastBlink = 0;
bool blinkState = false;
#define BLINK_INTERVAL 500 // 500ms blink interval
// Screen states
enum ScreenState { MAIN_MENU, SETTINGS, WIFI_LIST, KEYBOARD, INFO, LED_SETTINGS, IMAGE_VIEWER };
ScreenState currentState = MAIN_MENU;
// WiFi
int numNetworks = 0;
String networks[10];
int selectedNetwork = -1;
// Keyboard
String inputPassword = "";
// Image viewer
String imageFiles[10];
int numImages = 0;
int selectedImage = -1;
// Keyboard layout
const char keyboardLayout[4][11] = {
{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '<'},
{'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', ' '},
{'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', '.', ' '},
{'Z', 'X', 'C', 'V', 'B', 'N', 'M', '-', '_', '!', ' '}
};
// Box definitions
struct Box {
int x, y, w, h;
String label;
void (*action)();
uint16_t topColor, botColor;
};
Box boxes[6];
Box settingsBox;
Box wifiBox;
Box infoBox;
Box ledBox;
Box imageBox;
Box backBox;
Box toggleLEDRBox;
Box toggleLEDGBox;
Box toggleLEDBBox;
Box brightnessBox;
Box blinkBox;
// IP des ESP8266 Relay-Boards
const char* relayIP = "192.168.178.88"; // Feste IP aus deinem ESP8266-Code
const int relayPort = 80;
// Relais-Authentifizierung (aus ESP8266-Code)
const char* relayUsername = "admin";
const char* relayPassword = "passwort123";
// Relais-Status (für Button-Labels)
bool relayState[4] = {false, false, false, false};
// Status für alle Relais (für Button 5)
bool allRelaisState = false;
// JPG rendering callback
bool tft_output(int16_t x, int16_t y, uint16_t w, uint16_t h, uint16_t* bitmap) {
if (y >= tft.height()) return 0;
if (x < 0) { int offset = -x; x = 0; bitmap += offset; w -= offset; }
if (y < 0) { int offset = -y; y = 0; bitmap += offset * w; h -= offset; }
if (x + w > tft.width()) w = tft.width() - x;
if (y + h > tft.height()) h = tft.height() - y;
if (w > 0 && h > 0) {
tft.pushImage(x, y, w, h, bitmap);
}
return 1;
}
// 3D-Gradient-Button mit variablen Farben (korrigierte Bitmasken)
void draw3DButton(int x, int y, int w, int h, uint16_t topColor, uint16_t botColor, String label, uint8_t textSize, bool useBlackText = false) {
// Gradientenfüllung
tft.fillRoundRect(x, y, w, h, ROUND_RADIUS, topColor);
for (int i = 0; i < h; i++) {
uint8_t r = map(i, 0, h - 1, ((topColor >> 11) & 0x1F) << 3, ((botColor >> 11) & 0x1F) << 3);
uint8_t g = map(i, 0, h - 1, ((topColor >> 5) & 0x3F) << 2, ((botColor >> 5) & 0x3F) << 2);
uint8_t b = map(i, 0, h - 1, (topColor & 0x1F) << 3, (botColor & 0x1F) << 3);
uint16_t color = tft.color565(r, g, b);
tft.drawFastHLine(x + ROUND_RADIUS, y + i, w - 2 * ROUND_RADIUS, color);
if (i < ROUND_RADIUS) {
tft.drawFastHLine(x + ROUND_RADIUS - i, y + i, i, color);
tft.drawFastHLine(x + w - ROUND_RADIUS, y + i, i, color);
} else if (i >= h - ROUND_RADIUS) {
int offset = h - 1 - i;
tft.drawFastHLine(x + ROUND_RADIUS - offset, y + i, offset, color);
tft.drawFastHLine(x + w - ROUND_RADIUS, y + i, offset, color);
}
}
// Abgerundete Ränder
tft.drawRoundRect(x, y, w, h, ROUND_RADIUS, WHITE);
tft.drawRoundRect(x + 1, y + 1, w - 2, h - 2, ROUND_RADIUS, LIGHT_GREY);
tft.drawRoundRect(x + 2, y + 2, w - 4, h - 4, ROUND_RADIUS, DARK_GREY);
// Schatten für 3D-Effekt
tft.drawLine(x + ROUND_RADIUS, y + h - 1, x + w - ROUND_RADIUS, y + h - 1, BLACK);
tft.drawLine(x + w - 1, y + ROUND_RADIUS, x + w - 1, y + h - ROUND_RADIUS, BLACK);
// Text
tft.setTextColor(useBlackText ? BLACK : WHITE);
tft.setTextSize(textSize);
drawCenteredText(label, x, y + (h - textSize * 8) / 2, w, textSize);
}
void setup() {
Serial.begin(115200);
Serial.println("\nHD Robotics Control Panel starting...");
// SD initialisieren - mit Retry
bool sdOk = false;
if (!SD.begin(SD_CS)) {
Serial.println(F("SD.begin failed! (Erster Versuch)"));
delay(100);
if (!SD.begin(SD_CS)) {
Serial.println(F("SD.begin failed! (Zweiter Versuch)"));
} else {
sdOk = true;
}
} else {
sdOk = true;
}
if (sdOk) {
Serial.println("SD initialisiert.");
uint8_t cardType = SD.cardType();
if (cardType == CARD_NONE) {
Serial.println("Keine SD-Karte!");
} else {
Serial.printf("SD Card Type: %u\n", cardType);
Serial.printf("SD Card Size: %llu MB\n", SD.cardSize() / (1024 * 1024));
Serial.printf("SD Total Bytes: %llu\n", SD.totalBytes());
}
}
tft.init();
tft.setRotation(0);
// Touch wird automatisch initialisiert durch User_Setup.h
uint16_t xRaw = 0, yRaw = 0;
uint16_t zRaw = tft.getTouchRawZ();
tft.getTouchRaw(&xRaw, &yRaw);
Serial.printf("Initial Touch Raw: X=%d, Y=%d, Z=%d\n", xRaw, yRaw, zRaw);
if (zRaw > 0) {
Serial.println("Touch-Detektion OK!");
} else {
Serial.println("Touch-Detektion FEHLER! Überprüfe Verkabelung.");
}
pinMode(BACKLIGHT_PIN, OUTPUT);
digitalWrite(BACKLIGHT_PIN, HIGH);
tft.setSwapBytes(true);
TJpgDec.setJpgScale(1);
TJpgDec.setCallback(tft_output);
// RGB LED Pins setup
pinMode(LED_R, OUTPUT);
pinMode(LED_G, OUTPUT);
pinMode(LED_B, OUTPUT);
analogWrite(LED_R, 0);
analogWrite(LED_G, 0);
analogWrite(LED_B, 0);
// Initialize main menu boxes
int shift_left = 2;
int shift_up = 3;
boxes[0] = {MARGIN - shift_left, 40 + MARGIN - shift_up, BOX_WIDTH, BOX_HEIGHT, "Relais 1: AUS", toggleRelay1, ORANGE_TOP, ORANGE_BOT};
boxes[1] = {MARGIN + BOX_WIDTH + MARGIN - shift_left, 40 + MARGIN - shift_up, BOX_WIDTH, BOX_HEIGHT, "Relais 2: AUS", toggleRelay2, ORANGE_TOP, ORANGE_BOT};
boxes[2] = {MARGIN - shift_left, 40 + MARGIN + BOX_HEIGHT + MARGIN - shift_up, BOX_WIDTH, BOX_HEIGHT, "Relais 3: AUS", toggleRelay3, ORANGE_TOP, ORANGE_BOT};
boxes[3] = {MARGIN + BOX_WIDTH + MARGIN - shift_left, 40 + MARGIN + BOX_HEIGHT + MARGIN - shift_up, BOX_WIDTH, BOX_HEIGHT, "Relais 4: AUS", toggleRelay4, ORANGE_TOP, ORANGE_BOT};
boxes[4] = {MARGIN - shift_left, 40 + MARGIN + 2*(BOX_HEIGHT + MARGIN) - shift_up, BOX_WIDTH, BOX_HEIGHT, "Alle Relais: AUS", toggleAllRelais, ORANGE_TOP, ORANGE_BOT};
boxes[5] = {MARGIN + BOX_WIDTH + MARGIN - shift_left, 40 + MARGIN + 2*(BOX_HEIGHT + MARGIN) - shift_up, BOX_WIDTH, BOX_HEIGHT, "Button 6", toggleRunningLight, BLUE_TOP, BLUE_BOT};
settingsBox = {0, SCREEN_HEIGHT - 40, SCREEN_WIDTH, 40, "Einstellungen", settingsAction, ORANGE_TOP, ORANGE_BOT};
// Load saved WiFi credentials
prefs.begin("wifi", false);
savedSSID = prefs.getString("ssid", "");
savedPassword = prefs.getString("password", "");
prefs.end();
// Auto-connect to saved WiFi
if (savedSSID != "") {
connectToWiFi(savedSSID, savedPassword);
}
drawMainMenu();
}
void loop() {
uint16_t z = tft.getTouchRawZ();
if (z > TOUCH_THRESHOLD) {
uint16_t xRaw, yRaw;
tft.getTouchRaw(&xRaw, &yRaw);
Serial.printf("Touch erkannt! Raw: X=%d, Y=%d, Z=%d\n", xRaw, yRaw, z);
int x = map(yRaw, TOUCH_Y_MIN, TOUCH_Y_MAX, SCREEN_WIDTH, 0);
int y = map(xRaw, TOUCH_X_MIN, TOUCH_X_MAX, 0, SCREEN_HEIGHT);
x = constrain(x, 0, SCREEN_WIDTH - 1);
y = constrain(y, 0, SCREEN_HEIGHT - 1);
Serial.printf("Gemappte Koordinaten: X=%d, Y=%d\n", x, y);
handleTouch(x, y);
delay(200);
} else {
static unsigned long lastTest = 0;
if (millis() - lastTest > 5000) {
uint16_t tx = 0, ty = 0;
uint16_t tz = tft.getTouchRawZ();
tft.getTouchRaw(&tx, &ty);
if (tz == 0) {
Serial.println("Kein Touch erkannt (Normal, wenn nicht berührt).");
}
lastTest = millis();
}
}
updateLEDs();
// Periodische Relais-Status-Update (alle 10 Sekunden)
static unsigned long lastStatusUpdate = 0;
if (millis() - lastStatusUpdate >= 10000) {
updateRelayStatus();
lastStatusUpdate = millis();
}
delay(10);
}
void updateLEDs() {
if (!blinkingEnabled) {
uint8_t brightness = highBrightness ? 255 : 128;
if (enableLEDR) analogWrite(LED_G, brightness); // ROT-Button steuert Grün-LED
else analogWrite(LED_G, 0);
if (enableLEDG) analogWrite(LED_R, brightness); // Grün-Button steuert Rot-LED
else analogWrite(LED_R, 0);
if (enableLEDB) analogWrite(LED_B, brightness); // Blau-Button steuert Blau-LED
else analogWrite(LED_B, 0);
return;
}
unsigned long currentMillis = millis();
if (currentMillis - lastBlink >= BLINK_INTERVAL) {
blinkState = !blinkState;
lastBlink = currentMillis;
}
uint8_t brightness = highBrightness ? 255 : 128;
if (enableLEDR && blinkState) analogWrite(LED_G, brightness);
else analogWrite(LED_G, 0);
if (enableLEDG && blinkState) analogWrite(LED_R, brightness);
else analogWrite(LED_R, 0);
if (enableLEDB && blinkState) analogWrite(LED_B, brightness);
else analogWrite(LED_B, 0);
}
void drawMainMenu() {
currentState = MAIN_MENU;
tft.fillScreen(BLACK); // Einheitlicher schwarzer Hintergrund
drawRoundedFrame(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, WHITE, LIGHT_GREY, DARK_GREY);
tft.fillRoundRect(0, 0, SCREEN_WIDTH, 40, ROUND_RADIUS, TITLE_BG);
tft.setTextColor(WHITE);
tft.setTextSize(2);
drawCenteredText("HD Robotics", 0, 5, SCREEN_WIDTH, 2);
tft.setTextSize(1);
drawCenteredText("Control Panel", 0, 25, SCREEN_WIDTH, 1);
for (int i = 0; i < 6; i++) {
draw3DButton(boxes[i].x, boxes[i].y, boxes[i].w, boxes[i].h, boxes[i].topColor, boxes[i].botColor, boxes[i].label, 2);
}
draw3DButton(settingsBox.x, settingsBox.y, settingsBox.w, settingsBox.h, settingsBox.topColor, settingsBox.botColor, settingsBox.label, 2);
}
// Nur einen einzelnen Button neu zeichnen (ohne Blinken)
void updateSingleButton(int index) {
if (currentState == MAIN_MENU) {
// Nur den Button löschen und neu zeichnen
tft.fillRoundRect(boxes[index].x, boxes[index].y, boxes[index].w, boxes[index].h, ROUND_RADIUS, BLACK);
draw3DButton(boxes[index].x, boxes[index].y, boxes[index].w, boxes[index].h, boxes[index].topColor, boxes[index].botColor, boxes[index].label, 2);
}
}
void drawSettings() {
currentState = SETTINGS;
tft.fillScreen(BLACK); // Einheitlicher schwarzer Hintergrund
drawRoundedFrame(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, WHITE, LIGHT_GREY, DARK_GREY);
tft.setTextColor(WHITE);
tft.setTextSize(2);
drawCenteredText("Einstellungen", 0, 10, SCREEN_WIDTH, 2);
wifiBox = {MARGIN, 50, SCREEN_WIDTH - 2*MARGIN, 40, "WiFi", wifiAction, BLUE_TOP, BLUE_BOT};
draw3DButton(wifiBox.x, wifiBox.y, wifiBox.w, wifiBox.h, wifiBox.topColor, wifiBox.botColor, "WiFi", 2);
infoBox = {MARGIN, 100, SCREEN_WIDTH - 2*MARGIN, 40, "Info", infoAction, PURPLE_TOP, PURPLE_BOT};
draw3DButton(infoBox.x, infoBox.y, infoBox.w, infoBox.h, infoBox.topColor, infoBox.botColor, "Info", 2);
ledBox = {MARGIN, 150, SCREEN_WIDTH - 2*MARGIN, 40, "LED Settings", ledSettingsAction, BLUE_TOP, BLUE_BOT};
draw3DButton(ledBox.x, ledBox.y, ledBox.w, ledBox.h, ledBox.topColor, ledBox.botColor, "LED Settings", 2);
imageBox = {MARGIN, 200, SCREEN_WIDTH - 2*MARGIN, 40, "SD Bilder", imageViewerAction, ORANGE_TOP, ORANGE_BOT};
draw3DButton(imageBox.x, imageBox.y, imageBox.w, imageBox.h, imageBox.topColor, imageBox.botColor, "SD Bilder", 2);
backBox = {0, SCREEN_HEIGHT - 40, SCREEN_WIDTH, 40, "Back", nullptr, ORANGE_TOP, ORANGE_BOT};
draw3DButton(backBox.x, backBox.y, backBox.w, backBox.h, backBox.topColor, backBox.botColor, "Back", 2);
}
void scanSDImages(const String& path = "/", int levels = 3) {
if (levels < 0) return;
String tryPath = path;
if (path == "/") tryPath = "";
Serial.printf("Versuche Ordner öffnen: %s\n", tryPath.c_str());
File root = SD.open(tryPath);
if (!root) {
Serial.printf("Failed to open %s\n", tryPath.c_str());
if (tryPath == "") {
root = SD.open("/");
if (!root) {
Serial.println("Auch / fehlgeschlagen - SD lesbar?");
return;
}
} else {
return;
}
}
if (!root.isDirectory()) {
Serial.printf("%s ist kein Ordner\n", tryPath.c_str());
root.close();
return;
}
Serial.printf("Ordner %s geöffnet - Inhalt scannen...\n", tryPath.c_str());
File file = root.openNextFile();
while (file && numImages < 10) {
String filename = file.name();
Serial.print("Gefunden: "); Serial.println(filename);
if (file.isDirectory()) {
String subPath = (tryPath == "" ? "/" : tryPath + "/") + filename + "/";
Serial.printf(" ORDNER: %s\n", subPath.c_str());
scanSDImages(subPath, levels - 1);
} else {
String lowerName = filename;
lowerName.toLowerCase();
if (lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg")) {
String fullPath = (tryPath == "" ? "/" : "/" + tryPath + "/") + filename;
imageFiles[numImages] = fullPath;
Serial.printf(" JPG hinzugefügt: %s (Größe: %d)\n", fullPath.c_str(), file.size());
numImages++;
}
}
file = root.openNextFile();
}
root.close();
}
void drawImageList() {
currentState = IMAGE_VIEWER;
tft.fillScreen(BLACK); // Einheitlicher schwarzer Hintergrund
drawRoundedFrame(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, WHITE, LIGHT_GREY, DARK_GREY);
tft.setTextColor(WHITE);
tft.setTextSize(2);
drawCenteredText("SD JPG Bilder", 0, 10, SCREEN_WIDTH, 2);
numImages = 0;
scanSDImages("/", 3);
Serial.printf("Gesamt %d JPGs gefunden.\n", numImages);
if (numImages == 0) {
tft.setTextColor(RED);
tft.setTextSize(2);
drawCenteredText("Keine JPGs", 0, 50, SCREEN_WIDTH, 2);
tft.setTextSize(1);
drawCenteredText("SD-Fehler? Karte neu", 0, 70, SCREEN_WIDTH, 1);
drawCenteredText("formatieren (FAT32)!", 0, 85, SCREEN_WIDTH, 1);
tft.setTextSize(2);
tft.setTextColor(WHITE);
} else {
for (int i = 0; i < numImages; i++) {
int y_pos = 40 + i * 30;
String displayName = imageFiles[i].substring(1);
drawCenteredText(displayName, 0, y_pos, SCREEN_WIDTH, 1);
if (i < numImages - 1) {
tft.drawLine(0, y_pos + 20, SCREEN_WIDTH, y_pos + 20, LIGHT_GREY);
}
}
}
draw3DButton(0, SCREEN_HEIGHT - 40, SCREEN_WIDTH, 40, ORANGE_TOP, ORANGE_BOT, "Back", 2);
}
void drawSelectedImage(int index) {
tft.fillScreen(BLACK);
uint16_t w = 0, h = 0;
if (!TJpgDec.getSdJpgSize(&w, &h, imageFiles[index].c_str())) {
Serial.printf("Fehler: Ungültiges JPG %s\n", imageFiles[index].c_str());
tft.setTextColor(RED);
drawCenteredText("Ungültiges JPG!", 0, 100, SCREEN_WIDTH, 2);
draw3DButton(0, SCREEN_HEIGHT - 40, SCREEN_WIDTH, 40, ORANGE_TOP, ORANGE_BOT, "Back", 2);
return;
}
Serial.printf("Bild %s: %d x %d\n", imageFiles[index].c_str(), w, h);
int x = max(0, (SCREEN_WIDTH - w) / 2);
int y = max(0, (SCREEN_HEIGHT - h) / 2);
uint32_t t = millis();
if (!TJpgDec.drawSdJpg(x, y, imageFiles[index].c_str())) {
Serial.printf("Render-Fehler für %s\n", imageFiles[index].c_str());
tft.setTextColor(RED);
drawCenteredText("Render-Fehler!", 0, 150, SCREEN_WIDTH, 2);
} else {
t = millis() - t;
Serial.printf("Render-Zeit: %d ms\n", t);
delay(5); // SPI-Konflikt vermeiden
}
draw3DButton(0, SCREEN_HEIGHT - 40, SCREEN_WIDTH, 40, ORANGE_TOP, ORANGE_BOT, "Back", 2);
}
void drawWiFiList() {
currentState = WIFI_LIST;
tft.fillScreen(BLACK); // Einheitlicher schwarzer Hintergrund
drawRoundedFrame(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, WHITE, LIGHT_GREY, DARK_GREY);
tft.setTextColor(WHITE);
tft.setTextSize(2);
drawCenteredText("WIFI Networks", 0, 10, SCREEN_WIDTH, 2);
WiFi.mode(WIFI_STA);
numNetworks = WiFi.scanNetworks();
if (numNetworks == 0) {
drawCenteredText("No networks found", 0, 50, SCREEN_WIDTH, 2);
} else {
numNetworks = min(numNetworks, 10);
for (int i = 0; i < numNetworks; i++) {
networks[i] = WiFi.SSID(i);
int y_pos = 40 + i * 30;
tft.setTextColor(WHITE);
drawCenteredText(networks[i], 0, y_pos, SCREEN_WIDTH, 2);
if (i < numNetworks - 1) {
tft.drawLine(0, y_pos + 24, SCREEN_WIDTH, y_pos + 24, LIGHT_GREY);
}
}
}
draw3DButton(0, SCREEN_HEIGHT - 40, SCREEN_WIDTH, 40, ORANGE_TOP, ORANGE_BOT, "Back", 2);
}
void drawKeyboard() {
currentState = KEYBOARD;
tft.fillScreen(BLACK); // Einheitlicher schwarzer Hintergrund
drawRoundedFrame(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, WHITE, LIGHT_GREY, DARK_GREY);
tft.setTextColor(WHITE);
tft.setTextSize(2);
drawCenteredText("Enter Password for " + networks[selectedNetwork], 0, 10, SCREEN_WIDTH, 2);
tft.fillRoundRect(MARGIN, 50, SCREEN_WIDTH - 2*MARGIN, 40, ROUND_RADIUS, LIGHT_GREY);
tft.setTextColor(BLACK);
drawCenteredText(inputPassword, MARGIN, 55, SCREEN_WIDTH - 2*MARGIN, 2);
int kb_total_width = 11 * KB_KEY_WIDTH;
int kb_start_x = (SCREEN_WIDTH - kb_total_width) / 2;
for (int row = 0; row < 4; row++) {
for (int col = 0; col < 11; col++) {
if (keyboardLayout[row][col] == ' ') continue;
int x = kb_start_x + col * KB_KEY_WIDTH;
int y = KB_START_Y + row * KB_KEY_HEIGHT;
draw3DButton(x, y, KB_KEY_WIDTH, KB_KEY_HEIGHT, WHITE, LIGHT_GREY, String(keyboardLayout[row][col]), 1, true);
}
}
draw3DButton(0, SCREEN_HEIGHT - 40, SCREEN_WIDTH / 2, 40, ORANGE_TOP, ORANGE_BOT, "Back", 2);
draw3DButton(SCREEN_WIDTH / 2, SCREEN_HEIGHT - 40, SCREEN_WIDTH / 2, 40, ORANGE_TOP, ORANGE_BOT, "Connect", 2);
}
void drawInfo() {
currentState = INFO;
tft.fillScreen(BLACK); // Einheitlicher schwarzer Hintergrund
drawRoundedFrame(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, WHITE, LIGHT_GREY, DARK_GREY);
tft.setTextColor(WHITE);
tft.setTextSize(2);
drawCenteredText("System Info", 0, 10, SCREEN_WIDTH, 2);
drawRoundedBox(MARGIN, 40, SCREEN_WIDTH - 2*MARGIN, 200, LIGHT_GREY, LIGHT_GREY, DARK_GREY);
tft.setTextColor(BLACK);
tft.setTextSize(2);
String connectedSSID = (WiFi.status() == WL_CONNECTED) ? WiFi.SSID() : "Nicht verbunden";
String ipAddr = (WiFi.status() == WL_CONNECTED) ? WiFi.localIP().toString() : "N/A";
String datetime = getDateTime();
String date = datetime.substring(0, 10); // z.B. "2025-09-14"
String time = datetime.substring(11); // z.B. "20:58:00"
// Mehrfaches Zeichnen für "fett" Effekt
drawCenteredText(connectedSSID, MARGIN, 50, SCREEN_WIDTH - 2*MARGIN, 2);
drawCenteredText(connectedSSID, MARGIN + 1, 50, SCREEN_WIDTH - 2*MARGIN, 2);
drawCenteredText(ipAddr, MARGIN, 80, SCREEN_WIDTH - 2*MARGIN, 2);
drawCenteredText(ipAddr, MARGIN + 1, 80, SCREEN_WIDTH - 2*MARGIN, 2);
drawCenteredText(date, MARGIN, 110, SCREEN_WIDTH - 2*MARGIN, 2);
drawCenteredText(date, MARGIN + 1, 110, SCREEN_WIDTH - 2*MARGIN, 2);
drawCenteredText(time, MARGIN, 140, SCREEN_WIDTH - 2*MARGIN, 2);
drawCenteredText(time, MARGIN + 1, 140, SCREEN_WIDTH - 2*MARGIN, 2);
drawCenteredText("Copyright", MARGIN, 170, SCREEN_WIDTH - 2*MARGIN, 2);
drawCenteredText("Copyright", MARGIN + 1, 170, SCREEN_WIDTH - 2*MARGIN, 2);
drawCenteredText("HD Robotics Elc.", MARGIN, 200, SCREEN_WIDTH - 2*MARGIN, 2);
drawCenteredText("HD Robotics Elc.", MARGIN + 1, 200, SCREEN_WIDTH - 2*MARGIN, 2);
drawCenteredText("www.hdrobotics.de", MARGIN, 230, SCREEN_WIDTH - 2*MARGIN, 2);
drawCenteredText("www.hdrobotics.de", MARGIN + 1, 230, SCREEN_WIDTH - 2*MARGIN, 2);
draw3DButton(0, SCREEN_HEIGHT - 40, SCREEN_WIDTH, 40, ORANGE_TOP, ORANGE_BOT, "Back", 2);
}
void drawLEDSettings() {
currentState = LED_SETTINGS;
tft.fillScreen(BLACK); // Einheitlicher schwarzer Hintergrund
drawRoundedFrame(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, WHITE, LIGHT_GREY, DARK_GREY);
tft.setTextColor(WHITE);
tft.setTextSize(2);
drawCenteredText("LED Settings", 0, 10, SCREEN_WIDTH, 2);
int buttonWidth = 70;
int buttonHeight = 40;
int buttonSpacing = 10;
int startX = (SCREEN_WIDTH - (2 * buttonWidth + buttonSpacing)) / 2;
int startY = 50;
toggleLEDRBox = {startX, startY, buttonWidth, buttonHeight, enableLEDR ? "ROT Aus" : "ROT Ein", nullptr, enableLEDR ? RED_TOP : DARK_GREY, enableLEDR ? RED_BOT : DARK_GREY};
draw3DButton(toggleLEDRBox.x, toggleLEDRBox.y, toggleLEDRBox.w, toggleLEDRBox.h, toggleLEDRBox.topColor, toggleLEDRBox.botColor, toggleLEDRBox.label, 2);
toggleLEDGBox = {startX + buttonWidth + buttonSpacing, startY, buttonWidth, buttonHeight, enableLEDG ? "Grün Aus" : "Grün Ein", nullptr, enableLEDG ? GREEN_TOP : DARK_GREY, enableLEDG ? GREEN_BOT : DARK_GREY};
draw3DButton(toggleLEDGBox.x, toggleLEDGBox.y, toggleLEDGBox.w, toggleLEDGBox.h, toggleLEDGBox.topColor, toggleLEDGBox.botColor, toggleLEDGBox.label, 2);
toggleLEDBBox = {startX, startY + buttonHeight + buttonSpacing, buttonWidth, buttonHeight, enableLEDB ? "Blau Aus" : "Blau Ein", nullptr, enableLEDB ? BLUE_TOP : DARK_GREY, enableLEDB ? BLUE_BOT : DARK_GREY};
draw3DButton(toggleLEDBBox.x, toggleLEDBBox.y, toggleLEDBBox.w, toggleLEDBBox.h, toggleLEDBBox.topColor, toggleLEDBBox.botColor, toggleLEDBBox.label, 2);
brightnessBox = {startX + buttonWidth + buttonSpacing, startY + buttonHeight + buttonSpacing, buttonWidth, buttonHeight, highBrightness ? "Low Bright" : "High Bright", nullptr, highBrightness ? PURPLE_TOP : DARK_GREY, highBrightness ? PURPLE_BOT : DARK_GREY};
draw3DButton(brightnessBox.x, brightnessBox.y, brightnessBox.w, brightnessBox.h, brightnessBox.topColor, brightnessBox.botColor, brightnessBox.label, 2);
blinkBox = {startX, startY + 2*(buttonHeight + buttonSpacing), buttonWidth*2 + buttonSpacing, buttonHeight, blinkingEnabled ? "Blink Aus" : "Blink Ein", nullptr, blinkingEnabled ? PURPLE_TOP : DARK_GREY, blinkingEnabled ? PURPLE_BOT : DARK_GREY};
draw3DButton(blinkBox.x, blinkBox.y, blinkBox.w, blinkBox.h, blinkBox.topColor, blinkBox.botColor, blinkBox.label, 2);
drawRoundedBox(MARGIN, startY + 3*(buttonHeight + buttonSpacing), SCREEN_WIDTH - 2*MARGIN, 60, LIGHT_GREY, LIGHT_GREY, DARK_GREY);
tft.setTextColor(BLACK);
tft.setTextSize(1);
tft.drawString("ROT: " + String(enableLEDR ? "Ein" : "Aus"), MARGIN + 8, startY + 3*(buttonHeight + buttonSpacing) + 10);
tft.drawString("Grün: " + String(enableLEDG ? "Ein" : "Aus"), MARGIN + 8, startY + 3*(buttonHeight + buttonSpacing) + 25);
tft.drawString("Blau: " + String(enableLEDB ? "Ein" : "Aus"), MARGIN + 8, startY + 3*(buttonHeight + buttonSpacing) + 40);
tft.drawString("Helligkeit: " + String(highBrightness ? "Hoch" : "Niedrig"), MARGIN + 98, startY + 3*(buttonHeight + buttonSpacing) + 10);
tft.drawString("Blinken: " + String(blinkingEnabled ? "Ein" : "Aus"), MARGIN + 98, startY + 3*(buttonHeight + buttonSpacing) + 25);
tft.drawString("Modus: " + String(blinkingEnabled ? "Blink" : "Konstant"), MARGIN + 98, startY + 3*(buttonHeight + buttonSpacing) + 40);
draw3DButton(0, SCREEN_HEIGHT - 40, SCREEN_WIDTH, 40, ORANGE_TOP, ORANGE_BOT, "Back", 2);
}
void handleTouch(int x, int y) {
switch (currentState) {
case MAIN_MENU:
for (int i = 0; i < 6; i++) {
if (x >= boxes[i].x && x < boxes[i].x + boxes[i].w &&
y >= boxes[i].y && y < boxes[i].y + boxes[i].h) {
if (boxes[i].action != nullptr) boxes[i].action();
return;
}
}
if (x >= settingsBox.x && x < settingsBox.x + settingsBox.w &&
y >= settingsBox.y && y < settingsBox.y + settingsBox.h) {
if (settingsBox.action != nullptr) settingsBox.action();
return;
}
break;
case SETTINGS:
if (x >= wifiBox.x && x < wifiBox.x + wifiBox.w &&
y >= wifiBox.y && y < wifiBox.y + wifiBox.h) {
wifiAction();
return;
}
if (x >= infoBox.x && x < infoBox.x + infoBox.w &&
y >= infoBox.y && y < infoBox.y + infoBox.h) {
infoAction();
return;
}
if (x >= ledBox.x && x < ledBox.x + ledBox.w &&
y >= ledBox.y && y < ledBox.y + ledBox.h) {
ledSettingsAction();
return;
}
if (x >= imageBox.x && x < imageBox.x + imageBox.w &&
y >= imageBox.y && y < imageBox.y + imageBox.h) {
imageViewerAction();
return;
}
if (y >= SCREEN_HEIGHT - 40 && y < SCREEN_HEIGHT) {
drawMainMenu();
}
break;
case IMAGE_VIEWER:
if (selectedImage == -1) {
for (int i = 0; i < numImages; i++) {
if (y >= 40 + i * 30 && y < 40 + (i + 1) * 30) {
selectedImage = i;
drawSelectedImage(i);
return;
}
}
if (y >= SCREEN_HEIGHT - 40 && y < SCREEN_HEIGHT) {
drawSettings();
}
} else {
if (y >= SCREEN_HEIGHT - 40 && y < SCREEN_HEIGHT) {
selectedImage = -1;
drawImageList();
}
}
break;
case WIFI_LIST:
for (int i = 0; i < numNetworks; i++) {
if (y >= 40 + i * 30 && y < 40 + (i + 1) * 30) {
selectedNetwork = i;
inputPassword = "";
drawKeyboard();
return;
}
}
if (y >= SCREEN_HEIGHT - 40 && y < SCREEN_HEIGHT) {
drawSettings();
}
break;
case KEYBOARD:
for (int row = 0; row < 4; row++) {
for (int col = 0; col < 11; col++) {
char key = keyboardLayout[row][col];
if (key == ' ') continue;
int kb_total_width = 11 * KB_KEY_WIDTH;
int kb_start_x = (SCREEN_WIDTH - kb_total_width) / 2;
int kx = kb_start_x + col * KB_KEY_WIDTH;
int ky = KB_START_Y + row * KB_KEY_HEIGHT;
if (x >= kx && x < kx + KB_KEY_WIDTH && y >= ky && y < ky + KB_KEY_HEIGHT) {
if (key == '<') {
if (inputPassword.length() > 0) inputPassword = inputPassword.substring(0, inputPassword.length() - 1);
} else {
inputPassword += key; // 'E' ist jetzt normaler Key
}
tft.fillRoundRect(MARGIN, 50, SCREEN_WIDTH - 2*MARGIN, 40, ROUND_RADIUS, LIGHT_GREY);
tft.setTextColor(BLACK);
tft.setTextSize(2);
drawCenteredText(inputPassword, MARGIN, 55, SCREEN_WIDTH - 2*MARGIN, 2);
return;
}
}
}
if (y >= SCREEN_HEIGHT - 40 && y < SCREEN_HEIGHT && x < SCREEN_WIDTH / 2) {
drawWiFiList();
}
if (y >= SCREEN_HEIGHT - 40 && y < SCREEN_HEIGHT && x >= SCREEN_WIDTH / 2) {
connectToWiFi(networks[selectedNetwork], inputPassword);
drawSettings();
}
break;
case INFO:
if (y >= SCREEN_HEIGHT - 40 && y < SCREEN_HEIGHT) {
drawSettings();
}
break;
case LED_SETTINGS:
if (x >= toggleLEDRBox.x && x < toggleLEDRBox.x + toggleLEDRBox.w &&
y >= toggleLEDRBox.y && y < toggleLEDRBox.y + toggleLEDRBox.h) {
enableLEDR = !enableLEDR;
drawLEDSettings();
return;
}
if (x >= toggleLEDGBox.x && x < toggleLEDGBox.x + toggleLEDGBox.w &&
y >= toggleLEDGBox.y && y < toggleLEDGBox.y + toggleLEDGBox.h) {
enableLEDG = !enableLEDG;
drawLEDSettings();
return;
}
if (x >= toggleLEDBBox.x && x < toggleLEDBBox.x + toggleLEDBBox.w &&
y >= toggleLEDBBox.y && y < toggleLEDBBox.y + toggleLEDBBox.h) {
enableLEDB = !enableLEDB;
drawLEDSettings();
return;
}
if (x >= brightnessBox.x && x < brightnessBox.x + brightnessBox.w &&
y >= brightnessBox.y && y < brightnessBox.y + brightnessBox.h) {
highBrightness = !highBrightness;
drawLEDSettings();
return;
}
if (x >= blinkBox.x && x < blinkBox.x + blinkBox.w &&
y >= blinkBox.y && y < blinkBox.y + blinkBox.h) {
blinkingEnabled = !blinkingEnabled;
drawLEDSettings();
return;
}
if (y >= SCREEN_HEIGHT - 40 && y < SCREEN_HEIGHT) {
drawSettings();
}
break;
}
}
void settingsAction() {
drawSettings();
}
void wifiAction() {
drawWiFiList();
}
void infoAction() {
drawInfo();
}
void ledSettingsAction() {
drawLEDSettings();
}
void imageViewerAction() {
selectedImage = -1;
drawImageList();
}
void connectToWiFi(String ssid, String password) {
Serial.printf("Connecting to %s...\n", ssid.c_str());
WiFi.begin(ssid.c_str(), password.c_str());
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 10) {
delay(500);
Serial.print(".");
attempts++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("\nConnected!");
configTime(0, 0, "pool.ntp.org");
prefs.begin("wifi", false);
prefs.putString("ssid", ssid);
prefs.putString("password", password);
prefs.end();
savedSSID = ssid;
savedPassword = password;
} else {
Serial.println("\nConnection failed.");
tft.setTextColor(RED);
drawCenteredText("Connection Failed", 0, 100, SCREEN_WIDTH, 2);
delay(2000);
}
}
String getDateTime() {
time_t now = time(nullptr);
if (now < 100000) return "N/A";
struct tm * timeinfo = localtime(&now);
char buffer[20];
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo);
return String(buffer);
}
void drawCenteredText(String text, int x, int y, int w, uint8_t textSize) {
tft.setTextSize(textSize);
int charWidth = (textSize == 1) ? 6 : (textSize == 2) ? 12 : 18;
int estWidth = text.length() * charWidth;
if (estWidth > w) {
text = text.substring(0, w / charWidth);
estWidth = w;
}
int textX = x + (w - estWidth) / 2;
tft.drawString(text, textX, y);
}
void drawRoundedBox(int x, int y, int w, int h, uint16_t color, uint16_t light, uint16_t dark) {
tft.fillRoundRect(x, y, w, h, ROUND_RADIUS, color);
tft.drawRoundRect(x, y, w, h, ROUND_RADIUS, WHITE);
tft.drawRoundRect(x, y, w-1, h-1, ROUND_RADIUS, light);
tft.drawRoundRect(x+1, y+1, w, h, ROUND_RADIUS, dark);
}
void drawRoundedFrame(int x, int y, int w, int h, uint16_t color, uint16_t light, uint16_t dark) {
tft.drawRoundRect(x, y, w, h, ROUND_RADIUS, color);
tft.drawRoundRect(x + 1, y + 1, w - 2, h - 2, ROUND_RADIUS, light);
tft.drawRoundRect(x + 2, y + 2, w - 4, h - 4, ROUND_RADIUS, dark);
}
// Relais-Toggle-Funktionen
void toggleRelay1() {
toggleRelay(0); // Relais 1 (Index 0)
}
void toggleRelay2() {
toggleRelay(1); // Relais 2 (Index 1)
}
void toggleRelay3() {
toggleRelay(2); // Relais 3 (Index 2)
}
void toggleRelay4() {
toggleRelay(3); // Relais 4 (Index 3)
}
void toggleRelay(int relayNum) {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Kein WiFi – Relais kann nicht geschaltet werden.");
tft.setTextColor(RED);
drawCenteredText("Kein WiFi!", 0, 100, SCREEN_WIDTH, 2);
delay(1000);
drawMainMenu();
return;
}
HTTPClient http;
String url = "http://" + String(relayIP) + "/toggle?r=" + String(relayNum);
http.begin(url);
http.setAuthorization(relayUsername, relayPassword);
int httpCode = http.GET();
if (httpCode == 200) {
String payload = http.getString();
DynamicJsonDocument doc(256);
DeserializationError error = deserializeJson(doc, payload);
if (!error && doc.containsKey("status")) {
relayState[relayNum] = doc["status"].as<bool>();
Serial.println("Relais " + String(relayNum + 1) + " geschaltet: " + (relayState[relayNum] ? "EIN" : "AUS"));
boxes[relayNum].label = "Relais " + String(relayNum + 1) + ": " + (relayState[relayNum] ? "EIN" : "AUS");
updateSingleButton(relayNum); // Nur diesen Button neu zeichnen
} else {
Serial.println("Fehler beim Parsen der Antwort");
tft.setTextColor(RED);
drawCenteredText("Antwortfehler!", 0, 100, SCREEN_WIDTH, 2);
delay(1000);
drawMainMenu();
}
} else {
Serial.println("Fehler beim Schalten: HTTP-Code " + String(httpCode));
tft.setTextColor(RED);
drawCenteredText("Verbindungsfehler!", 0, 100, SCREEN_WIDTH, 2);
delay(1000);
drawMainMenu();
}
http.end();
}
// Toggle für alle Relais (Button 5)
void toggleAllRelais() {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Kein WiFi – Relais kann nicht geschaltet werden.");
tft.setTextColor(RED);
drawCenteredText("Kein WiFi!", 0, 100, SCREEN_WIDTH, 2);
delay(1000);
drawMainMenu();
return;
}
allRelaisState = !allRelaisState;
int state = allRelaisState ? 1 : 0;
HTTPClient http;
String url = "http://" + String(relayIP) + "/allonoff?state=" + String(state);
http.begin(url);
http.setAuthorization(relayUsername, relayPassword);
int httpCode = http.GET();
if (httpCode == 200) {
String payload = http.getString();
DynamicJsonDocument doc(512);
DeserializationError error = deserializeJson(doc, payload);
if (!error && doc.containsKey("status")) {
for (int i = 0; i < 4; i++) {
relayState[i] = doc["status"][i].as<bool>();
boxes[i].label = "Relais " + String(i + 1) + ": " + (relayState[i] ? "EIN" : "AUS");
updateSingleButton(i); // Jeden Relais-Button aktualisieren
}
boxes[4].label = String("Alle Relais: ") + (allRelaisState ? String("EIN") : String("AUS"));
updateSingleButton(4); // Button 5 aktualisieren
Serial.println("Alle Relais geschaltet: " + String(allRelaisState ? "EIN" : "AUS"));
} else {
Serial.println("Fehler beim Parsen der Antwort");
}
} else {
Serial.println("Fehler beim Schalten aller Relais: HTTP-Code " + String(httpCode));
tft.setTextColor(RED);
drawCenteredText("Verbindungsfehler!", 0, 100, SCREEN_WIDTH, 2);
delay(1000);
drawMainMenu();
}
http.end();
}
// Lauflicht aktivieren (Button 6)
void toggleRunningLight() {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Kein WiFi – Lauflicht kann nicht aktiviert werden.");
tft.setTextColor(RED);
drawCenteredText("Kein WiFi!", 0, 100, SCREEN_WIDTH, 2);
delay(1000);
drawMainMenu();
return;
}
HTTPClient http;
String url = "http://" + String(relayIP) + "/runninglight";
http.begin(url);
http.setAuthorization(relayUsername, relayPassword);
int httpCode = http.GET();
if (httpCode == 200) {
Serial.println("Lauflicht aktiviert");
tft.setTextColor(GREEN);
drawCenteredText("Lauflicht aktiviert!", 0, 100, SCREEN_WIDTH, 2);
delay(1000);
drawMainMenu();
} else {
Serial.println("Fehler beim Aktivieren des Lauflichts: HTTP-Code " + String(httpCode));
tft.setTextColor(RED);
drawCenteredText("Verbindungsfehler!", 0, 100, SCREEN_WIDTH, 2);
delay(1000);
drawMainMenu();
}
http.end();
}
// Relais-Status aktualisieren
void updateRelayStatus() {
if (WiFi.status() != WL_CONNECTED) return;
HTTPClient http;
String url = "http://" + String(relayIP) + "/status";
http.begin(url);
http.setAuthorization(relayUsername, relayPassword);
int httpCode = http.GET();
if (httpCode == 200) {
String payload = http.getString();
DynamicJsonDocument doc(256);
DeserializationError error = deserializeJson(doc, payload);
if (!error && doc.containsKey("status")) {
bool allOn = true;
for (int i = 0; i < 4; i++) {
bool newState = doc["status"][i].as<bool>();
if (newState != relayState[i]) { // Nur bei Änderung aktualisieren
relayState[i] = newState;
boxes[i].label = "Relais " + String(i + 1) + ": " + (relayState[i] ? "EIN" : "AUS");
if (currentState == MAIN_MENU) {
updateSingleButton(i); // Nur diesen Button neu zeichnen
}
}
if (!relayState[i]) allOn = false;
}
if (allOn != allRelaisState) { // Nur bei Änderung aktualisieren
allRelaisState = allOn;
boxes[4].label = String("Alle Relais: ") + (allRelaisState ? String("EIN") : String("AUS"));
if (currentState == MAIN_MENU) {
updateSingleButton(4); // Button 5 neu zeichnen
}
}
}
}
http.end();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment