======== ESP32/ESP8266 Projets en cours ======== ===== ESP 32/ESP8266 station meteo ===== [[https://projetsdiy.fr/projet-station-meteo-interface-html-esp8266-dht22-bmp180/|projet-station-meteo-interface-html-esp8266-dht22-bmp180 partie 1 FR ]] [[https://projetsdiy.fr/esp8266-web-serveur-partie2-interaction-arduino-interface-html/|esp8266-web-serveur-partie2-interaction-arduino-interface-html FR ]] ==== ESP8266 Marc ==== {{ :start:arduino:esp32:serveur_web.jpg?direct&400 |}} // Essais de programmation de sites Internet avec ESP8266 // M. Sabarthes le 8 janvier 2022 // BON COURAGE !! #include "Arduino.h" #include "ESP8266WiFi.h" //#include "InfoConnexion.h" #include "ESP8266WebServer.h" // Définition des entrées/sorties de l'ESP8266 #define PIN_D0 16 #define PIN_D1 5 // ==> Envoi un signal PWM au démarrage !! #define PIN_D2 4 #define PIN_D3_VERTE 0 // LED VERTE ATTENTION ==> Envoi un signal PWM au démarrage !! #define PIN_D4_ESP 2 // Led Blue du circuit #define PIN_D5_ROUGE 14 // LED ROUGE ==> Envoi un signal PWM au démarrage !! #define PIN_D6_BP 12 // BOUTON POUSSOIR #define PIN_D7_INTER 13 // INTERRUPTEUR #define PIN_D8 15 // ==> Envoi un signal PWM au démarrage !! #define PIN_D9 3 // Objet : Serial RX ==> Prend l’état HIGH au démarrage !! #define PIN_D10 1 // Objet : Serial TX #define PIN_A0 // Analog 10 bits : maxi 1 volt !! #define ssid "Votre LiveBox" // WiFi SSID #define password "Le mot de passe" // WiFi password //#define DHTTYPE DHT22 // DHT type (DHT11, DHT22) //#define DHTPIN D4 // Broche du DHT / DHT Pin //#define LEDPIN D3 // Led float t = 0.0 ; float h = 0.0 ; float p = 0.0; //String etatLed = "OFF"; char etatLed[]= "OFF"; // Protype des fonctions void handleSubmit(); // ==================== // DEBUT CODE HTML = // ==================== const char page[] PROGMEM = R"=====( Exemple serveur WEB

ESP8266 Demo

"

DHT22

BMP180

" "

GPIO

"

www.projetsdiy.fr/>

)====="; // =================== // = FIN CODE HTML = // =================== // Création des objets / create Objects ESP8266WebServer server ( 80 ); /* Tout le code HTML reste une simple chaîne de caractère facile à manipuler. Vous avez du voir dans le texte qu’il y a des %s %0.1d et %u. Ce sont les emplacements des données que l’on va actualiser à chaque fois que la page change. Pour mettre à jour la page, il suffit de remplacer chaque variable par sa valeur, voici comment faire: On détermine la taille de la page (le nombre de caractères). par sécurité, vous pouvez ajouter quelques caractères supplémentaires. */ //int pagesize = sizeof(page) + 10; // On prépare un buffer qui contiendra la page modifiée //char newpage[pagesize] = ""; /* Maintenant, il suffit de substituer chaque variable par sa valeur à l’aide de la méthode sprintf en utilisant le format indiqué. Par exemple %s pour une chaîne, %0.1d pour un nombre décimal avec un chiffre derrière la virgule… */ // Fonction getpage: mise à jour du contenu de la page HTML String getPage() { // Préparation de la page Internet char newpage[(sizeof(page) + 10)] =""; sprintf(newpage, page, t, h, p, etatLed); //sprintf(newpage, page, 11, 22, 33, etatLed); return newpage; } // Mise à jour de la page WEB void handleRoot(){ if (server.hasArg("LED")) { handleSubmit(); } else { server.send ( 200, "text/html", getPage() ); } } void handleSubmit() { // Actualise le GPIO / Update GPIO String LEDValue; LEDValue = server.arg("LED"); Serial.println("Set GPIO "); Serial.print(LEDValue); if ( LEDValue == "1" ) { digitalWrite(PIN_D3_VERTE, 1); strcat(etatLed,"On"); server.send ( 200, "text/html", getPage() ); } else if ( LEDValue == "0" ) { digitalWrite(PIN_D3_VERTE, 0); strcat(etatLed,"Off"); server.send ( 200, "text/html", getPage() ); } else { Serial.println("Err Led Value"); } } void setup() { Serial.begin (9600); Serial.println("Démarrage !!"); pinMode(PIN_D3_VERTE,OUTPUT); pinMode(PIN_D4_ESP,OUTPUT); // Initialisation du BMP180 / Init BMP180 /* if ( !bmp.begin() ) { Serial.println("BMP180 KO!"); while(1); } else { Serial.println("BMP180 OK"); } */ WiFi.begin (ssid,password); // Attente de la connexion au réseau WiFi / Wait for connection while (WiFi.status() != WL_CONNECTED) { delay ( 500 ); Serial.print ( "." ); } // Connexion WiFi établie / WiFi connexion is OK Serial.println (""); Serial.print ("Connected to "); Serial.println (ssid ); Serial.print ("IP address: "); Serial.println (WiFi.localIP()); digitalWrite(PIN_D4_ESP,LOW); // Allumer LED Blue de l'ESP8266 // On branche la fonction qui gère la premiere page / link to the function that manage launch page server.on ("/",handleRoot); server.begin(); Serial.println ("HTTP server started"); } void loop() { server.handleClient(); /* t = dht.readTemperature(); h = dht.readHumidity(); p = bmp.readPressure() / 100.0F; */ t=20.5555; h=30.6666; p=40.7777; delay(1000); }
===== ESP32 commande chauffage ====== {{:start:arduino:esp32:capture_du_2022-01-14_16-40-31.jpg?direct&400 |}} {{ :start:arduino:esp32:commandechauffage002.jpg?direct&400|}} ---------------------------------- L'utilisation d un relais statique à triac permet d'eviter les parasites du contact du relais lors de son ouverture **Apercu de la page web via http:/192.168.1.xx** {{ :start:arduino:esp32:commande_chauffage_webesp32.png?direct&400 |}} === version 1 === /********* Rui Santos Complete project details at https://RandomNerdTutorials.com/esp32-relay-module-ac-web-server/ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Modification GL 01/2022 *********/ // Import required libraries #include "WiFi.h" #include "ESPAsyncWebServer.h" #include #include #include // Set to true to define Relay as Normally Open (NO) #define RELAY_NO false // Set number of relays #define NUM_RELAYS 1 // Assign each GPIO to a relay int relayGPIOs[NUM_RELAYS] = {15}; // Replace with your network credentials const char* ssid = "xxxxxxxxxxxxxxxx"; const char* password = "xxxxxxxxxxxxxxxxxx"; /* // Wifi castellab const char* ssid = "castellab"; const char* password = "Castel37110$"; */ void Wifi_connected(WiFiEvent_t event, WiFiEventInfo_t info){ Serial.println("Successfully connected to Access Point"); } void Get_IPAddress(WiFiEvent_t event, WiFiEventInfo_t info){ Serial.println("WIFI is connected!"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void Wifi_disconnected(WiFiEvent_t event, WiFiEventInfo_t info){ Serial.println("Disconnected from WIFI access point"); Serial.print("WiFi lost connection. Reason: "); Serial.println(info.disconnected.reason); Serial.println("Reconnecting..."); WiFi.begin(ssid, password); } const char* PARAM_INPUT_1 = "relay"; const char* PARAM_INPUT_2 = "state"; // Create AsyncWebServer object on port 80 AsyncWebServer server(80); const char index_html[] PROGMEM = R"rawliteral(

Castellab commande chauffage

%BUTTONPLACEHOLDER% )rawliteral"; // Replaces placeholder with button section in your web page String processor(const String& var){ //Serial.println(var); if(var == "BUTTONPLACEHOLDER"){ String buttons =""; for(int i=1; i<=NUM_RELAYS; i++){ String relayStateValue = relayState(i-1); buttons+= "

