App Inventor sends information to ESP8266 by WiFi

4.- App requests two random numbers to the ESP8266 over WiFi .

esp8266_random.aia (2.5 KB)

  • App requests two random numbers to the ESP8266 over WiFi (Router client, static IP)
  • ESP8266 sends two random numbers separated by commas.

#include <ESP8266WiFi.h>
 
const char* ssid = "Name_WiFi";
const char* password = "Password_WiFi";

// Configuración de la IP estática.
    IPAddress local_IP(192, 168, 1, 12);
    IPAddress gateway(192, 168, 1, 1);
    IPAddress subnet(255, 255, 255, 0); 

int random_1 = 0;
int random_2 = 0;
String random_out = "0,0";

WiFiServer server(80);
 
void setup() {
  Serial.begin(115200);
// Establecimiento de la IP estática.
   WiFi.config(local_IP, gateway, subnet); 
  
// Conecta a la red wifi.
  Serial.println();
  Serial.print("Conectando con ");
  Serial.println(ssid);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Conectado con WiFi.");
 
  // Inicio del Servidor web.
  server.begin();
  Serial.println("Servidor web iniciado.");
 
  // Esta es la IP
  Serial.print("Esta es la IP para conectar: ");
  Serial.println("http://");
  Serial.print(WiFi.localIP());
}
 
void loop() {
  // Consulta si se ha conectado algún cliente.
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
 
  Serial.print("Nuevo cliente: ");
  Serial.println(client.remoteIP());
   
  // Espera hasta que el cliente envíe datos.
  while(!client.available()){ delay(1); }

  // Lee la información enviada por el cliente.
  String received = client.readStringUntil('\r');
  Serial.println(received);
  received.replace("+", " ");          // Para que los espacios no salgan con +
  received.replace(" HTTP/1.1", "");   // Para quitar HTTP/1.1
  received.replace("GET /", "");       // Para quitar GET /
  if (received.indexOf("give_me_random") != -1){
   random_1 = random(10,50);
   random_2 = random(50,90);
   random_out = (String) random_1 + "," + (String) random_2;
   }
  
  //////////////////////////////////////////////
  // Página WEB. ////////////////////////////
  String responseContent = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
  responseContent += random_out;
  client.println(responseContent);
}
1 Like