Arduino Mega + Wifi Automation: Step 1: Assembly
Arduino Mega + Wifi Automation: Step 1: Assembly
by Fernando Koyanagi
Today, I’ll talk about an assembly that was suggested by many followers: Arduino Mega + ESP. This will include
an automation project with 16 relays, three sensors, and a smartphone. We’ll make a Web Server for the Arduino
Mega using serial communication with the ESP8266, in the ESP-01 version. I will also show a page with the
values of sensors and buttons to modify the state of the relays.
https://youtu.be/u75uASGEvNg
Step 1: Assembly
I placed here the schematic, which shows the DHT22, the Ds18b20, and a third sensor (the light), which are all
connected to the relays by the pins 36 to 51.
See the video demonstration of the project in send them to the cell phone from the Arduino Mega,
operation. In the assembly, you are given a 16-wire through the ESP, which would be the serial bridge (ie
board, which is connected directly to the ports of an the WiFi).
Arduino Uno. This Uno I used was only to power the
3v3 of the ESP-01. I still have an LDR (which is my In the assembly, we have LEDs which, when lit,
light sensor), a Ds18b20 thermometer, and the indicate that the respective relays are switched off.
DHT22, which collects humidity and temperature This process is also controlled by the smartphone.
data. We have an application on the smartphone that
will display the data collected by these sensors and
For our project today, we will need certain libs: In the Arduino IDE, go to Sketch-> Include Library->
Manage Libraries ...
WiFiEsp Library
Install DallasTemperature
In the Arduino IDE, go to Sketch-> Include Library->
Manage Libraries ... OneWire Library
MEGAESP_01.ino
We start off by including the libraries and defining the pins attached to the sensors. We also point out the pin
where the first relay will be and how many pins (starting from this first one) will be used.
We continue with the DS18B20 temperature sensor, and the DHT22 temperature and humidity sensor. We then
set out for definitions involving the WiFi network, such as the SSID and password for the ESP to connect. We
point to the server that will receive the requests on port 80 (standard port http), as well as the variables to store the
values of the sensors.
MEGAESP_01.ino - setup
We initialize the serial and serial monitor where the ESP-01 is with AT firmware, in addition to pins, and DS18B20
and DHT22 sensors. For the brightness sensor, we just need to read the analog pin. We also initialize the WiFi
and connect to the network. Finally, we initialize the server.
//Inicializa os pinos
setupPins();
//Inicializa o server
server.begin();
}
MEGAESP_01.ino - setupPins
In this step, we put the pins that are connected to the relays as outputs.
void setupPins()
{
//Coloca os pinos que estão ligados os relês como saída
for(int i=0; i
MEGAESP_01.ino - setupWiFi
Here, we perform a function that initializes the serial where the ESP-01 is with the AT firmware already installed.
We wait to connect to the WiFi network, configure the IP, and verify the same IP.
Serial.print("Conectando a ");
Serial.println(ssid);
Serial.println();
Serial.println("Conectado");
//Configura o IP
IPAddress ipAddress;
ipAddress.fromString(ip);
WiFi.config(ipAddress);
//Veririca o IP
IPAddress localIP = WiFi.localIP();
Serial.print("IP: ");
Serial.println(localIP);
}
MEGAESP_01.ino - setupDS18B20
if (!sensors.getAddress(sensor, 0))
{
Serial.println("Sensor não encontrado!");
}
}
MEGAESP_01.ino - Loop
In the Loop, we check for a new client. We read the request and, if the request is not for the favicon, we execute
the action with the value passed in the request. We then read the sensors and send the response to the customer.
We determine a time for the browser to receive the data and close the connection with the client.
MEGAESP_01.ino - readRequest
Here, we have a very important function. What does it do? When we press a button on the smartphone, the
function sends the command in HTTP to ESP8266, using only the first line, as you see in the example below. I
emphasize that even after reading the first line, it is important to read it until the end, otherwise the WiFiESP lib
gives a timeout.
Host: 192.168.3.154\r\n
Connection: keep-alive\r\n
Cache-Control: max-age=0\r\n
Upgrade-Insecure-Requests: 1\r\n
User-Agent: Mozilla/5.0 (Linux; Android 8.0.0; SM-G955F Build/R16N ) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/68.0.3440.91 Mobile Safari/537.36\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n
Referer: http://192.168.3.154/\r\n
\r\n
while (client.connected()){
if(client.available()){
char c = client.read();
Serial.write(c);
We see that the last line of the request is: \ r \ n alone, \ r \ n. And, after the previous line, it is: \ r \ nso. If we get
here, it is because the request has been read in full. Also, if you read any character other than \ n and \ r, it means
that the line is not blank.
if (c == '\n'){
//A última linha da requisição é um \r\n sozinho, após o \r\n da linha anterior
if(currentLineIsBlank){
//Se chegou aqui é porque a requisição foi lida por completo
break;
}
currentLineIsBlank = true;
firstLine = false;
}
else if (c != '\r'){
//Se leu qualquer caracter que não for \n e \r significa que a linha não está em branco
currentLineIsBlank = false;
}
}
}
return request;
}
MEGAESP_01.ino - sendResponse
This function sends the HTML to the client. It also sends the HTTP header, as well as the HTML header and body.
client.println("<!DOCTYPE HTML>");
client.println("<html>");
head(client);//Envia o cabeçalho do HTML
body(client);//Envia o corpo do HTML
client.println("</html>");
MEGAESP_01.ino - head
"body{"
"text-align: center;"
"font-family: sans-serif;"
"font-size: 14px;"
"}"
"p{"
"color:#555;"
"font-size: 12px;"
"}"
".button{"
"outline: none;"
"display: block;"
"border: 1px solid #555;"
"border-radius:18px;"
"width: 150px;"
"height: 30px;"
"margin: 10px;"
"margin-left: auto;"
"margin-right: auto;"
"cursor: pointer;"
"}"
".button_off{"
"background-color:#FFF;"
"color: #555;"
"}"
".button_on{"
"background-color:#2C5;"
"color: #fff;"
"}"
"</style>"
"</head>" ));
We then proceed to display the sensor data and create the buttons for each pin that has a relay.
buttons.concat(button(i));
client.println(buttons);
client.println("</body>");
MEGAESP_01.ino - button
We create a button with the appearance and action that corresponds to the current state of the relay.
MEGAESP_01.ino - sensors
We return the action that the client wants to execute (on / off), as well as the value (number of the relay) of the
action that will be executed.
MEGAESP_01.ino - getStringBetween
We continue, this time, returning the string that lies between the first “start” character and the first “end” character.
We return the memory address of the "start" character. If it does not find the character, it goes to the next one, until
it reaches the "end" character or the end of the string.
return str;
}
MEGAESP_01.ino - execute
Finally, executed in the action next to the value (number of the relay), we observe if it is one of the two actions that
we expect (On or Off). The relays are numbered from 1, but the array starts from 0. Then we draw 1.
The pin number will be the index plus the pin number where the relays start. The relays must be in sequence from
the starting pin.
" "body{" "text-align: center;" "font-family: sans-serif;" "font-size: 14px;" "}" "p{" "color:#555;" "font-size: 12px;" "}"
".button{" "outline: none;" "display: block;" "border: 1px solid #555;" "border-radius:18px;" "width: 150px;" "height:
30px;" "margin: 10px;" "margin-left: auto;" "margin-right: auto;" "cursor: pointer;" "}" ".button_off{" "background-
color:#FFF;" "color: #555;" "}" ".button_on{" "background-color:#2C5;" "color: #fff;" "}" "
INO