Relay #" + String(i) + " - GPIO " + relayGPIOs[i-1] + "

"; } return buttons; } return String(); } String relayState(int numRelay){ if(RELAY_NO){ if(digitalRead(relayGPIOs[numRelay-1])){ return ""; } else { return "checked"; } } else { if(digitalRead(relayGPIOs[numRelay-1])){ return "checked"; } else { return ""; } } return ""; } void setup(){ // Serial port for debugging purposes Serial.begin(115200); Serial.println("Booting"); pinMode(relayGPIOs[0], OUTPUT); digitalWrite(relayGPIOs[0],LOW); if(RELAY_NO){ digitalWrite(relayGPIOs[0], LOW); } else{ digitalWrite(relayGPIOs[0], HIGH); } // Set all relays to off when the program starts - if set to Normally Open (NO), the relay is off when you set the relay to HIGH /*for(int i=1; i<=NUM_RELAYS; i++){ pinMode(relayGPIOs[i-1], OUTPUT); if(RELAY_NO){ digitalWrite(relayGPIOs[i-1], LOW); } else{ digitalWrite(relayGPIOs[i-1], HIGH); } } */ // Connect to Wi-Fi WiFi.mode(WIFI_STA); WiFi.disconnect(true); delay(1000); WiFi.onEvent(Wifi_connected,SYSTEM_EVENT_STA_CONNECTED); WiFi.onEvent(Get_IPAddress, SYSTEM_EVENT_STA_GOT_IP); WiFi.onEvent(Wifi_disconnected, SYSTEM_EVENT_STA_DISCONNECTED); WiFi.begin(ssid, password); Serial.println("Waiting for WIFI network..."); /* WiFi.begin(ssid, password); while (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.println("Connection Failed! Rebooting..."); delay(5000); ESP.restart(); } */ /* while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } */ // Route for root / web page server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ request->send_P(200, "text/html", index_html, processor); }); // Send a GET request to /update?relay=&state= server.on("/update", HTTP_GET, [] (AsyncWebServerRequest *request) { String inputMessage; String inputParam; String inputMessage2; String inputParam2; // GET input1 value on /update?relay= if (request->hasParam(PARAM_INPUT_1) & request->hasParam(PARAM_INPUT_2)) { inputMessage = request->getParam(PARAM_INPUT_1)->value(); inputParam = PARAM_INPUT_1; inputMessage2 = request->getParam(PARAM_INPUT_2)->value(); inputParam2 = PARAM_INPUT_2; if(RELAY_NO){ Serial.print("NO "); digitalWrite(relayGPIOs[inputMessage.toInt()-1], !inputMessage2.toInt()); } else{ Serial.print("NC "); digitalWrite(relayGPIOs[inputMessage.toInt()-1], inputMessage2.toInt()); } } else { inputMessage = "No message sent"; inputParam = "none"; } Serial.println(inputMessage + inputMessage2); request->send(200, "text/plain", "OK"); }); // Start server server.begin(); ArduinoOTA .onStart([]() { String type; if (ArduinoOTA.getCommand() == U_FLASH) type = "sketch"; else // U_SPIFFS type = "filesystem"; // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() Serial.println("Start updating " + type); }) .onEnd([]() { Serial.println("\nEnd"); }) .onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }) .onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); }); ArduinoOTA.begin(); /* Serial.println("Ready"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); */ } void loop() { ArduinoOTA.handle(); delay(1000); }
===version 2 === **Inserer les 4 programmes suivant dans le même repertoire** /********* Rui Santos Complete project details at https://RandomNerdTutorials.com/esp32-relay-module-ac-web-server/ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Modification GL 01/2022 *********/ // Import required libraries #include "WiFi.h" #include "ESPAsyncWebServer.h" #include #include #include #include "configT.h" // Create AsyncWebServer object on port 80 AsyncWebServer server(80); #include "page_web001.h" // Replaces placeholder with button section in your web page String processor(const String& var){ //Serial.println(var); if(var == "BUTTONPLACEHOLDER"){ String buttons =""; for(int i=1; i<=NUM_RELAYS; i++){ String relayStateValue = relayState(i); buttons+= "

