DenkLicht Arduino-Code

Hier findest du den Arduino-Code für DenkLicht. Wenn du zwei DenkLichter baust, benötigt jedes Gerät einen eigenen Code:

Kopiere den folgenden Code.
– Öffne die Arduino IDE und füge den Code für jedes Gerät in ein neues Sketch-Fenster ein.
– Gehe zurück zur Anleitung  und fahre mit Schritt 5 (Netzwerk anpassen) fort, um den Code weiter anzupassen und auf den ESP8266 hochzuladen.




// DenkLicht Gerät A

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Adafruit_NeoPixel.h>
#include <ArduinoJson.h>
#include <time.h>

#define MAX_STATUS_AGE 10 

// -------------------------- WiFi & Server Configuration -------------------------------------------

const char* ssid = "DEIN-WLAN-Namen"; // <<<<<      Hier deinen WLAN-Namen einfügen

const char* password = "DEIN-PASSWORT"; // <<<<<    Hier das Passwort deines WLANs einfügen

const String serverUrl = "http://92.205.177.103:3001/";

const String uid = "candleA";  

const String code = "GEMEINSAMER-CODE"; // <<<<<    Hier euren gemeinsamen Code eingeben


WiFiClient client;
HTTPClient http;

// -------------------------- TempSensor Configuration -------------------------------------
#define ONE_WIRE_BUS 4 
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
int sensorCount;

// -------------------------- Neopixel Configuration -------------------------------------
#define PIN2 D7
#define LED_COUNT 12
Adafruit_NeoPixel ledTemp = Adafruit_NeoPixel(LED_COUNT, PIN2, NEO_GRB + NEO_KHZ800);

// ----------------------------------------------------------------------------------------
void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("Connected to WiFi");

  
  sensors.begin();
  sensorCount = sensors.getDS18Count();
  ledTemp.begin();
  ledTemp.show(); 

  
  registerDevice();
}

void loop() {
  delay(2000);

 
  float temp;
  sensors.requestTemperatures();
  temp = sensors.getTempCByIndex(0);

  if (sensorCount == 0) {
    Serial.println("No temperature sensor found!");
    return;
  }

  Serial.print("Temperature A: ");
  Serial.println(temp);

  
  if (temp > 24) {
    updateCandleStatus(true);  
  } else {
    updateCandleStatus(false); 
  }

  
  bool otherCandleStatus = checkCandleStatus();

// Hinweis: die Farbe von LED :
// (255, 0, 0) entspricht reinem Rot
// (0, 255, 0) entspricht reinem Grün
// (0, 0, 255) entspricht reinem Blau
// (255, 0, 255) entspricht Magenta (Pink)

  
  if (otherCandleStatus) {
    for (int i = 0; i < ledTemp.numPixels(); i++) {
      ledTemp.setPixelColor(i, ledTemp.Color(0, 0, 255)); // die Farbe von LED : Blau
    }
  } else {
    for (int i = 0; i < ledTemp.numPixels(); i++) {
      ledTemp.setPixelColor(i, ledTemp.Color(0, 0, 0)); 
    }
  }
  ledTemp.show();
}

void registerDevice() {
  String regUrl = serverUrl + "register";
  http.begin(client, regUrl);
  http.addHeader("Content-Type", "application/json");

  String payload = "{\"uid\":\"" + uid + "\",\"code\":\"" + code + "\"}";
  int httpResponseCode = http.POST(payload);

  if (httpResponseCode > 0) {
    Serial.println("Device registered successfully:");
    Serial.println(http.getString());
  } else {
    Serial.print("Failed to register device. HTTP response code: ");
    Serial.println(httpResponseCode);
  }

  http.end();
}

void updateCandleStatus(bool status) {
  String updateUrl = serverUrl + "updateStatus";
  http.begin(client, updateUrl);
  http.addHeader("Content-Type", "application/json");

  String payload = "{\"uid\":\"" + uid + "\",\"status\":" + (status ? "true" : "false") + "}";
  int httpResponseCode = http.POST(payload);

  if (httpResponseCode > 0) {
    Serial.println("Candle status updated successfully:");
    Serial.println(http.getString());
  } else {
    Serial.print("Failed to update candle status. HTTP response code: ");
    Serial.println(httpResponseCode);
  }

  http.end();
}



bool checkCandleStatus() {
  String statusUrl = serverUrl + "getStatus";
  http.begin(client, statusUrl);
  http.addHeader("Content-Type", "application/json");

  http.setTimeout(5000);  

  String payload = "{\"uid\":\"" + uid + "\"}";
  int httpResponseCode = http.POST(payload);

  if (httpResponseCode > 0) {
    String response = http.getString();
    Serial.println("Status response:");
    Serial.println(response);

   
    StaticJsonDocument<200> jsonDoc;
    DeserializationError error = deserializeJson(jsonDoc, response);

    if (error) {
      Serial.println("Failed to parse JSON response");
      return false;
    }

    
    bool status = jsonDoc["status"];
    const char* lastUpdated = jsonDoc["lastUpdated"];

    
    time_t currentTime = time(nullptr); 
    time_t lastUpdatedTime = parseISO8601Time(lastUpdated);

    if (lastUpdatedTime == 0 || (currentTime - lastUpdatedTime > MAX_STATUS_AGE)) {
      Serial.println("Status is too old or invalid. Ignoring.");
      return false;
    }

    return status; 
  } else {
    Serial.println("Failed to get connected candle status. Device B might be off or no connection.");
    return false; 
  }

  http.end();
  return false;
}


time_t parseISO8601Time(const char* isoTime) {
  struct tm timeinfo;
  if (strptime(isoTime, "%Y-%m-%dT%H:%M:%S", &timeinfo)) {
    return mktime(&timeinfo);
  }
  return 0; 
}



  

