Examples with the ESP8266-01. Wifi. LED on/off. Arduino. Standalone. MQTT

The ESP8266 has a lot of variety of models...
https://www.researchgate.net/figure/Variation-of-ESP8266-modules_fig1_332527943

https://blog.squix.org/2015/03/esp8266-module-comparison-esp-01-esp-05.html

  • The best known are the ESP8266-01 and the ESP8266-12.

  • We can find the ESP8266-12 on the NodeMCU board.

nodemcu2

https://community.appinventor.mit.edu/t/ble-esp32-bluetooth-send-receive-arduino-ide-multitouch/1980

4 Likes

1.- But this guide is about ESP8266-01

Pros:

  • Small dimensions.
  • Cheap.
  • Wifi access point and router client.
  • It can work connected to an Arduino or standalone.

Cons:

  • It only has GPIO0 and GPIO2
  • Low memory.
  • We cannot insert it into a standard Protoboard due to the distance of its pins.

On the internet you can find a lot of information about this model, I am going to summarize my tutorial in Spanish about this model.

http://kio4.com/arduino/57modulowifi_2.htm

2 Likes

2.- Load Firmware. It's easy.

3.- Playing with AT commands from Serial Monitor.

AT+CIOBAUD=?
AT+CIOBAUD?
AT+CIOBAUD=9600
AT+GMR
AT+CWMODE?
AT+CWMODE=3
AT+CWLAP
AT+CWJAP="MIROUTER","micontraseña"
AT+CWJAP?
AT+CIFSR
AT+CIPSERVER=1,80

1 Like

4.- Load a Sketch. Turn On/Off the Arduino LED13. Web page. App Inventor.

/***********
Juan A. Villalpando
KIO4.COM
25/11/22

Version del módulo 9.2.4
Velocidad 9600
Carga el programa. Ve al Serial Monitor.
Escribe en un navegador 192.168.1.5
Pulsa los botones para encender o apagar el LED13 del Arduino.

***********/

#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(3,2); 
// El TX del módulo al terminal 3 del Arduino.
// El RX del módulo al terminal 2 del Arduino.
void setup()
{
pinMode(13,OUTPUT);
Serial.begin(9600);
esp8266.begin(9600); // Importante la velocidad del módulo.

sendData("AT+RST\r\n",2000,DEBUG); // Borra la configuración que tenía el módulo
sendData("AT+CWJAP=\"Nombre_de_tu_WiFi\",\"Clave_de_tu_WiFi\"\r\n", 2000, DEBUG);
delay(5000); // Espera un poco que conecte con el Router.
sendData("AT+CWMODE=3\r\n",1000,DEBUG); // Modo de cliente y servidor.
sendData("AT+CIFSR\r\n",1000,DEBUG); // En el Serial Monitor aparece la IP de cliente y servidor.
sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // Multiples conexiones.
sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // El Puerto web es el 80
}
   
void loop(){
if(esp8266.available()) // Consulta si el módulo está enviando algún mensaje
{
if(esp8266.find("+IPD,"))
{
delay(500);

int connectionId = esp8266.read()-48; 
// Aquí las construcción de la PAGINA WEB.
String webpage = "HTTP/1.1 200 OK\r\n Content-Type: text/html\r\n\r\n\r\n";
webpage += "<h1>KIO4.COM</h1>";
webpage += "<form method=\"get\" action=\"/enci\">";
webpage += "<button type=\"submit\">ON - ENCIENDE</button></form>";
webpage += "<form method=\"get\" action=\"/apag\">";
webpage += "<button type=\"submit\">OFF - APAGA</button></form>\r\n\r\n";

String cipSend = "AT+CIPSEND=";
cipSend += connectionId;
cipSend += ",";
cipSend +=webpage.length();
cipSend +="\r\n";

sendData(cipSend,500,DEBUG);
sendData(webpage,500,DEBUG);

// Lee el pin 13
int pin13 = digitalRead(13); 
// Retorno de la lectura.
String retorno = "HTTP/1.1 200 OK\r\n Content-Type: text/html\r\n\r\n\r\n";
if (pin13 == 1) {retorno += "<br> ON - Encendido";}
if (pin13 == 0) {retorno += "<br> OFF - Apagado";}

// ResponseCode App Inventor
cipSend = "AT+CIPSEND=";
cipSend += connectionId;
cipSend += ",";
cipSend += retorno.length();
cipSend +="\r\n";

sendData(cipSend,500,DEBUG);
sendData(retorno,500,DEBUG);

// Cierra la conexión
String closeCommand = "AT+CIPCLOSE="; 
closeCommand+=connectionId;
closeCommand+="\r\n";

sendData(closeCommand,500,DEBUG);
}
}
}

