esp01 autonome+module relay+android ?

bonjour,
je cherche à construire un interrupteur à relay commandé par wifi mobile android avec esp01 en wifi local
le module relay "esp-01S relay v1.0" doit etre modifié comme ceci :
photo
et savoir que la commande du transistor qui pilote le relais est sur gpio0
un exemple de code a injecter dans l'esp01 :

// Load Wi-Fi library
#include <ESP8266WiFi.h>

// Replace with your network credentials
const char* ssid     = "myssid";
const char* password = "mypsword";

const int RelayPin =  0; // gpio0

byte crm; // Holds if command was recieved to change relay mode
byte  relayMode; // Holds current relay state

// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output5State = "off";


void setup() {
  Serial.begin(115200);
  // Initialize the output variables as outputs
  pinMode(RelayPin, OUTPUT);
  // Set outputs to LOW
  digitalWrite(RelayPin, LOW);

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
  relayMode = 0;
  crm = 0;
}

void loop() {
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            // turns the GPIOs on and off
            if (header.indexOf("GET /5/on") >= 0) {
              Serial.println("Relay on");
              output5State = "on";
              digitalWrite(RelayPin, HIGH);
            } else if (header.indexOf("GET /5/off") >= 0) {
              Serial.println("Relay off");
              output5State = "off";
              digitalWrite(RelayPin, LOW);
            }

            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons 
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #77878A;}</style></head>");
            
            // Web Page Heading
            client.println("<body><h1>ESP8266 Web Server</h1>");
            
            // Display current state, and ON/OFF buttons for GPIO 5  
            client.println("<p>GPIO 0 - State " + output5State + "</p>");
            // If the output5State is off, it displays the ON button       
            if (output5State=="off") {
              client.println("<p><a href=\"/5/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/5/off\"><button class=\"button button2\">OFF</button></a></p>");
            } 
               /*
            // Display current state, and ON/OFF buttons for GPIO 4  
            client.println("<p>GPIO 4 - State " + output4State + "</p>");
            // If the output4State is off, it displays the ON button       
            if (output4State=="off") {
              client.println("<p><a href=\"/4/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/4/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
            */
            client.println("</body></html>");
            
            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}

ensuite on ouvre le moniteur série pour connaitre l'adresse ip de l'esp01 (192.168.0.11 dans mon cas)
apres un navigateur web adresse 192.168.0.11, on a une page html avec bouton OFF, on appuye le bouton passe sur ON, la led bleue s'allume et le relais s'enclenche, l'adresse ip devient 192.168.0.11/5/ON, on réappuye çà s'éteint et l'adresse est 192.168.0.11/5/OFF
j'aimerais une application android avec un bouton on/off ou 1 on et 1 off.
je cherche donc une appli android+code esp01 correspondant (pas un code pour UNO/promini/nano)
ou çà n'existe pas ou je cherche mal.....
Merci

soit tu a mal chercher...

tu veux un site web? ou app android?

ce que tu as dans ton code c'est une page HTML, et non app android...

Au lieu d'avoir la LED tu as le relais, il suffit juste de le remplacer....

Mais il vaux mieux utiliser du javascript dans ta page HTML

Tu as la meme chose en version android

ce n'est pas vraiment un bouton, mais avec une adaptation c'est largement possible

tu as la base, mais avec APP inventor tu peux créer une app android avec un bouton ON/OFF

bonjour,

oui une app android qui correspond a un esp01 avec le code a mettre dans le esp8266
j'ai vu des relay wifi avec blynk ou mit app inventor avec souvent des wemos d1
j'ai rien compris à ceux qui utilise nodemcu ou lua
il y des applis sur le playstore : esp01 relay, wifi relay, mais sans savoir à quel "produit" çà s'appliquait
le lien hackster.io : c'est bien le principe d'ailleurs
" built this project because I could not find open source available Android code to communicate with a WiFi access point (in this case an ESP8266)"

il faut que le smartphone accede a l'esp01 en étant connecté en permanence sur mon wifi local
ou que l'esp01 "ecoute" mon wifi local pour savoir quand une commande lui est destinée ???????

Merci pour les liens

esp01 et esp8266, c'est la meme chose...

Bonjour

j'ai rien compris à ceux qui utilise nodemcu ou lua

'nodemcu' est devenu un terme 'fourre tout' et par conséquent piégeur
A l'origine c'est effectivement un firmawre open source à base de langage Lua
Ce projet Open Source a été accpompagné d'une carte nommée Devkit NodeMCU
ette carte a servi de modèle à une grande variété de cartes à base d'ESP8266, puis, le terrme étant 'vendeur' de cartes à base d'ESP32 ayant le mëme 'look', on peut s'attendre sur ceratins sites à le voir attribué à des cartes avec d'autres processeurs....