Click copy button




// DenkLicht Gerät B

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Adafruit_NeoPixel.h>
#include <ArduinoJson.h>
#include <time.h>

#define MAX_STATUS_AGE 10 

// -------------------------- WiFi & Server Configuration -------------------------------------------

const char* ssid = "DEIN-WLAN-Namen"; // <<<<<      Hier deinen WLAN-Namen einfügen

const char* password = "DEIN-PASSWORT"; // <<<<<    Hier das Passwort deines WLANs einfügen

const String serverUrl = "http://92.205.177.103:3001/";

const String uid = "candleB";  

const String code = "GEMEINSAMER-CODE"; // <<<<<    Hier euren gemeinsamen Code eingeben


WiFiClient client;
HTTPClient http;

// -------------------------- TempSensor Configuration -------------------------------------
#define ONE_WIRE_BUS 4 
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
int sensorCount;

// -------------------------- Neopixel Configuration -------------------------------------
#define PIN2 D7
#define LED_COUNT 12
Adafruit_NeoPixel ledTemp = Adafruit_NeoPixel(LED_COUNT, PIN2, NEO_GRB + NEO_KHZ800);

// ----------------------------------------------------------------------------------------
void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("Connected to WiFi");

  
  sensors.begin();
  sensorCount = sensors.getDS18Count();
  ledTemp.begin();
  ledTemp.show(); 

  
  registerDevice();
}

void loop() {
  delay(2000);

 
  float temp;
  sensors.requestTemperatures();
  temp = sensors.getTempCByIndex(0);

  if (sensorCount == 0) {
    Serial.println("No temperature sensor found!");
    return;
  }

  Serial.print("Temperature B: ");
  Serial.println(temp);

  
  if (temp > 24) {
    updateCandleStatus(true);  
  } else {
    updateCandleStatus(false); 
  }

  
  bool otherCandleStatus = checkCandleStatus();

// Hinweis: die Farbe von LED :
// (255, 0, 0) entspricht reinem Rot
// (0, 255, 0) entspricht reinem Grün
// (0, 0, 255) entspricht reinem Blau
// (255, 0, 255) entspricht Magenta (Pink)

  
  if (otherCandleStatus) {
    for (int i = 0; i < ledTemp.numPixels(); i++) {
      ledTemp.setPixelColor(i, ledTemp.Color(0, 0, 255)); // die Farbe von LED : Blau
    }
  } else {
    for (int i = 0; i < ledTemp.numPixels(); i++) {
      ledTemp.setPixelColor(i, ledTemp.Color(0, 0, 0)); // aus
    }
  }
  ledTemp.show();
}

void registerDevice() {
  String regUrl = serverUrl + "register";
  http.begin(client, regUrl);
  http.addHeader("Content-Type", "application/json");

  String payload = "{\"uid\":\"" + uid + "\",\"code\":\"" + code + "\"}";
  int httpResponseCode = http.POST(payload);

  if (httpResponseCode > 0) {
    Serial.println("Device registered successfully:");
    Serial.println(http.getString());
  } else {
    Serial.print("Failed to register device. HTTP response code: ");
    Serial.println(httpResponseCode);
  }

  http.end();
}

void updateCandleStatus(bool status) {
  String updateUrl = serverUrl + "updateStatus";
  http.begin(client, updateUrl);
  http.addHeader("Content-Type", "application/json");

  String payload = "{\"uid\":\"" + uid + "\",\"status\":" + (status ? "true" : "false") + "}";
  int httpResponseCode = http.POST(payload);

  if (httpResponseCode > 0) {
    Serial.println("Candle status updated successfully:");
    Serial.println(http.getString());
  } else {
    Serial.print("Failed to update candle status. HTTP response code: ");
    Serial.println(httpResponseCode);
  }

  http.end();
}



bool checkCandleStatus() {
  String statusUrl = serverUrl + "getStatus";
  http.begin(client, statusUrl);
  http.addHeader("Content-Type", "application/json");

  http.setTimeout(5000);  

  String payload = "{\"uid\":\"" + uid + "\"}";
  int httpResponseCode = http.POST(payload);

  if (httpResponseCode > 0) {
    String response = http.getString();
    Serial.println("Status response:");
    Serial.println(response);

   
    StaticJsonDocument<200> jsonDoc;
    DeserializationError error = deserializeJson(jsonDoc, response);

    if (error) {
      Serial.println("Failed to parse JSON response");
      return false;
    }

    
    bool status = jsonDoc["status"];
    const char* lastUpdated = jsonDoc["lastUpdated"];

    
    time_t currentTime = time(nullptr); 
    time_t lastUpdatedTime = parseISO8601Time(lastUpdated);

    if (lastUpdatedTime == 0 || (currentTime - lastUpdatedTime > MAX_STATUS_AGE)) {
      Serial.println("Status is too old or invalid. Ignoring.");
      return false;
    }

    return status; 
  } else {
    Serial.println("Failed to get connected candle status. Device A might be off or no connection.");
    return false; 
  }

  http.end();
  return false;
}


time_t parseISO8601Time(const char* isoTime) {
  struct tm timeinfo;
  if (strptime(isoTime, "%Y-%m-%dT%H:%M:%S", &timeinfo)) {
    return mktime(&timeinfo);
  }
  return 0; 
}


  

Click copy button

Zielgruppe: Familie, Paare, Freunde
Art: DIT
Zeitlicher Aufwand: Mittel
Schwierigkeitsgrad: Mittel

Materialien:
Hardware-Komponenten (z.B. ESP8266, LED, Temperatursensor)
Computer
Webbrowser
Internet

Idee & Inspiration:
Das DenkLicht entdecken

Anleitung:
Dein eigenes DenkLicht bauen