// Función para Enviar datos al Servidor.
String sendData(String command, const int timeout, boolean debug){
String response = "";
esp8266.print(command); // Envía la información de command al servidor
long int time = millis();

while( (time+timeout) > millis())
{
while(esp8266.available())
{
// A response van los datos que regresan al servidor.
char c = esp8266.read(); // Va leyendo caracter a caracter.
response+=c;

// Consulta si en la información que regresa al servidor
// viene "GET /enci" o "GET /apag"
// Encenderá o apagará el LED13 del Arduino
if(response.indexOf("GET /enci") >0){
// Serial.print("enciende");
digitalWrite(13,HIGH);
}
if(response.indexOf("GET /apag") >0){
//Serial.print("apaga");
digitalWrite(13,LOW);
}
} 
}

if(debug)
{
Serial.print(response);
} 
return response;
}

p57_esp8266_01.aia (2.0 KB)

esp8266_45

esp8266_43

esp8266_46

- Comments.

  • We can turn on/off the LED13 of the Arduino through an app with the Web component or through a web page.

  • In order for the Web component's GotText event to recognize the responseContent, Sketch needs to send an HTTP header.

  • The Sketch shown is didactic, note that the HTTP header is sent twice, also note that the app receives the source code of the web page, you can modify and improve it.

  • In this example, the ESP8266-01 works as a client of a local WiFi network.

  • Note that the Sketch has several delays of 500 ms, so we must wait about 6 seconds to make the changes.

1 Like

5.- The app requests two random numbers from the Web Server.

p57B_esp8266_01.aia (2.8 KB)

  • The app requests two random numbers from the Web Server using
    http ://192.168.1.9/genera

  • When the Server receives the word "genera" it creates two random numbers separated by commas: 14,71

  • Through the header, the Server sends "14,71" to the app that will receive it in responseContent.

  • This converts the string to a list and displays its two elements.

// http://kio4.com/arduino/57modulowifi_2.htm
// Juan A. Villalpando

#include <SoftwareSerial.h>
SoftwareSerial esp8266(3,2); 
// El TX del módulo al terminal 3 del Arduino.
// El RX del módulo al terminal 2 del Arduino.

int random_1 = 10;
int random_2 = 50;
String random_out = "0,0";
String input_data = "";
String fin = "";

void setup(){
  randomSeed(analogRead(A0));  
  Serial.begin(9600);
  esp8266.begin(9600);
  
  sendData("AT+RST\r\n",2000); // Borra la configuración que tenía el módulo
  sendData("AT+CWJAP=\"Nombre_de_tu_WiFi\",\"Clave_de_tu_WiFi\"\r\n", 2000);
  delay(10000); // Espera un poco que conecte con el Router.
  sendData("AT+CWMODE=1\r\n",1000); // Modo de cliente del Router.
  sendData("AT+CIFSR\r\n",1000); // En el Serial Monitor aparece la IP del Servidor Web.
  sendData("AT+CIPMUX=1\r\n",1000); // Multiples conexiones.
  sendData("AT+CIPSERVER=1,80\r\n",1000); // Crea Servidor Web, puerto 80
}

void loop(){
if(esp8266.available()){ 
   while(esp8266.available()){
      char c = esp8266.read();
      input_data += c;

      if(input_data.indexOf("genera") > 0){
      random_1 = random(10,50);
      random_2 = random(50,99);
      random_out = (String) random_1 + "," + (String) random_2;
      input_data = "";
      fin = "finalizado";
      }
   } 
}

// Return responseContent 
if(fin == "finalizado"){ 
     String header = "HTTP/1.1 200 OK\r\n Content-Type: text/html; \r\n"; 
     header += "Content-Length: ";
     header += random_out.length();
     header += "\r\nConnection: close\r\n\r\n";
     header += random_out;
     sendData("AT+CIPSEND=" + String(0) + "," + header.length() + "\r\n", 500);
     sendData(header,1000);
     // sendData ("AT+CIPCLOSE=" + String(0) + "\r\n", 1000);
     fin = "";
     }
}

