Files
appRobotDriver/EmergencyStopButton/EmergencyStopButton.ino
2026-06-19 06:43:56 +02:00

90 lines
2.8 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// EmergencyStopButton.ino
// ESP32 WiFi Light Sleep, wacht per GPIO-Interrupt auf Knopfdruck auf
// und sendet sofort einen API-Call. Ziel: <250ms von Knopfdruck bis API.
#include <WiFi.h>
#include <HTTPClient.h>
#include "esp_wifi.h"
#include "esp_sleep.h"
#include "driver/gpio.h"
// ── Konfiguration ────────────────────────────────────────────────────────────
#define BUTTON_PIN 9 // GPIO-Pin des Tasters (gegen GND)
#define WIFI_SSID "DEIN_SSID"
#define WIFI_PASSWORD "DEIN_PASSWORT"
#define API_URL "https://deine-api.example.com/emergency-stop"
#define API_TOKEN "DEIN_API_TOKEN"
// ─────────────────────────────────────────────────────────────────────────────
void connectWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("WiFi verbinden");
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.printf("\nVerbunden. IP: %s\n", WiFi.localIP().toString().c_str());
}
void sendEmergencyStop() {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi nicht verbunden API-Call abgebrochen");
return;
}
HTTPClient http;
http.begin(API_URL);
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", "Bearer " API_TOKEN);
http.setTimeout(3000);
String body = "{\"event\":\"emergency_stop\",\"device\":\"esp32-estop\"}";
int httpCode = http.POST(body);
if (httpCode > 0) {
Serial.printf("API Response: %d\n", httpCode);
} else {
Serial.printf("HTTP Fehler: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
void enterLightSleep() {
// Wakeup bei LOW-Pegel (Taster gegen GND, Pull-Up aktiv)
gpio_wakeup_enable((gpio_num_t)BUTTON_PIN, GPIO_INTR_LOW_LEVEL);
esp_sleep_enable_gpio_wakeup();
esp_light_sleep_start();
// Ab hier läuft der Code weiter, sobald der Taster gedrückt wird
}
void setup() {
Serial.begin(115200);
pinMode(BUTTON_PIN, INPUT_PULLUP);
connectWiFi();
// DTIM=10: ESP32 wacht alle ~1000ms kurz für Beacon auf → ~0.51 mA
esp_wifi_set_ps(WIFI_PS_MAX_MODEM);
Serial.println("Bereit. Warte auf Knopfdruck...");
}
void loop() {
enterLightSleep();
// Wakeup → Taster prüfen (Low-aktiv wegen Pull-Up)
if (digitalRead(BUTTON_PIN) == LOW) {
unsigned long t0 = millis();
sendEmergencyStop();
Serial.printf("Latenz API-Call: %lu ms\n", millis() - t0);
// Warten bis Taster losgelassen (Entprellung)
while (digitalRead(BUTTON_PIN) == LOW) {
delay(10);
}
delay(50);
}
}