Relay #" + String(i) + " - GPIO " + relayGPIOs[i-1] + "

"; } return buttons; } return String(); } String relayState(int numRelay){ if(RELAY_NO){ if(digitalRead(relayGPIOs[numRelay-1])){ return ""; } else { return "checked"; } } else { if(digitalRead(relayGPIOs[numRelay-1])){ return "checked"; } else { return ""; } } return ""; } void setup(){ #include "setup_relais.h" void loop() { ArduinoOTA.handle(); delay(1000); }
// Set to true to define Relay as Normally Open (NO) #define RELAY_NO false // Set number of relays #define NUM_RELAYS 1 // Assign each GPIO to a relay int relayGPIOs[NUM_RELAYS] = {15}; // Replace with your network credentials const char* ssid = "xxxxxxxxxxxxxxxx"; const char* password = "xxxxxxxxxxxxxxxxxxxx"; void Wifi_connected(WiFiEvent_t event, WiFiEventInfo_t info){ Serial.println("Successfully connected to Access Point"); } void Get_IPAddress(WiFiEvent_t event, WiFiEventInfo_t info){ Serial.println("WIFI is connected!"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void Wifi_disconnected(WiFiEvent_t event, WiFiEventInfo_t info){ Serial.println("Disconnected from WIFI access point"); Serial.print("WiFi lost connection. Reason: "); Serial.println(info.disconnected.reason); Serial.println("Reconnecting..."); WiFi.begin(ssid, password); } const char* PARAM_INPUT_1 = "relay"; const char* PARAM_INPUT_2 = "state"; const char index_html[] PROGMEM = R"rawliteral(