// Envia datos al servidor y recibe la respuesta de los AT.
String sendData(String command, const int timeout){
    String response = "";
    esp8266.print(command); // Envía la información de command al servidor
    long int time = millis();
    
    while( (time+timeout) > millis()){
      while(esp8266.available()){
          // A response van los datos que regresan al servidor.
          char c = esp8266.read(); // Va leyendo caracter a caracter.
          response+=c;
       } 
    }
    
    Serial.print(response);
    return response; // Devuelve la respuesta del AT
}

Thank you for the tutorials.

The AT+... commands were new to me, so I searched for them and found this site explaining them ...
https://room-15.github.io/blog/2015/03/26/esp8266-at-command-reference/

It took me a while to figure out how the web server "knew" to work off IP address 192.168.1.9, but then I saw it in the COM24 log as the result of the AT+CIFSR command, and I imagine you read that output to get the IP address hard coded into the AI2 app.

1 Like

Good AT command guide!

I tried to change the IP and get the Mac, but it didn't work for me with my Firmware.

sendData("AT+CIPSTA=\"192.168.1.222\"\r\n",1000); // Set IP
sendData("AT+CIPSTAMAC?\r\n",1000); // Get Mac

6.- Configure an Access Point. SoftAP.

  • Now we are going to carry out the previous example but we will create an Access Point (SoftAP - Soft Access Point), that is, the module will create a network independent from the Router, it will not be connected to the Router.

  • The code will create a network called ESP_81411C and the Web Server will have as IP: 192.168.4.1

  • For this we will change these lines...

void setup(){
  randomSeed(analogRead(A0));  
  Serial.begin(9600);
  esp8266.begin(9600);
  
  sendData("AT+RST\r\n",2000); // Borra la configuración que tenía el módulo
  // sendData("AT+CWJAP=\"Nombre_de_tu_WiFi\",\"Clave_de_tu_WiFi\"\r\n", 2000);
  // delay(10000); // Espera un poco que conecte con el Router.
  sendData("AT+CWMODE=2\r\n",1000); // NOW IS A SOFT ACCESS POINT, MODE = 2
  sendData("AT+CIFSR\r\n",1000); // En el Serial Monitor aparece la IP del Servidor Web. (192.168.4.1)
  sendData("AT+CIPMUX=1\r\n",1000); // Multiples conexiones.
  sendData("AT+CIPSERVER=1,80\r\n",1000); // Crea Servidor Web, puerto 80
}
  • We must change the IP in the code...
    esp8266_54

  • It is also convenient to install the application, since we are going to change the network and the MIT Companion will be in the Router's network.

  • Once the application is installed, we go to the WiFi configuration and establish the ESP_81411C network

  • It is not necessary to put a Password since in this default configuration it does not have it.

  • If we wanted to change the name of the network and put a password on it, we would put this line:

sendData("AT+CWSAP=\"ESP8266\",\"key1234\",5,3\r\n",1000);

7.- Proposals.

a) Connect two pushbuttons to the Arduino and get their status in the application.

b) Connect a potentiometer to the Arduino and get its value in the app.

http://kio4.com/arduino/57modulowifi_2.htm#pulsadores

8.- Standalone (without Arduino). Turn LED on/off.

  • The ESP8266-01 can work without being connected to the Arduino, this is called standalone.
  • We are going to create a Web Server that will be a client of a Router, for this we will not use the AT commands that we have seen previously, but the "<ESP8266WiFi.h>" library.
  • To load the Sketch in the ESP8266-01 we will use the Arduino

1.- This connection...


2.- IDE, Tools, Board: "Generic ESP8266 Module"

3.- Remove the Serial Monitor, in case you have it open.

4.- We load this sketch in the IDE and upload it...

It is convenient from time to time to remove the power from the ESP8266 and put it back if it does not load well.

Summary
/*
 *  This sketch demonstrates how to set up a simple HTTP-like server.
 *  The server will set a GPIO pin depending on the request
 *    http://server_ip/gpio/0 will set the GPIO2 low,
 *    http://server_ip/gpio/1 will set the GPIO2 high
 *  server_ip is the IP address of the ESP8266 module, will be 
 *  printed to Serial when the module is connected.
 */

#include <ESP8266WiFi.h>

const char* ssid = "nombredemirouter";
const char* password = "contraseñadelrouter";

// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

void setup() {
Serial.begin(9600);
delay(1500);

// prepare GPIO2
pinMode(2, OUTPUT);
digitalWrite(2, LOW);

// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");

// Start the server
server.begin();
Serial.println("Server started");

// Print the IP address
Serial.println(WiFi.localIP());
}