j'aimerais une application android avec un bouton on/off ou 1 on et 1 off.

cette application peut tout simplement êre le navigateur
la carte quelconque à ESP8266 quelconque
-configurée en STATION connectée a au Point d'accès
-faisant tourner un serveur HTTP proposant au client( smartphone et son navigateur) une page web dotée de boutons.

On trouve de nombreux exemples de ce type de configuration dans lesquelels les boutons permettent d'allumer ou éteindre la led de la carte. Il suffit de décaler le GPIO géré.
Un tutoriel içi : Build an ESP8266 Web Server - Code and Schematics (NodeMCU) | Random Nerd Tutorials

bonjour,

merci pour les explications node mcu/lua

code pour esp12f + apk : ICI

un autre pour wemosd1 ? application dans le playstore et le code arduino

Merci

bonjour,

a force on y arrive....
dans le croquis je change sw1 sur 0

int switch1 = 0;
//int switch2 = 15;

je recompile le fichier aia qui a été fourni sur le github comme le blog l'indique en changeant la langue text-to-speech en francais
j'ai installé l'apk sur un appareil android 4.2, çà fonctionne sur le relais1, il y la voix qui dit lamp1 ON et lamp1 OFF, bien que çà fonctionne il y a un message d'erreur en appuyant sur les boutons apres que la voix ait fini son speech
"error 1101 : unable to get un response with the specified url http://192.168.0.14/sw1on"
le message disparait apres 3 sec tant que l'on n'appuye plus sur un bouton
l'application attend une reponse de l'esp01 ?

void loop()
{
    client = server.available();
    if (!client) return; 
    command = checkClient ();

         if (command == "sw1on") digitalWrite(switch1,HIGH);
    else if (command == "sw1off") digitalWrite(switch1,LOW);
   // else if (command == "sw2on") digitalWrite(switch2,HIGH);     
    //else if (command == "sw2off") digitalWrite(switch2,LOW);
    else if (command == "allon") 
    {
      digitalWrite(switch1,HIGH);
      //digitalWrite(switch2,HIGH);
    }
    else if (command == "alloff") 
    {
      digitalWrite(switch1,LOW);
     // digitalWrite(switch2,LOW);
    }
    sendBackEcho(command); // send command echo back to android device
    command = "";
}

/* connecting WiFi */
void connectWiFi()
{
  Serial.println("Connecting to WIFI");
  WiFi.begin(ssid, password);
  while ((!(WiFi.status() == WL_CONNECTED)))
  {
    delay(300);
    Serial.print("..");
  }
  Serial.println("");
  Serial.println("WiFi connection established");
  Serial.println("IP number is : ");
  Serial.print((WiFi.localIP()));
}

/* check command received from Android Device */
String checkClient (void)
{
  while(!client.available()) delay(1); 
  String request = client.readStringUntil('\r');
  request.remove(0, 5);
  request.remove(request.length()-9,9);
  return request;
}

/* send command echo back to android device */
void sendBackEcho(String echo)
{
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println("");
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");
  client.println(echo);
  client.println("</html>");
  client.stop();
  delay(1);
}

Merci

je ne parviens pas a inserer une image avec "attachements"

lien vers hebergeur externe

Bonjour

l'application attend une reponse de l'esp01 ?

Oui : dt ans le code de Luc Voulders, côté ESP8266 on lit

sendBackEcho(command); // send command echo back to android device

= appel de la fonction construisant la réponse, une réponse atant attendue pour des raisons 'protocolaires'

L'ESP renvoie ici en écho la commande qu'il a reçue, commande qui a été envoyée sous forme de requête GET.

C'est à dire que pour allumer disons la DEL1 ton application Android se comporte avc la méthode GET comme un navigateur qui demande l'accès au contenu de la page 192.168.x.x/sw1on

Il est dans la logique des choses que le serveur HTML installé côté ESP réponde quelque chose et que la méthode GET implantéé dans AIA attende cette réponse à une demande de contenu (elle est conçue pour charger du contenu pas juste pour envoyer une info)

l’appareil android ne reçoit pas cette réponse ?
le serveur html de l'esp01 reçoit la commande pour allumer led1
en meme temps il recoit l'adresse IP de celui qui a envoyé la commande ?
et il envoie une chaine de caracteres "http://adresseIP/sw1on" par exemple ?

si j'utilise l'application sans brancher l'esp01, je n'ai pas le message d'erreur ? ?

IL SUFFIT de supprimer les notifications dans les parametres de l'applications sur le smartphone pour que le message ne s'affiche plus, ce qui ne signifie pas que android reçoit une réponse ....

d'autre part j'aimerais supprimer completement le text to speech dans le "pgme" aia appinventor, pcque c'est tres énervant....

Merci pour vos réponses antérieures et futures