ESP Web Server

%BUTTONPLACEHOLDER% )rawliteral";
// Serial port for debugging purposes Serial.begin(115200); // Set all relays to off when the program starts - if set to Normally Open (NO), the relay is off when you set the relay to HIGH for(int i=1; i<=NUM_RELAYS; i++){ pinMode(relayGPIOs[i-1], OUTPUT); if(RELAY_NO){ digitalWrite(relayGPIOs[i-1],LOW); } else{ digitalWrite(relayGPIOs[i-1], HIGH); } } //digitalWrite(relayGPIOs[0], LOW); // Connect to Wi-Fi WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } // Print ESP32 Local IP Address Serial.println(WiFi.localIP()); // Route for root / web page server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ request->send_P(200, "text/html", index_html, processor); }); // Send a GET request to /update?relay=&state= server.on("/update", HTTP_GET, [] (AsyncWebServerRequest *request) { String inputMessage; String inputParam; String inputMessage2; String inputParam2; // GET input1 value on /update?relay= if (request->hasParam(PARAM_INPUT_1) & request->hasParam(PARAM_INPUT_2)) { inputMessage = request->getParam(PARAM_INPUT_1)->value(); inputParam = PARAM_INPUT_1; inputMessage2 = request->getParam(PARAM_INPUT_2)->value(); inputParam2 = PARAM_INPUT_2; if(RELAY_NO){ Serial.print("NO "); digitalWrite(relayGPIOs[inputMessage.toInt()-1], !inputMessage2.toInt()); } else{ Serial.print("NC "); digitalWrite(relayGPIOs[inputMessage.toInt()-1], inputMessage2.toInt()); } } else { inputMessage = "No message sent"; inputParam = "none"; } Serial.println(inputMessage + inputMessage2); request->send(200, "text/plain", "OK"); }); // Start server server.begin(); // code pour inclure la programmation via le wifi en OTA ArduinoOTA .onStart([]() { String type; if (ArduinoOTA.getCommand() == U_FLASH) type = "sketch"; else // U_SPIFFS type = "filesystem"; // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() Serial.println("Start updating " + type); }) .onEnd([]() { Serial.println("\nEnd"); }) .onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }) .onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); }); ArduinoOTA.begin(); }