void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}

// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}

// Read the first line of the request
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();

// Match the request
int val;
if (req.indexOf("/gpio/0") != -1)
val = 0;
else if (req.indexOf("/gpio/1") != -1)
val = 1;
else {
Serial.println("invalid request");
client.stop();
return;
}

// Set GPIO2 according to the request
digitalWrite(2, val);

client.flush();

// Prepare the response
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
s += (val)?"high":"low";
s += "</html>\n";

// Send the response to the client
client.print(s);
delay(1);
Serial.println("Client disonnected");

// The client will actually be disconnected 
// when the function returns and 'client' object is detroyed
}

5.- When there is upload, remove the GPIO 0 to GND cable and open the Serial Monitor. Restart.
esp8266_57

6.- Once the sketch is loaded we can remove the Arduino, connect an LED to the GPIO2 and feed the module with 3.3V

  • If you don't have a 3.3V power supply, you can use the Arduino to power the module, note that you don't need RX or TX.

7.- In a web browser...
http ://192.168.1.11/gpio/1

http ://192.168.1.11/gpio/0

esp8266_58

9.- Proposals.

a) Carry out the previous example, but configuring the Server through the AT commands.

b) Carry out the previous example but creating an access point (SoftAP).

c) The "18B20" is a temperature sensor, connect it to the ESP8266-01 and get the temperature in the app.

10.- Turn on/off a LED from the Internet. MQTT. Standalone.

p117B_ESP82666_mqtt_Extension_Btn_LED.aia (73.9 KB)

- Designer.

- Blocks.

- ESP8266-01. Code.

Summary
// http://kio4.com/arduino/57modulowifi_4.htm
// http://kio4.com/arduino/117_Wemos_MQTT.htm
// Juan A. Villalpando


#include <ESP8266WiFi.h> // Para el ESP8266
// #include <WiFi.h> // Para el ESP32
WiFiClient WIFI_CLIENT;
#include <PubSubClient.h>
PubSubClient MQTT_CLIENT;

const char* ssid = "Nombre_Red_WiFi";
const char* password = "Clave_WiFi";

#define LED2 2 
String LED2_status = "-";

void setup() {
  pinMode(LED2, OUTPUT);
  Serial.begin(9600);
  delay(10);
  Serial.println();
  Serial.print("Connecting with ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

Serial.println("");
Serial.print("WiFi conected. IP: ");
Serial.println(WiFi.localIP());

// Setting Callback.
  MQTT_CLIENT.setCallback(callback);
}

// What to do when it receives the data. 
void callback(char* recibido, byte* payload, unsigned int length) {
  Serial.print("Message received: ");
  Serial.print(recibido);
  Serial.print("   ");

  for (int i=0;i<length;i++) {
    char receivedChar = (char)payload[i];
    Serial.println(receivedChar);
  if (receivedChar == '1') {digitalWrite(LED2, HIGH);}
  if (receivedChar == '2') {digitalWrite(LED2, LOW);}

    if (digitalRead(LED2) == HIGH) {LED2_status = "LED2 ON";} else {LED2_status = "LED2 OFF";}
  }
}
 
void loop() {
  if (!MQTT_CLIENT.connected()) {
    reconnect();
  }

  // PUBLISH topic.
// Convierte el entero a char. Debe ser char.
char led2_st[10];
LED2_status.toCharArray(led2_st, 10);

MQTT_CLIENT.publish("juan/led2_status", led2_st);
  delay(1000);
MQTT_CLIENT.loop(); // Check Subscription.

}

// Reconecta con MQTT broker
void reconnect() {
MQTT_CLIENT.setServer("broker.hivemq.com", 1883);  
//MQTT_CLIENT.setServer("mqtt.eclipse.org", 1883);
MQTT_CLIENT.setClient(WIFI_CLIENT);

// Trying connect with broker.
while (!MQTT_CLIENT.connected()) {
Serial.println("Trying to connect with Broker MQTT.");
MQTT_CLIENT.subscribe("juan/boton2"); // HERE SUBSCRIBE.

// Wait to try to reconnect again...
delay(3000);
}

Serial.println("Conectado a MQTT.");
}

11.- Arduino Mega 2560 and Pro Mini. Software Serial library.

In Arduino Mega 2560 and Pro Mini it is necessary to change the connection pins.

pinMode (8,OUTPUT);
pinMode (11,INPUT);

SoftwareSerial esp8266(11,8);

SoftwareSerial Library in Mega.