Last active
October 1, 2025 07:00
-
-
Save HDRobotica/10e78480a8430d65e8ae2943c776b286 to your computer and use it in GitHub Desktop.
π ESP32 Touchscreen Relaissteuerung | 6-Kanal Smart Home Projekt mit TFT-Display
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <WebServer.h> | |
| #include <TFT_eSPI.h> | |
| #include <XPT2046_Touchscreen.h> | |
| #include <SPI.h> | |
| #include <WiFi.h> | |
| #include <Preferences.h> | |
| #include <time.h> | |
| #include <ESP.h> | |
| #define SCREEN_WIDTH 320 | |
| #define SCREEN_HEIGHT 240 | |
| #define TOUCH_OFFSET_X 0 | |
| #define TOUCH_CS 21 | |
| #define TOUCH_IRQ 255 | |
| #define DEBOUNCE_DELAY 300 | |
| enum RelayIndex { RELAY_1, RELAY_2, RELAY_3, RELAY_4, RELAY_5, RELAY_6, RELAY_COUNT }; | |
| const int RELAY_PINS[RELAY_COUNT] = {25, 26, 27, 33, 14, 12}; | |
| TFT_eSPI tft = TFT_eSPI(); | |
| XPT2046_Touchscreen ts(TOUCH_CS, TOUCH_IRQ); | |
| uint16_t touchScreenMinimumX = 141, touchScreenMaximumX = 3671; | |
| uint16_t touchScreenMinimumY = 247, touchScreenMaximumY = 3765; | |
| enum MenuState { MAIN_MENU, SETTINGS_MENU, WIFI_MENU, PASSWORD_MENU, CALIBRATION_MENU, INFOS_MENU }; | |
| MenuState currentMenu = MAIN_MENU; | |
| // WiFi-Variablen | |
| String selectedSSID = ""; | |
| String password = ""; | |
| int wifiNetworksFound = 0; | |
| String wifiSSIDs[20]; | |
| int wifiScrollOffset = 0; | |
| const int visibleWifiCount = 5; | |
| // Scrollbar Parameter | |
| const int scrollbarX = 290; | |
| const int scrollbarY = 50; | |
| const int scrollbarHeight = 150; | |
| const int scrollbarWidth = 20; | |
| // Settings Scroll Parameter | |
| const int settingsListY = 50; | |
| const int settingsListHeight = 150; | |
| const int settingsItemHeight = 35; | |
| const int visibleSettingsCount = settingsListHeight / settingsItemHeight; | |
| int settingsScrollOffset = 0; | |
| // Virtuelles Keyboard | |
| const String keyboardRows[5] = { | |
| "1234567890", | |
| "QWERTYUIOP", | |
| "ASDFGHJKL<", | |
| "ZXCVBNM", | |
| "" | |
| }; | |
| const int keyWidth = 28; | |
| const int keyHeight = 35; | |
| const int keyStartX = 10; | |
| const int keyStartY = 60; | |
| const int keyboardRowsCount = 4; | |
| // Kalibrierungs-Variablen | |
| struct CalibrationPoint { | |
| uint16_t rawX, rawY; | |
| uint16_t screenX, screenY; | |
| }; | |
| CalibrationPoint calPoints[5]; | |
| int calPointIndex = 0; | |
| // Preferences | |
| Preferences prefs; | |
| // WebServer | |
| WebServer server(80); | |
| // Zeitvariablen | |
| bool timeConfigured = false; | |
| unsigned long lastUpdate = 0; | |
| unsigned long lastTimeSyncAttempt = 0; | |
| const unsigned long timeSyncInterval = 5000; // Try syncing every 5 seconds if not configured | |
| // VorwΓ€rtsdeklarationen | |
| void drawMainMenu(); | |
| void drawSettingsMenu(); | |
| void drawWifiMenu(); | |
| void drawPasswordMenu(); | |
| void drawCalibrationMenu(); | |
| void drawInfosMenu(); | |
| void updateInfos(); | |
| void scanWifiNetworks(); | |
| void calibrateTouch(); | |
| void syncTime(); | |
| String getMainPage(); | |
| void handleToggle(); | |
| void handleAllRelays(); | |
| void handleWifiConfig(); | |
| void handleReset(); | |
| // Button-Klasse | |
| class Button { | |
| public: | |
| Button(int x, int y, int w, int h, String label, uint16_t color, void (*action)() = nullptr) | |
| : x_(x), y_(y), w_(w), h_(h), label_(label), color_(color), action_(action), state_(false) {} | |
| virtual void draw() { | |
| tft.fillRoundRect(x_, y_, w_, h_, 8, state_ ? TFT_WHITE : color_); | |
| tft.drawRoundRect(x_, y_, w_, h_, 8, TFT_WHITE); | |
| tft.setTextColor(state_ ? TFT_BLACK : TFT_WHITE, state_ ? TFT_WHITE : color_); | |
| tft.setTextDatum(MC_DATUM); | |
| tft.drawString(label_, x_ + w_ / 2, y_ + h_ / 2, 2); | |
| } | |
| bool isTouched(uint16_t x, uint16_t y) { | |
| return (x >= x_ && x <= x_ + w_ && y >= y_ && y <= y_ + h_); | |
| } | |
| virtual void trigger() { | |
| if (action_) action_(); | |
| } | |
| bool getState() { return state_; } | |
| void setState(bool state) { state_ = state; } | |
| void setY(int y) { y_ = y; } | |
| protected: | |
| int x_, y_, w_, h_; | |
| String label_; | |
| uint16_t color_; | |
| void (*action_)(); | |
| bool state_; | |
| }; | |
| class RelayButton : public Button { | |
| public: | |
| RelayButton(int x, int y, int w, int h, String label, uint16_t color, int relayPin) | |
| : Button(x, y, w, h, label, color), relayPin_(relayPin) {} | |
| void draw() override { | |
| tft.fillRoundRect(x_, y_, w_, h_, 8, state_ ? TFT_LIGHTGREY : color_); | |
| tft.drawRoundRect(x_, y_, w_, h_, 8, TFT_WHITE); | |
| tft.setTextColor(state_ ? TFT_BLACK : TFT_WHITE, state_ ? TFT_LIGHTGREY : color_); | |
| tft.setTextDatum(MC_DATUM); | |
| tft.drawString(label_, x_ + w_ / 2, y_ + h_ / 2, 2); | |
| } | |
| void trigger() override { | |
| state_ = !state_; | |
| digitalWrite(relayPin_, state_ ? HIGH : LOW); | |
| draw(); | |
| } | |
| private: | |
| int relayPin_; | |
| }; | |
| // Relais-Buttons | |
| RelayButton relays[RELAY_COUNT] = { | |
| RelayButton(20, 50, 85, 45, "Relay 1", TFT_BLUE, RELAY_PINS[RELAY_1]), | |
| RelayButton(115, 50, 85, 45, "Relay 2", TFT_DARKCYAN, RELAY_PINS[RELAY_2]), | |
| RelayButton(210, 50, 85, 45, "Relay 3", TFT_RED, RELAY_PINS[RELAY_3]), | |
| RelayButton(20, 105, 85, 45, "Relay 4", TFT_ORANGE, RELAY_PINS[RELAY_4]), | |
| RelayButton(115, 105, 85, 45, "Relay 5", TFT_PURPLE, RELAY_PINS[RELAY_5]), | |
| RelayButton(210, 105, 85, 45, "Relay 6", TFT_MAGENTA, RELAY_PINS[RELAY_6]) | |
| }; | |
| // HauptmenΓΌ Buttons | |
| Button allRelaysButton(20, 160, 130, 45, "All Relays", TFT_BLUE, []() { | |
| bool allOn = true; | |
| for (int i = 0; i < RELAY_COUNT; i++) { | |
| if (!relays[i].getState()) { | |
| allOn = false; | |
| break; | |
| } | |
| } | |
| bool newState = !allOn; | |
| for (int i = 0; i < RELAY_COUNT; i++) { | |
| relays[i].setState(newState); | |
| digitalWrite(RELAY_PINS[i], newState ? HIGH : LOW); | |
| relays[i].draw(); // Only redraw the relay buttons | |
| } | |
| delay(50); // Small delay to stabilize rendering | |
| }); | |
| Button settingsButton(160, 160, 130, 45, "Settings", TFT_ORANGE, []() { | |
| currentMenu = SETTINGS_MENU; | |
| settingsScrollOffset = 0; | |
| drawSettingsMenu(); | |
| }); | |
| // Settings-MenΓΌ Buttons | |
| Button wifiButton(20, 0, 260, 35, "WiFi Settings", TFT_BLUE, []() { | |
| currentMenu = WIFI_MENU; | |
| scanWifiNetworks(); | |
| drawWifiMenu(); | |
| }); | |
| Button infosButton(20, 0, 260, 35, "Infos", TFT_ORANGE, []() { | |
| currentMenu = INFOS_MENU; | |
| drawInfosMenu(); | |
| }); | |
| Button calibrationButton(20, 0, 260, 35, "Calibration", TFT_PURPLE, []() { | |
| currentMenu = CALIBRATION_MENU; | |
| calPointIndex = 0; | |
| drawCalibrationMenu(); | |
| }); | |
| Button factoryResetButton(20, 0, 260, 35, "Factory Reset", TFT_RED, []() { | |
| prefs.clear(); | |
| WiFi.disconnect(); | |
| ESP.restart(); | |
| }); | |
| Button* settingsButtons[] = {&wifiButton, &infosButton, &calibrationButton, &factoryResetButton}; | |
| int settingsButtonsCount = sizeof(settingsButtons) / sizeof(settingsButtons[0]); | |
| Button backToMainButton(20, 0, 260, 30, "Back", TFT_RED, []() { | |
| currentMenu = MAIN_MENU; | |
| drawMainMenu(); | |
| }); | |
| // WiFi-MenΓΌ Buttons | |
| Button wifiBackButton(20, 200, 260, 30, "Back", TFT_RED, []() { | |
| currentMenu = SETTINGS_MENU; | |
| drawSettingsMenu(); | |
| }); | |
| // Password-MenΓΌ Buttons | |
| Button connectButton(160, 200, 130, 30, "Connect", TFT_BLUE, []() { | |
| WiFi.disconnect(); | |
| WiFi.begin(selectedSSID.c_str(), password.c_str()); | |
| prefs.putString("ssid", selectedSSID); | |
| prefs.putString("password", password); | |
| password = ""; | |
| currentMenu = WIFI_MENU; | |
| scanWifiNetworks(); | |
| drawWifiMenu(); | |
| }); | |
| Button passwordBackButton(20, 200, 130, 30, "Back", TFT_RED, []() { | |
| password = ""; | |
| currentMenu = WIFI_MENU; | |
| scanWifiNetworks(); | |
| drawWifiMenu(); | |
| }); | |
| // Infos-MenΓΌ Buttons | |
| Button infosBackButton(20, 200, 260, 30, "Back", TFT_RED, []() { | |
| currentMenu = SETTINGS_MENU; | |
| drawSettingsMenu(); | |
| }); | |
| // WiFi scannen | |
| void scanWifiNetworks() { | |
| WiFi.mode(WIFI_STA); | |
| WiFi.disconnect(); | |
| delay(100); | |
| wifiNetworksFound = WiFi.scanNetworks(); | |
| if (wifiNetworksFound == 0) { | |
| delay(500); | |
| wifiNetworksFound = WiFi.scanNetworks(); | |
| } | |
| for (int i = 0; i < wifiNetworksFound && i < 20; ++i) { | |
| wifiSSIDs[i] = WiFi.SSID(i); | |
| } | |
| WiFi.mode(WIFI_AP_STA); | |
| WiFi.softAP("ESP32_Relay_Control", "admin123"); | |
| } | |
| // Zeit synchronisieren | |
| void syncTime() { | |
| if (WiFi.status() == WL_CONNECTED && !timeConfigured) { | |
| configTime(0, 0, "pool.ntp.org"); | |
| setenv("TZ", "CET-1CEST,M3.5.0,M10.5.0/3", 1); | |
| tzset(); | |
| time_t now; | |
| time(&now); | |
| struct tm timeinfo; | |
| localtime_r(&now, &timeinfo); | |
| if (timeinfo.tm_year >= (2020 - 1900)) { | |
| timeConfigured = true; | |
| if (currentMenu == INFOS_MENU) { | |
| updateInfos(); | |
| } | |
| } | |
| } | |
| } | |
| // Kalibrierungsfunktion | |
| void calibrateTouch() { | |
| if (calPointIndex < 5) { | |
| TS_Point p; | |
| while (!ts.touched()) delay(10); | |
| p = ts.getPoint(); | |
| calPoints[calPointIndex].rawX = p.x; | |
| calPoints[calPointIndex].rawY = p.y; | |
| switch (calPointIndex) { | |
| case 0: | |
| calPoints[calPointIndex].screenX = 10; | |
| calPoints[calPointIndex].screenY = 10; | |
| break; | |
| case 1: | |
| calPoints[calPointIndex].screenX = SCREEN_WIDTH - 10; | |
| calPoints[calPointIndex].screenY = 10; | |
| break; | |
| case 2: | |
| calPoints[calPointIndex].screenX = 10; | |
| calPoints[calPointIndex].screenY = SCREEN_HEIGHT - 10; | |
| break; | |
| case 3: | |
| calPoints[calPointIndex].screenX = SCREEN_WIDTH - 10; | |
| calPoints[calPointIndex].screenY = SCREEN_HEIGHT - 10; | |
| break; | |
| case 4: | |
| calPoints[calPointIndex].screenX = SCREEN_WIDTH / 2; | |
| calPoints[calPointIndex].screenY = SCREEN_HEIGHT / 2; | |
| break; | |
| } | |
| calPointIndex++; | |
| drawCalibrationMenu(); | |
| while (ts.touched()) delay(10); | |
| } | |
| if (calPointIndex >= 5) { | |
| touchScreenMinimumX = min(min(min(min(calPoints[0].rawX, calPoints[1].rawX), calPoints[2].rawX), calPoints[3].rawX), calPoints[4].rawX); | |
| touchScreenMaximumX = max(max(max(max(calPoints[0].rawX, calPoints[1].rawX), calPoints[2].rawX), calPoints[3].rawX), calPoints[4].rawX); | |
| touchScreenMinimumY = min(min(min(min(calPoints[0].rawY, calPoints[1].rawY), calPoints[2].rawY), calPoints[3].rawY), calPoints[4].rawY); | |
| touchScreenMaximumY = max(max(max(max(calPoints[0].rawY, calPoints[1].rawY), calPoints[2].rawY), calPoints[3].rawY), calPoints[4].rawY); | |
| currentMenu = SETTINGS_MENU; | |
| drawSettingsMenu(); | |
| } | |
| } | |
| // HauptmenΓΌ zeichnen | |
| void drawMainMenu() { | |
| tft.fillScreen(TFT_BLACK); | |
| tft.setTextColor(TFT_WHITE, TFT_BLACK); | |
| tft.setTextDatum(TC_DATUM); | |
| tft.drawString("HD Robotics", SCREEN_WIDTH / 2, 20, 4); | |
| for (int i = 0; i < RELAY_COUNT; i++) { | |
| relays[i].draw(); | |
| } | |
| allRelaysButton.draw(); | |
| settingsButton.draw(); | |
| } | |
| // Settings-MenΓΌ zeichnen | |
| void drawSettingsMenu() { | |
| tft.fillScreen(TFT_BLACK); | |
| tft.setTextColor(TFT_WHITE, TFT_BLACK); | |
| tft.setTextDatum(TC_DATUM); | |
| tft.drawString("Settings", SCREEN_WIDTH / 2, 20, 4); | |
| for (int i = 0; i < settingsButtonsCount; i++) { | |
| int idx = i + settingsScrollOffset; | |
| if (idx >= settingsButtonsCount) break; | |
| int y = settingsListY + i * settingsItemHeight; | |
| settingsButtons[idx]->setY(y); | |
| settingsButtons[idx]->draw(); | |
| } | |
| if (settingsButtonsCount > visibleSettingsCount) { | |
| tft.fillRect(scrollbarX, settingsListY, scrollbarWidth, settingsListHeight, TFT_DARKGREY); | |
| int thumbHeight = settingsListHeight * visibleSettingsCount / settingsButtonsCount; | |
| int thumbY = settingsListY + (settingsListHeight - thumbHeight) * settingsScrollOffset / (settingsButtonsCount - visibleSettingsCount); | |
| tft.fillRect(scrollbarX, thumbY, scrollbarWidth, thumbHeight, TFT_LIGHTGREY); | |
| } | |
| backToMainButton.setY(SCREEN_HEIGHT - 40); | |
| backToMainButton.draw(); | |
| } | |
| // WiFi-MenΓΌ zeichnen | |
| void drawWifiMenu() { | |
| tft.fillScreen(TFT_BLACK); | |
| tft.setTextColor(TFT_WHITE, TFT_BLACK); | |
| tft.setTextDatum(TC_DATUM); | |
| tft.drawString("WiFi Networks", SCREEN_WIDTH / 2, 20, 4); | |
| for (int i = 0; i < visibleWifiCount; i++) { | |
| int idx = i + wifiScrollOffset; | |
| if (idx >= wifiNetworksFound) break; | |
| int y = 60 + i * 35; | |
| tft.fillRoundRect(10, y, 270, 30, 5, TFT_DARKGREY); | |
| tft.drawRoundRect(10, y, 270, 30, 5, TFT_WHITE); | |
| tft.setTextColor(TFT_WHITE); | |
| tft.setTextDatum(MC_DATUM); | |
| tft.drawString(wifiSSIDs[idx], 140, y + 15, 2); | |
| } | |
| if (wifiNetworksFound > visibleWifiCount) { | |
| tft.fillRect(scrollbarX, scrollbarY, scrollbarWidth, scrollbarHeight, TFT_DARKGREY); | |
| int thumbHeight = scrollbarHeight * visibleWifiCount / wifiNetworksFound; | |
| int thumbY = scrollbarY + (scrollbarHeight - thumbHeight) * wifiScrollOffset / (wifiNetworksFound - visibleWifiCount); | |
| tft.fillRect(scrollbarX, thumbY, scrollbarWidth, thumbHeight, TFT_LIGHTGREY); | |
| } | |
| wifiBackButton.draw(); | |
| } | |
| // Password-MenΓΌ zeichnen | |
| void drawPasswordMenu() { | |
| tft.fillScreen(TFT_BLACK); | |
| tft.setTextColor(TFT_WHITE, TFT_BLACK); | |
| tft.setTextDatum(TC_DATUM); | |
| tft.drawString(password, SCREEN_WIDTH / 2, 30, 2); | |
| for (int row = 0; row < keyboardRowsCount; row++) { | |
| int cols = keyboardRows[row].length(); | |
| for (int col = 0; col < cols; col++) { | |
| int x = keyStartX + col * keyWidth; | |
| int y = keyStartY + row * keyHeight; | |
| tft.fillRect(x, y, keyWidth - 2, keyHeight - 2, TFT_DARKGREY); | |
| tft.drawRect(x, y, keyWidth - 2, keyHeight - 2, TFT_WHITE); | |
| char ch = keyboardRows[row][col]; | |
| if (ch == '<') { | |
| tft.drawString("<-", x + keyWidth / 2 - 10, y + keyHeight / 2 - 5, 2); | |
| } else { | |
| tft.drawChar(ch, x + keyWidth / 2 - 5, y + keyHeight / 2 - 5, 2); | |
| } | |
| } | |
| } | |
| passwordBackButton.draw(); | |
| connectButton.draw(); | |
| } | |
| // KalibrierungsmenΓΌ zeichnen | |
| void drawCalibrationMenu() { | |
| tft.fillScreen(TFT_BLACK); | |
| tft.setTextColor(TFT_WHITE, TFT_BLACK); | |
| tft.setTextDatum(TC_DATUM); | |
| String prompt; | |
| int x_pos, y_pos; | |
| switch (calPointIndex) { | |
| case 0: | |
| prompt = "Touch Top-Left Corner"; | |
| x_pos = 10; | |
| y_pos = 10; | |
| break; | |
| case 1: | |
| prompt = "Touch Top-Right Corner"; | |
| x_pos = SCREEN_WIDTH - 10; | |
| y_pos = 10; | |
| break; | |
| case 2: | |
| prompt = "Touch Bottom-Left Corner"; | |
| x_pos = 10; | |
| y_pos = SCREEN_HEIGHT - 10; | |
| break; | |
| case 3: | |
| prompt = "Touch Bottom-Right Corner"; | |
| x_pos = SCREEN_WIDTH - 10; | |
| y_pos = SCREEN_HEIGHT - 10; | |
| break; | |
| case 4: | |
| prompt = "Touch Center"; | |
| x_pos = SCREEN_WIDTH / 2; | |
| y_pos = SCREEN_HEIGHT / 2; | |
| break; | |
| default: | |
| return; | |
| } | |
| tft.drawString(prompt, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 20, 2); | |
| tft.drawCircle(x_pos, y_pos, 5, TFT_RED); | |
| } | |
| // Infos-MenΓΌ zeichnen | |
| void drawInfosMenu() { | |
| tft.fillScreen(TFT_BLACK); | |
| tft.setTextColor(TFT_WHITE, TFT_BLACK); | |
| tft.setTextDatum(TC_DATUM); | |
| tft.drawString("Infos", SCREEN_WIDTH / 2, 20, 4); | |
| tft.setTextDatum(TL_DATUM); | |
| tft.fillRoundRect(20, 60, 260, 70, 8, TFT_DARKGREY); | |
| tft.drawRoundRect(20, 60, 260, 70, 8, TFT_WHITE); | |
| tft.drawString("Date:", 30, 70, 2); | |
| tft.drawString("Time:", 30, 100, 2); | |
| tft.fillRoundRect(20, 140, 260, 50, 8, TFT_DARKGREY); | |
| tft.drawRoundRect(20, 140, 260, 50, 8, TFT_WHITE); | |
| tft.drawString("AP IP:", 30, 150, 2); | |
| tft.drawString("STA IP:", 30, 170, 2); | |
| infosBackButton.draw(); | |
| updateInfos(); | |
| } | |
| // Infos aktualisieren | |
| void updateInfos() { | |
| tft.setTextColor(TFT_WHITE, TFT_DARKGREY); | |
| tft.setTextDatum(TL_DATUM); | |
| tft.fillRect(100, 65, 160, 60, TFT_DARKGREY); | |
| time_t now; | |
| time(&now); | |
| struct tm timeinfo; | |
| localtime_r(&now, &timeinfo); | |
| if (timeinfo.tm_year < (2020 - 1900)) { | |
| tft.drawString("Not synced", 100, 70, 2); | |
| } else { | |
| char dateBuf[20]; | |
| strftime(dateBuf, sizeof(dateBuf), "%d.%m.%Y", &timeinfo); | |
| tft.drawString(dateBuf, 100, 70, 2); | |
| char timeBuf[20]; | |
| strftime(timeBuf, sizeof(timeBuf), "%H:%M:%S", &timeinfo); | |
| tft.drawString(timeBuf, 100, 100, 2); | |
| } | |
| tft.fillRect(100, 145, 160, 40, TFT_DARKGREY); | |
| tft.drawString("192.168.4.1", 100, 150, 2); | |
| String staIP = (WiFi.status() == WL_CONNECTED) ? WiFi.localIP().toString() : "N/A"; | |
| tft.drawString(staIP, 100, 170, 2); | |
| } | |
| unsigned long lastTouchTime = 0; | |
| void handleTouch() { | |
| if (!ts.touched() || (millis() - lastTouchTime < DEBOUNCE_DELAY)) return; | |
| TS_Point p = ts.getPoint(); | |
| if (p.x < touchScreenMinimumX || p.x > touchScreenMaximumX || | |
| p.y < touchScreenMinimumY || p.y > touchScreenMaximumY) return; | |
| uint16_t x = map(p.x, touchScreenMinimumX, touchScreenMaximumX, 0, SCREEN_WIDTH); | |
| uint16_t y = map(p.y, touchScreenMinimumY, touchScreenMaximumY, SCREEN_HEIGHT, 0); | |
| x += TOUCH_OFFSET_X; | |
| if (x > SCREEN_WIDTH) x = SCREEN_WIDTH; | |
| switch (currentMenu) { | |
| case MAIN_MENU: | |
| for (int i = 0; i < RELAY_COUNT; i++) { | |
| if (relays[i].isTouched(x, y)) { | |
| relays[i].trigger(); | |
| break; | |
| } | |
| } | |
| if (allRelaysButton.isTouched(x, y)) allRelaysButton.trigger(); | |
| if (settingsButton.isTouched(x, y)) settingsButton.trigger(); | |
| break; | |
| case SETTINGS_MENU: | |
| for (int i = 0; i < settingsButtonsCount; i++) { | |
| int idx = i + settingsScrollOffset; | |
| if (idx >= settingsButtonsCount) break; | |
| if (settingsButtons[idx]->isTouched(x, y)) { | |
| settingsButtons[idx]->trigger(); | |
| break; | |
| } | |
| } | |
| if (backToMainButton.isTouched(x, y)) backToMainButton.trigger(); | |
| if (settingsButtonsCount > visibleSettingsCount && x >= scrollbarX && x <= scrollbarX + scrollbarWidth && y >= settingsListY && y <= settingsListY + settingsListHeight) { | |
| int maxOffset = settingsButtonsCount - visibleSettingsCount; | |
| settingsScrollOffset = map(y, settingsListY, settingsListY + settingsListHeight, 0, maxOffset); | |
| settingsScrollOffset = constrain(settingsScrollOffset, 0, maxOffset); | |
| drawSettingsMenu(); | |
| } | |
| break; | |
| case WIFI_MENU: | |
| for (int i = 0; i < visibleWifiCount; i++) { | |
| int idx = i + wifiScrollOffset; | |
| if (idx >= wifiNetworksFound) break; | |
| int wy = 60 + i * 35; | |
| if (x >= 10 && x <= 280 && y >= wy && y <= wy + 30) { | |
| selectedSSID = wifiSSIDs[idx]; | |
| currentMenu = PASSWORD_MENU; | |
| drawPasswordMenu(); | |
| break; | |
| } | |
| } | |
| if (wifiBackButton.isTouched(x, y)) wifiBackButton.trigger(); | |
| if (wifiNetworksFound > visibleWifiCount && x >= scrollbarX && x <= scrollbarX + scrollbarWidth && y >= scrollbarY && y <= scrollbarY + scrollbarHeight) { | |
| int maxOffset = wifiNetworksFound - visibleWifiCount; | |
| wifiScrollOffset = map(y, scrollbarY, scrollbarY + scrollbarHeight, 0, maxOffset); | |
| wifiScrollOffset = constrain(wifiScrollOffset, 0, maxOffset); | |
| drawWifiMenu(); | |
| } | |
| break; | |
| case PASSWORD_MENU: | |
| for (int row = 0; row < keyboardRowsCount; row++) { | |
| int cols = keyboardRows[row].length(); | |
| for (int col = 0; col < cols; col++) { | |
| int kx = keyStartX + col * keyWidth; | |
| int ky = keyStartY + row * keyHeight; | |
| if (x >= kx && x <= kx + keyWidth && y >= ky && y <= ky + keyHeight) { | |
| char ch = keyboardRows[row][col]; | |
| if (ch == '<') { | |
| if (password.length() > 0) password.remove(password.length() - 1); | |
| } else { | |
| password += ch; | |
| } | |
| drawPasswordMenu(); | |
| break; | |
| } | |
| } | |
| } | |
| if (passwordBackButton.isTouched(x, y)) passwordBackButton.trigger(); | |
| if (connectButton.isTouched(x, y)) connectButton.trigger(); | |
| break; | |
| case CALIBRATION_MENU: | |
| calibrateTouch(); | |
| break; | |
| case INFOS_MENU: | |
| if (infosBackButton.isTouched(x, y)) infosBackButton.trigger(); | |
| break; | |
| } | |
| lastTouchTime = millis(); | |
| } | |
| // Webserver Handler | |
| String getMainPage() { | |
| String html = "<!DOCTYPE html><html><head><title>ESP32 Relay Control</title>"; | |
| html += "<meta name='viewport' content='width=device-width, initial-scale=1.0'>"; | |
| html += "<style>"; | |
| html += "body {background-color: #1a1a1a; color: #fff; font-family: Arial, sans-serif; text-align: center; margin: 0; padding: 20px;}"; | |
| html += "h1 {color: #ffa500; font-size: 2em;}"; | |
| html += ".relay-box {background-color: #2c2c2c; border: 1px solid #444; padding: 15px; margin: 10px auto; border-radius: 10px; max-width: 300px;}"; | |
| html += ".button {background: linear-gradient(to bottom, #007bff, #0056b3); color: white; padding: 10px 20px; border: none; border-radius: 5px; margin: 5px; cursor: pointer; font-size: 1em; touch-action: manipulation;}"; | |
| html += ".button:hover {background: linear-gradient(to bottom, #0056b3, #003d80);}"; | |
| html += "</style>"; | |
| html += "<script>"; | |
| html += "function sendRequest(url, callback) {"; | |
| html += " var xhr = new XMLHttpRequest();"; | |
| html += " xhr.onreadystatechange = function() {"; | |
| html += " if (xhr.readyState == 4) {"; | |
| html += " if (xhr.status == 200) { callback(true); }"; | |
| html += " else { console.error('Request failed: ' + url + ', status: ' + xhr.status); callback(false); }"; | |
| html += " }"; | |
| html += " };"; | |
| html += " xhr.open('GET', url, true);"; | |
| html += " xhr.send();"; | |
| html += "}"; | |
| html += "function toggleRelay(id) {"; | |
| html += " sendRequest('/toggle?relay=' + id, function(success) {"; | |
| html += " if (success) {"; | |
| html += " var status = document.getElementById('status' + id);"; | |
| html += " status.innerText = (status.innerText === 'ON' ? 'OFF' : 'ON');"; | |
| html += " }"; | |
| html += " });"; | |
| html += "}"; | |
| html += "function allRelays(state) {"; | |
| html += " sendRequest('/all?state=' + state, function(success) {"; | |
| html += " if (success) {"; | |
| html += " for (var i = 0; i < 6; i++) {"; | |
| html += " document.getElementById('status' + i).innerText = (state === 'on' ? 'ON' : 'OFF');"; | |
| html += " }"; | |
| html += " }"; | |
| html += " });"; | |
| html += "}"; | |
| html += "function factoryReset() {"; | |
| html += " if (confirm('Are you sure you want to perform a factory reset? This will clear all settings.')) {"; | |
| html += " sendRequest('/reset', function(success) {"; | |
| html += " if (success) {"; | |
| html += " setTimeout(function() { window.location.reload(); }, 5000);"; | |
| html += " }"; | |
| html += " });"; | |
| html += " }"; | |
| html += "}"; | |
| html += "</script></head><body>"; | |
| html += "<h1>HD Robotics Relay Control</h1>"; | |
| for (int i = 0; i < RELAY_COUNT; i++) { | |
| bool isOn = relays[i].getState(); | |
| html += "<div class='relay-box'>Relay " + String(i + 1) + ": <span id='status" + String(i) + "'>" + (isOn ? "ON" : "OFF") + "</span><br>"; | |
| html += "<button class='button' onclick='toggleRelay(" + String(i) + ")'>Toggle</button></div>"; | |
| } | |
| html += "<div><button class='button' onclick=\"allRelays('on')\">All On</button>"; | |
| html += "<button class='button' onclick=\"allRelays('off')\">All Off</button>"; | |
| html += "<button class='button' onclick=\"factoryReset()\">Factory Reset</button></div>"; | |
| html += "<h2>WiFi Status</h2>"; | |
| html += "<p>Connected: " + String(WiFi.status() == WL_CONNECTED ? "Yes (" + WiFi.SSID() + ")" : "No") + "</p>"; | |
| html += "<h2>WiFi Config</h2><form action='/wifi' method='post'>SSID: <input name='ssid' style='padding: 5px; margin: 5px;'><br>"; | |
| html += "Password: <input name='pass' type='password' style='padding: 5px; margin: 5px;'><br>"; | |
| html += "<input type='submit' value='Connect' class='button'></form>"; | |
| html += "</body></html>"; | |
| return html; | |
| } | |
| void handleToggle() { | |
| if (server.hasArg("relay")) { | |
| int r = server.arg("relay").toInt(); | |
| if (r >= 0 && r < RELAY_COUNT) { | |
| relays[r].trigger(); | |
| } | |
| } | |
| server.send(200, "text/plain", "OK"); | |
| } | |
| void handleAllRelays() { | |
| if (server.hasArg("state")) { | |
| bool newState = (server.arg("state") == "on"); | |
| for (int i = 0; i < RELAY_COUNT; i++) { | |
| if (relays[i].getState() != newState) { | |
| relays[i].trigger(); | |
| } | |
| } | |
| } | |
| server.send(200, "text/plain", "OK"); | |
| } | |
| void handleWifiConfig() { | |
| String newSSID = server.arg("ssid"); | |
| String newPass = server.arg("pass"); | |
| if (newSSID.length() > 0) { | |
| WiFi.disconnect(); | |
| WiFi.begin(newSSID.c_str(), newPass.c_str()); | |
| prefs.putString("ssid", newSSID); | |
| prefs.putString("password", newPass); | |
| } | |
| server.sendHeader("Location", "/"); | |
| server.send(303); | |
| } | |
| void handleReset() { | |
| prefs.clear(); | |
| WiFi.disconnect(); | |
| ESP.restart(); | |
| server.send(200, "text/plain", "Factory reset initiated. Device will restart."); | |
| } | |
| void setup() { | |
| Serial.begin(115200); | |
| tft.init(); | |
| tft.setRotation(1); | |
| ts.begin(); | |
| ts.setRotation(3); | |
| for (int i = 0; i < RELAY_COUNT; i++) { | |
| pinMode(RELAY_PINS[i], OUTPUT); | |
| digitalWrite(RELAY_PINS[i], LOW); | |
| } | |
| prefs.begin("wifi-config", false); | |
| String savedSSID = prefs.getString("ssid", ""); | |
| String savedPassword = prefs.getString("password", ""); | |
| WiFi.mode(WIFI_AP_STA); | |
| WiFi.softAP("ESP32_Relay_Control", "admin123"); | |
| if (savedSSID.length() > 0) { | |
| WiFi.begin(savedSSID.c_str(), savedPassword.c_str()); | |
| } | |
| server.on("/", HTTP_GET, []() { | |
| server.send(200, "text/html", getMainPage()); | |
| }); | |
| server.on("/toggle", HTTP_GET, handleToggle); | |
| server.on("/all", HTTP_GET, handleAllRelays); | |
| server.on("/wifi", HTTP_POST, handleWifiConfig); | |
| server.on("/reset", HTTP_GET, handleReset); | |
| server.begin(); | |
| configTime(0, 0, "pool.ntp.org"); | |
| setenv("TZ", "CET-1CEST,M3.5.0,M10.5.0/3", 1); | |
| tzset(); | |
| drawMainMenu(); | |
| } | |
| void loop() { | |
| if (!timeConfigured && WiFi.status() == WL_CONNECTED && (millis() - lastTimeSyncAttempt >= timeSyncInterval)) { | |
| syncTime(); | |
| lastTimeSyncAttempt = millis(); | |
| } | |
| handleTouch(); | |
| server.handleClient(); | |
| if (millis() - lastUpdate > 1000 && currentMenu == INFOS_MENU) { | |
| updateInfos(); | |
| lastUpdate = millis(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment