Lab 11 - WiFi and Internet with Arduino
In questa pagina 5
Builds on Lab 10 - Arduino Standalone and Serial ProtocolsLaboratory 10 builds a standalone ATMega328P on a breadboard (16 MHz crystal, bootloader via ArduinoISP, or 8 MHz internal clock) and introduces the synchronous serial protocols I2C and SPI used to connect Arduino boards and peripherals.Lab 10 - Arduino Standalone and Serial Protocols → (serial links) and on the WiFi class of Data Transmission Technologies - Wired, Wireless, LAN and WANSurvey of the data transmission technologies used to connect measurement and IoT nodes, from local ones (RFID, NFC, Bluetooth, WiFi, ZigBee) to wide-area ones (LoRa, SigFox, GSM/GPRS, UMTS, LTE, LTE-M, NB-IoT, 5G), with frequencies, ranges and bit rates.Data Transmission Technologies - Wired, Wireless, LAN and WAN →; board: Arduino PlatformArduino is a family of open single-board microcontroller boards built on Atmel AVR chips (UNO, Mega, Micro), extended with stackable shields and programmed through its own IDE.Arduino Platform →.
ESP8266-01 module: pinout
| Pin number | Pin name | Alternate name | Normally used for | Alternate purpose |
|---|---|---|---|---|
| 1 | Ground | - | connected to the ground of the circuit | - |
| 2 | TX | GPIO-1 | connected to the Rx pin of the programmer/microcontroller to upload the program | can act as a general-purpose input/output pin when not used as TX |
| 3 | GPIO-2 | - | general-purpose input/output pin | - |
| 4 | CH_EN | - | chip enable, active high | - |
| 5 | GPIO-0 | Flash | general-purpose input/output pin | takes the module into serial programming mode when held low during start-up |
| 6 | Reset | - | resets the module | - |
| 7 | RX | GPIO-3 | general-purpose input/output pin | can act as a general-purpose input/output pin when not used as RX |
| 8 | Vcc | - | connect to +3.3 V only |
(The slide also shows photographs of the module with the label "ESP8266MOD, AI-Thinker, 802.11b/g/n, 2.4 GHz" and the 2 x 4 pin header with the signals RX, VCC, GPIO0, Reset, CH_PD, GPIO2, TX, GND.)
Connections to the Arduino
- ESP8266 TX -> Arduino RX (the
SoftwareSerialRX pin). - ESP8266 RX -> Arduino TX (the
SoftwareSerialTX pin). - ESP8266 CH_PD -> 3.3 V.
- ESP8266 VCC -> 3.3 V.
- ESP8266 GND -> GND.
- Resistors as a voltage divider to bring the 5 V logic level of the Arduino to the 3.3 V logic level of the ESP: in the figure a 1 kOhm resistor and a 2 kOhm resistor are used on the line going to the ESP RX pin (the Arduino TX pin feeds the 1 kOhm resistor, the junction of the two resistors goes to the ESP RX pin, and the 2 kOhm resistor goes to GND). Check with the divider formula (computed here, not on the slide): . The ESP TX output can go directly to the Arduino RX pin.
Power supply problem
- The 3.3 V output of the Arduino is not optimal: it does not provide enough current, because the ESP can consume up to 200 mA when turned on.
- A voltage regulator fed from the 5 V pin should be used. The figure uses an LM1117-3.3 regulator on the breadboard with a 100 uF electrolytic capacitor on the ESP supply.
- Final scheme (left figure): regulator plus capacitors (a 0.1 uF ceramic, a 220 uF electrolytic and the 100 uF one are drawn; the slide says a slightly different capacitor can also be used, it is needed for filtering electronic noise) and the 2000 ohm / 1000 ohm divider on the line to the ESP RX; the serial lines go to Arduino pins labelled TX and RX in the figure.
- An equivalent way using diodes is shown on the right (two 1N4007 diodes drawn in the supply path, plus the 220 uF capacitor), instead of the regulator.
Troubleshooting: baud rate
- ESP modules often have a default baud rate of 115200 bps, which is the speed limit of
SoftwareSerialin reception: the output is corrupted or altered and programming the module does not succeed. - A lower baud rate can be set as follows:
- use the sketch Examples -> Communication -> SerialPassthrough; before the
setup()scope declare theSoftwareSerialas usual:
- use the sketch Examples -> Communication -> SerialPassthrough; before the
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX- once the sketch is uploaded, change the ESP baud rate by sending through the serial monitor the following AT command. First send only
AT: if everything is fine the ESP replies OK.
AT+UART_DEF=9600,8,1,0,0The serial monitor must be set to line ending "Both NL & CR" (the slide shows the Italian menu "Entrambi (NL & CR)") and 115200 baud.
(The parameters of AT+UART_DEF are baud rate, data bits, stop bits, parity and flow control as written by the command; the slide does not explain them.)
WiFiEsp library
- Source: https://github.com/bportaluri/WiFiEsp or, better, from the IDE's Library manager by searching for WiFiEsp.
- Open the examples folder of the library (File -> Examples -> WiFiEsp, which lists ConnectWPA, ScanNetworks, UdpNTPClient, UdpSendReceive, WebClient, WebClientRepeating, WebClientSSL, WebServer, WebServerAP, WebServerLed) and test:
| Example | What it does |
|---|---|
| ScanNetworks | shows in the serial monitor the available WiFi networks and their information |
| WebClient | connects to a website to download some information (here the Arduino logo) |
| UdpNTPClient | retrieves the time from a Network Time Protocol time server |
| WebServer | connects to the network, sets up a page server at a given IP address, posts the value of an analog pin |
| WebServerLed | turns a LED on and off from a web page |
(The WebClient and WebServer examples are TCP-level exchanges; see Socket ProgrammingA socket is a communication endpoint identified like a file descriptor; a TCP server runs socket, setsockopt, bind, listen, accept, read/write, close, while the client runs socket, connect, read/write, close.Socket Programming → for the same client/server concept in code.)
Posting data in the cloud: dweet.io
The service dweet.io stores "dweets" (small data messages) sent by a "thing". The Arduino sends the value of an analog sensor with an HTTP GET request every 10 seconds, and the values can be retrieved with the two URLs given on the slide:
- latest value:
https://dweet.io/get/latest/dweet/for/Nomeboard - all stored values:
https://dweet.io/get/dweets/for/Nomeboard
("Nomeboard" is the placeholder name of the thing in the example: "board name".)
Sketch, as shown over two slides (declarations first, then loop() and the request function). The setup() function is not shown on the slides, so it is not reproduced here; note that SSID and password are empty strings to be filled in.
#include "WiFiEsp.h"
// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(10, 11); // RX, TX
#endif
char ssid[] = ""; // your network SSID (name)
char pass[] = ""; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
char server[] = "dweet.io";
unsigned long lastConnectionTime=0;
const unsigned long postingInterval=10L*1000;
char * thingName = "Nomeboard";
// Initialize the Ethernet client object
WiFiEspClient client;void loop()
{
// Read incoming data
while (client.available()) {
char c = client.read();
Serial.write(c);
}
// Send request at regular intervals
if (millis() - lastConnectionTime > postingInterval) {
// Reading from analog sensor
int sensorValue = analogRead(A0);
// Send request
httpRequest(sensorValue);
}
}void httpRequest(int sensorValue) {
// Close existing connection
client.stop();
// Connect & send request
if (client.connect(server, 80)) {
Serial.println("connecting...");
// Prepare request
String request = "GET /dweet/for/";
request += String(thingName);
request += "?light=" + String(sensorValue);
request += " HTTP/1.1";
// Send the HTTP request:
client.println(request);
client.println("Host: dweet.io");
client.println("User-Agent: ArduinoWiFi/1.1");
client.println("Connection: close");
client.println();
// Note the time that the connection was made:
lastConnectionTime = millis();
}
else {
// if you couldn't make a connection:
Serial.println("connection failed");
}
}How it works (from the listing):
postingInterval = 10L*1000ms: one request every 10 s, timed withmillis()againstlastConnectionTime(no blockingdelay).- In
loop()the characters that arrive from the server are copied to the serial monitor (client.available(),client.read(),Serial.write()). httpRequest()closes any previous connection, opens a TCP connection todweet.ioon port 80, and sends an HTTP/1.1 request: first lineGET /dweet/for/Nomeboard?light=<value> HTTP/1.1, then the headersHost: dweet.io,User-Agent: ArduinoWiFi/1.1andConnection: close, and an empty line that ends the header.- The sensor value (here
analogRead(A0), e.g. a photoresistor as in Lab 8 - Analog Output and Sensors with ArduinoLaboratory 8 covers digital input modes, PWM analog output with analogWrite (LED fading), the 10-bit analogRead input, the map and constrain functions, trimmer and photoresistor exercises, the LM35 temperature sensor and two additional exercises (hysteresis and potentiometer-controlled data logger).Lab 8 - Analog Output and Sensors with Arduino →) travels in the query string under the namelight.
Versione ripasso
- ESP8266-01 pins: 1 Ground; 2 TX (GPIO-1); 3 GPIO-2; 4 CH_EN (chip enable, active high); 5 GPIO-0 (held low at start-up = serial programming mode); 6 Reset; 7 RX (GPIO-3); 8 Vcc, +3.3 V only.
- Connections to the Arduino:
- ESP TX goes to Arduino RX (SoftwareSerial RX); ESP RX goes to Arduino TX through a divider: 1 kOhm and 2 kOhm, junction on ESP RX, 2 kOhm to GND. Check: (computed here, not on the slide);
- CH_PD and VCC to 3.3 V; GND to GND.
- Power: the Arduino 3.3 V pin cannot supply the ESP, which draws up to 200 mA when on. Use a regulator fed from 5 V (LM1117-3.3) with a 100 uF electrolytic and a 0.1 uF ceramic capacitor, to filter noise. The slide also shows an equivalent version with two 1N4007 diodes and a 220 uF capacitor.
- Baud rate fix: the ESP default of 115200 bps is too fast for SoftwareSerial reception, so the output is corrupted.
- Upload Examples -> Communication -> SerialPassthrough, with
SoftwareSerial Serial1(6, 7); // RX, TXdeclared beforesetup(). - In the serial monitor ("Both NL & CR", 115200 baud) send
AT(the ESP answers OK), then:
- Upload Examples -> Communication -> SerialPassthrough, with
AT+UART_DEF=9600,8,1,0,0- WiFiEsp library: install it from the Library manager. Examples to test:
- ScanNetworks: lists the WiFi networks;
- WebClient: downloads a page;
- UdpNTPClient: time from a Network Time Protocol server;
- WebServer and WebServerLed: a page showing an analog pin, or switching a LED.
- TCP-level exchanges, see Socket ProgrammingA socket is a communication endpoint identified like a file descriptor; a TCP server runs socket, setsockopt, bind, listen, accept, read/write, close, while the client runs socket, connect, read/write, close.Socket Programming →.
- dweet.io (cloud service for "dweets", small data messages): the Arduino sends an analog value with an HTTP GET every 10 seconds; read back at
/get/latest/dweet/for/<thing>or/get/dweets/for/<thing>.postingInterval = 10L*1000ms, timed withmillis()(no blockingdelay);httpRequest()closes the previous connection, thenclient.connect(server, 80)and sends the request.
String request = "GET /dweet/for/";
request += String(thingName);
request += "?light=" + String(sensorValue);
request += " HTTP/1.1";- Then the headers
Host: dweet.io,User-Agent: ArduinoWiFi/1.1,Connection: close, and a blank line. - The sensor value, e.g.
analogRead(A0)from a photoresistor (Lab 8 - Analog Output and Sensors with ArduinoLaboratory 8 covers digital input modes, PWM analog output with analogWrite (LED fading), the 10-bit analogRead input, the map and constrain functions, trimmer and photoresistor exercises, the LM35 temperature sensor and two additional exercises (hysteresis and potentiometer-controlled data logger).Lab 8 - Analog Output and Sensors with Arduino →), travels as thelightparameter. - The slide shows no
setup(); SSID and password are empty strings to be filled in. - Typical mistakes:
- powering the ESP from 5 V or from the weak Arduino 3.3 V pin;
- feeding 5 V logic straight into the ESP RX;
- leaving 115200 baud on SoftwareSerial;
- empty SSID or password;
- forgetting the blank
client.println()that ends the HTTP header.