ESP32WIFI LOT Kit V1.0
ESP32WIFI LOT Kit V1.0
202102025V1.0
1
List
2
3
4
5
Preface
Lesson 0 Installing the ESP32 Board in Arduino IDE............................................................... 7
Lesson 1 Telegram: Control ESP32 Outputs ........................................................................16
Lesson 2 ESP32: Control Outputs with Web Server and a Physical Button Simultaneously ......... 38
6
Lesson 0 Installing the ESP32 Board in Arduino IDE
There’s an add-on for the Arduino IDE that allows you to program the ESP32 using
the Arduino IDE and its programming language. In this tutorial we’ll show you how to
install the ESP32 board in Arduino IDE whether you’re using Windows, Mac OS X or
Linux.
To install the ESP32 board in your Arduino IDE, follow these next instructions:
7
2 、 Enter https://dl.espressif.com/dl/package_esp32_index.json into the “Additional
Board Manager URLs” field as shown in the figure below. Then, click the “OK” button:
Note: if you already have the ESP8266 boards URL, you can separate the URLs with
a comma as follows:
https://dl.espressif.com/dl/package_esp32_index.json,
http://arduino.esp8266.com/stable/package_esp8266com_index.json
8
3、Open the Boards Manager. Go to Tools > Board > Boards Manager…
4、Search for ESP32 and press install button for the “ESP32 by Espressif Systems“:
9
5、That’s it. It should be installed after a few seconds.
10
2. Select the Port (if you don’t see the COM Port in your Arduino IDE, you need to
install the CP210x USB to UART Bridge VCP Drivers):
3、Open the following example under File > Examples > WiFi (ESP32) > WiFiScan
11
4、A new sketch opens in your Arduino IDE:
5、Press the Upload button in the Arduino IDE. Wait a few seconds while the code
compiles and uploads to your board.
12
7、Open the Arduino IDE Serial Monitor at a baud rate of 115200:
8. Press the ESP32 on-board Enable button and you should see the networks
available near your ESP32:
Troubleshooting
If you try to upload a new sketch to your ESP32 and you get this error message “A
fatal error occurred: Failed to connect to ESP32: Timed out… Connecting…“. It means
that your ESP32 is not in flashing/uploading mode.
Having the right board name and COM por selected, follow these steps:
13
Press the “Upload” button in the Arduino IDE to upload your sketch:
After you see the “Connecting….” message in your Arduino IDE, release the
finger from the “BOOT” button:
14
ESP32 Peripherals
The ESP32 peripherals include:
18 Analog-to-Digital Converter (ADC) channels
3 SPI interfaces
3 UART interfaces
2 I2C interfaces
16 PWM output channels
2 Digital-to-Analog Converters (DAC)
2 I2S interfaces
10 Capacitive sensing GPIOs
The ADC (analog to digital converter) and DAC (digital to analog converter) features
are assigned to specific static pins. However, you can decide which pins are UART, I2C,
SPI, PWM, etc – you just need to assign them in the code. This is possible due to the
ESP32 chip’s multiplexing feature.
Although you can define the pins properties on the software, there are pins assigned
by default as shown in the following figure .
15
Lesson 1 Telegram: Control ESP32 Outputs
This guide shows how to control the ESP32 or ESP8266 NodeMCU GPIOs
an LED, but you can control any other output. You just need to send a
message to your Telegram Bot to set your outputs HIGH or LOW. The ESP
Project Overview:
In this tutorial we’ll build a simple project that allows you to control
ESP32 or ESP8266 NodeMCU GPIOs using Telegram. You can also control
a relay module.
16
You’ll create a Telegram bot for your ESP32/ESP8266 board;
When you send the message /led_on to the bot, the ESP board receives the message
Similarly, when you send the message /led_off, it turns GPIO 2 off;
Additionally, you can also send the message /state to request the current GPIO state.
When the ESP receives that message, the bot responds with the current GPIO state;
You can send the /start message to receive a welcome message with the commands
This is a simple project, but shows how you can use Telegram in your IoT and Home
Automation projects. The idea is to apply the concepts learned in your own projects.
17
Introducing Telegram:
You can easily install it in your smartphone (Android and iPhone) or computer (PC,
Mac and Linux). It is free and without any ads. Telegram allows you to create bots
“Bots are third-party applications that run inside Telegram. Users can interact with
bots by sending them messages, commands and inline requests. You control your
The ESP32/ESP8266 will interact with the Telegram bot to receive and handle the
messages, and send responses. In this tutorial you’ll learn how to use Telegram to
send messages to your bot to control the ESP outputs from anywhere (you just need
18
Open Telegram and follow the next steps to create a Telegram Bot. First,
search for “botfather” and click the BotFather as shown below. Or open
The following window should open and you’ll be prompted to click the start button.
19
Type /newbot and follow the instructions to create your bot. Give it a name and
username.
If your bot is successfully created, you’ll receive a message with a link to access the
bot and the bot token. Save the bot token because you’ll need it so that the
ESP32/ESP8266 can interact with the bot.
20
Get Your Telegram User ID
Anyone that knows your bot username can interact with it. To make sure that we
ignore messages that are not from our Telegram account (or any authorized users),
you can get your Telegram User ID. Then, when your telegram bot receives a message,
the ESP can check whether the sender ID corresponds to your User ID and handle the
In your Telegram account, search for “IDBot” or open this link t.me/myidbot in your
smartphone.
Start a conversation with that bot and type /getid. You will get a reply back with your
user ID. Save that user ID, because you’ll need it later in this tutorial.
21
Universal Telegram Bot Library :
To interact with the Telegram bot, we’ll use the Universal Telegram Bot
Library created by Brian Lough that provides an easy interface for the Telegram Bot
API.
Follow the next steps to install the latest release of the library.
Click here to download the Universal Arduino Telegram Bot library.
Go to Sketch > Include Library > Add.ZIP Library...
Add the library you’ve just downloaded.
And that’s it. The library is installed.
Important: don’t install the library through the Arduino Library Manager because
it might install a deprecated version.
For all the details about the library, take a look at the Universal Arduino Telegram Bot
Library GitHub page.
ArduinoJson Library
You also have to install the ArduinoJson library. Follow the next steps to install the
library.
Go to Skech > Include Library > Manage Libraries.
Search for “ArduinoJson”.
Install the library.
We’re using ArduinoJson library version 6.15.2.
22
Control Outputs using Telegram – ESP32/ESP8266 Sketch:
work for you, you need to insert your network credentials (SSID and
password), the Telegram Bot Token and your Telegram User ID.
Code:
#ifdef ESP32
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif
#include <WiFiClientSecure.h>
https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
#include <ArduinoJson.h>
23
#define BOTtoken "xxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
// Also note that you need to click "start" on a bot before it can
// message you
WiFiClientSecure client;
Serial.println("handleNewMessages");
Serial.println(String(numNewMessages));
24
for (int i=0; i<numNewMessages; i++) {
if (chat_id != CHAT_ID){
continue;
Serial.println(text);
if (text == "/start") {
outputs.\n\n";
25
bot.sendMessage(chat_id, welcome, "");
if (text == "/led_on") {
ledState = HIGH;
digitalWrite(ledPin, ledState);
if (text == "/led_off") {
ledState = LOW;
digitalWrite(ledPin, ledState);
if (text == "/state") {
if (digitalRead(ledPin)){
else{
26
}
void setup() {
Serial.begin(115200);
#ifdef ESP32
client.setInsecure();
#endif
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
// Connect to Wi-Fi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
delay(1000);
Serial.println("Connecting to WiFi..");
27
Serial.println(WiFi.localIP());
void loop() {
+ 2);
while(numNewMessages) {
Serial.println("got response");
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received
+ 2);
lastTimeBotRan = millis();
28
How the Code Works:
This sections explain how the code works.
Start by importing the required libraries.
#ifdef ESP32
#include <WiFi.h>#else
#include <ESP8266WiFi.h>
#endif#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
Network Credentials
Insert your network credentials in the following variables.
Define Output
Set the GPIO you want to control. In our case, we’ll control GPIO 2 (built-in LED) and
its state is LOW by default.
const int ledPin = 2;
Note: if you’re using an ESP8266, the built-in LED works with inverted logic. So, you
should send a LOW signal to turn the LED on and a HIGH signal to turn it off.
29
Telegram User ID
Insert your chat ID. The one you’ve got from the IDBot.
WiFiClientSecure client;
The botRequestDelay and lastTimeBotRan are used to check for new Telegram
messages every x number of seconds. In this case, the code will check for new
messages every second (1000 milliseconds). You can change that delay time in the
botRequestDelay variable.
handleNewMessages()
The handleNewMessages() function handles what happens when new messages
arrive.
Serial.println("handleNewMessages");
Serial.println(String(numNewMessages));
30
Get the chat ID for that particular message and store it in the chat_id variable. The
chat ID allows us to identify who sent the message.
String chat_id = String(bot.messages[i].chat_id);
If the chat_id is different from your chat ID (CHAT_ID), it means that someone (that is
not you) has sent a message to your bot. If that’s the case, ignore the message and
wait for the next message.
if (chat_id != CHAT_ID) {
continue;}
Otherwise, it means that the message was sent from a valid user, so we’ll save it in
the text variable and check its content.
Serial.println(text);
If it receives the /start message, we’ll send the valid commands to control the
ESP32/ESP8266. This is useful if you happen to forget what are the commands to
control your board.
if (text == "/start") {
31
welcome += "/led_off to turn GPIO OFF \n";
Sending a message to the bot is very simply. You just need to use the sendMessage()
method on the bot object and pass as arguments the recipient’s chat ID, the message,
and the parse mode.
In our particular example, we’ll send the message to the ID stored on the chat_id
variable (that corresponds to the person who’ve sent the message) and send the
message saved on the welcome variable.
If it receives the /led_on message, turn the LED on and send a message confirming
we’ve received the message. Also, update the ledState variable with the new state.
if (text == "/led_on") {
ledState = HIGH;
digitalWrite(ledPin, ledState);}
if (text == "/led_off") {
ledState = LOW;
digitalWrite(ledPin, ledState);}
32
Note: if you’re using an ESP8266, the built-in LED works with inverted logic. So, you
should send a LOW signal to turn the LED on and a HIGH signal to turn it off.
Finally, if the received message is /state, check the current GPIO state and send a
message accordingly.
if (text == "/state") {
if (digitalRead(ledPin)){
else{
}}
setup()
If you’re using the ESP8266, you need to use the following line:
#ifdef ESP8266
client.setInsecure();
#endif
In the library examples for the ESP8266 they say: “This is the simplest way of getting
this working. If you are passing sensitive information, or controlling something
important, please either use certStore or at least client.setFingerPrint“.
Set the LED as an output and set it to LOW when the ESP first starts:
33
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
Init Wi-Fi
Initialize Wi-Fi and connect the ESP to your local network with the SSID and password
defined earlier.
WiFi.mode(WIFI_STA);
delay(1000);
Serial.println("Connecting to WiFi..");}
loop()
In the loop(), check for new messages every second.
void loop() {
while(numNewMessages) {
Serial.println("got response");
handleNewMessages(numNewMessages);
lastTimeBotRan = millis();
}}
34
When a new message arrives, call the handleNewMessages function.
while(numNewMessages) {
Serial.println("got response");
handleNewMessages(numNewMessages);
Demonstration:
Upload the code to your ESP32 or ESP8266 board. Don’t forget to go to Tools > Board
and select the board you’re using. Go to Tools > Port and select the COM port your
board is connected to.
After uploading the code, press the ESP32/ESP8266 on-board EN/RST button so that
it starts running the code. Then, you can open the Serial Monitor to check what’s
happening in the background.
35
Go to your Telegram account and open a conversation with your bot. Send the
following commands and see the bot responding:
36
The on-board LED should turn on and turn off accordingly (the ESP8266 on-board
LED works in reverse, it’s off when you send /led_on and on when you send
/led_off).
At the same time, on the Serial Monitor you should see that the ESP is receiving the
messages.
37
Lesson2 ESP32: Control Outputs with Web Server and a
Physical Button Simultaneously
This tutorial shows how to control the ESP32 outputs using a web server and a
physical button simultaneously. The output state is updated on the web page
whether it is changed via physical button or web server.
Project Overview:
Let’s take a quick look at how the project works.
38
The ESP32 hosts a web server that allows you to control the state of an
output;
The current output state is displayed on the web server;
The ESP is also connected to a physical pushbutton that controls the same
output;
If you change the output state using the physical puhsbutton, its current state
is also updated on the web server.
In summary, this project allows you to control the same output using a web server
and a push button simultaneously. Whenever the output state changes, the web
server is updated.
Parts Required
Here’s a list of the parts to you need to build the circuit:
ESP32 Schematic
Note: The pin interface of the board should be checked with the actual
39
Installing Libraries – Async Web Server:
To build the web server you need to install the following libraries:
ESP32: install the ESPAsyncWebServer and the AsyncTCP libraries.
ESP8266: install the ESPAsyncWebServer and the ESPAsyncTCP libraries.
These libraries aren’t available to install through the Arduino Library Manager, so you
need to copy the library files to the Arduino Installation Libraries folder. Alternatively,
in your Arduino IDE, you can go to Sketch > Include Library > Add .zip Library and
select the libraries you’ve just downloaded.
Code:
// Import required libraries#ifdef ESP32
#include <WiFi.h>
#include <AsyncTCP.h>#else
#include <ESP8266WiFi.h>
// the following variables are unsigned longs because the time, measured
in// milliseconds, will quickly become a bigger number than can be stored
in an int.unsigned long lastDebounceTime = 0; // the last time the output
pin was toggledunsigned long debounceDelay = 50; // the debounce time;
increase if the output flickers
40
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
<style>
h2 {font-size: 3.0rem;}
p {font-size: 3.0rem;}
</style></head><body>
%BUTTONPLACEHOLDER%<script>function toggleCheckbox(element) {
41
var xhr = new XMLHttpRequest();
xhr.send();}
setInterval(function ( ) {
xhttp.onreadystatechange = function() {
var inputChecked;
var outputStateM;
inputChecked = true;
outputStateM = "On";
else {
inputChecked = false;
outputStateM = "Off";
document.getElementById("output").checked = inputChecked;
document.getElementById("outputState").innerHTML = outputStateM;
};
42
xhttp.send();}, 1000 ) ;</script></body></html>)rawliteral";
//Serial.println(var);
if(var == "BUTTONPLACEHOLDER"){
return buttons;
return String();}
String outputState(){
if(digitalRead(output)){
return "checked";
else {
return "";
return "";}
void setup(){
43
// Serial port for debugging purposes
Serial.begin(115200);
pinMode(output, OUTPUT);
digitalWrite(output, LOW);
pinMode(buttonPin, INPUT);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
delay(1000);
Serial.println("Connecting to WiFi..");
Serial.println(WiFi.localIP());
});
44
server.on("/update", HTTP_GET, [] (AsyncWebServerRequest *request) {
String inputMessage;
String inputParam;
if (request->hasParam(PARAM_INPUT_1)) {
inputMessage = request->getParam(PARAM_INPUT_1)->value();
inputParam = PARAM_INPUT_1;
digitalWrite(output, inputMessage.toInt());
ledState = !ledState;
else {
inputParam = "none";
Serial.println(inputMessage);
});
request->send(200, "text/plain",
String(digitalRead(output)).c_str());
});
45
// Start server
server.begin();}
void loop() {
// (i.e. the input went from LOW to HIGH), and you've waited long enough
if (reading != lastButtonState) {
lastDebounceTime = millis();
// whatever the reading is at, it's been there for longer than the
debounce
if (reading != buttonState) {
46
buttonState = reading;
if (buttonState == HIGH) {
ledState = !ledState;
digitalWrite(output, ledState);
// save the reading. Next time through the loop, it'll be the
lastButtonState:
lastButtonState = reading;}
You only need to enter the network credentials (SSID and password), and
the web server will work immediately. This code is compatible with
ESP32 and ESP8266 boards and controls GPIO 2-you can change the code
47
How the Code Works
We’ve already explained in great details how web servers like this work
Network Credentials
following lines:
The ledState variable holds the LED output state. For default, when the
48
Button (web server)
We didn’t include the HTML to create the button on the the index_html
the current LED state that can also be changed with the pushbutton.
that will be replaced with HTML text to create the button later on the
%BUTTONPLACEHOLDER%
processor()
with actual values. First, it checks whether the HTML texts contains any
placeholders %BUTTONPLACEHOLDER%.
if(var == "BUTTONPLACEHOLDER"){
Then, call the outputState() function that returns the current output
After that, use that value to create the HTML text to display the button
49
buttons+= "<h4>Output - GPIO 2 - State <span
id=\"outputState\"><span></h4><label class=\"switch\"><input
type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"output\" " +
outputStateValue + "><span class=\"slider\"></span></label>";
When you press the button, the toggleCheckbox() function is called. This
function will make a request on different URLs to turn the LED on or off.
function toggleCheckbox(element) {
xhr.send();}
To keep the output state updated on the web server, we call the
following function that makes a new request on the /state URL every
second.
50
setInterval(function ( ) {
xhttp.onreadystatechange = function() {
var inputChecked;
var outputStateM;
inputChecked = true;
outputStateM = "On";
else {
inputChecked = false;
outputStateM = "Off";
document.getElementById("output").checked = inputChecked;
document.getElementById("outputState").innerHTML = outputStateM;
};
xhttp.send();}, 1000 ) ;
51
Handle Requests
When a request is received on the root / URL, we send the HTML page as
accordingly.
server.on("/update", HTTP_GET, [] (AsyncWebServerRequest *request) {
String inputMessage;
String inputParam;
if (request->hasParam(PARAM_INPUT_1)) {
inputMessage = request->getParam(PARAM_INPUT_1)->value();
inputParam = PARAM_INPUT_1;
digitalWrite(output, inputMessage.toInt());
ledState = !ledState;
else {
52
inputMessage = "No message sent";
inputParam = "none";
Serial.println(inputMessage);
output state:
server.on("/state", HTTP_GET, [] (AsyncWebServerRequest *request) {
request->send(200, "text/plain",
String(digitalRead(output)).c_str());});
loop()
In the loop(), we debounce the pushbutton and turn the LED on or off
Demonstration
Then, open the Serial Monitor at a baud rate of 115200. Press the
53
Open a browser on your local network, and type the ESP IP address. You
You can toggle the button on the web server to turn the LED on.
54
You can also control the same LED with the physical pushbutton. Its state
Wrapping Up
with a web server and a physical button at the same time. The output
state is always updated whether it is changed via web server or with the
physical button.
55
Lesson 3 Telegram: ESP32 Motion Detection with Notifications
This tutorial shows how to send a notification to your Telegram account when the
ESP32 detects motion. As long as you can use your smartphone to access the
Internet, you will receive notifications no matter where you are. The ESP board will
be programmed using the Arduino IDE.
Project Overview:
This tutorial explains how to get notifications in your Telegram account when the
ESP32 detects motion.
56
An overview of how the project works:
You will create a Telegram bot for ESP32.
ESP32 is connected to the PIR motion sensor.
When the sensor detects movement, the ESP32 will send a warning message to your Telegram
account.
Whenever motion is detected, you will be notified in your Telegram account.
This is a simple project, but shows how to use Telegram in IoT and home automation projects.
The idea is to apply the concepts learned in your own project to the project.
The introduction about telegram has been described in the first section of the project, and the
specific operations can be viewed by referring to the first section of the course by turning the
page.
In this example, we connect the PIR motion sensor data pin to GPIO 27. You can use any other
suitable GPIO.
57
Telegram motion detection with notification-ESP32 code:
Whenever motion is detected, the following code will use your Telegram
make this sketch work for you, you need to insert network credentials
(SSID and password), Telegram Bot token and Telegram user ID.
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
WiFiClientSecure client;
//Serial.println("MOTION DETECTED!!!");
Serial.begin(115200);
58
// PIR Motion Sensor mode INPUT_PULLUP
pinMode(motionSensor, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(motionSensor),
detectsMovement, RISING);
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print(".");
delay(500);
Serial.println("");
Serial.println("WiFi connected");
Serial.println(WiFi.localIP());
if(motionDetected){
Serial.println("Motion Detected");
motionDetected = false;
59
}}
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
Network credentials
Insert the Telegram Bot token you got from Botfather into the BOT token.
Telegram User ID
Insert your chat ID. The one you got from IDBot.
WiFiClientSecure client;
Create a bot and use the token and client defined earlier.
60
Motion sensor:
This motionDetected Boolean variable is used to indicate whether motion is detected. Set to the
wrong default.
bool motionDetected = false;
detectorMovement()
The detectsmovement() function is a callback function that will be executed when
motion is detected. In this case, it just changes the state motionDetected to true.
//Serial.println("MOTION DETECTED!!!");
motionDetected = true;}
Setup()
Serial.begin(115200);
Set the PIR motion sensor to interrupt and set the detectorMovement() as a callback
function (when motion is detected, this function will be executed):
61
attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement,
RISING);
Initialize Wi-Fi
Initialize Wi-Fi and use the previously defined SSID and password to connect ESP32
to your local network.
WiFi.mode(WIFI_STA);
delay(1000);
Serial.println("Connecting to WiFi..");}
Loop()
void loop() {
if(motionDetected){
Sending a message to the robot is very simple. You only need to use the method of
sending a message () Robot object, and pass the recipient's chat ID, message and
parsing mode as parameters.
Finally, after sending the message, setting motionDetected can become wrong, so it
can detect motion again.
motionDetected = false;
62
This is pretty much how the code works.
Example:
Upload the code to your ESP32 development board. Don't forget to go to "Tools">
"Development Board" and select the development board you are using. Go to
"Tools"> "Port", and then select the COM port your motherboard is connected to.
After uploading the code, please press the onboard EN/RST button of ESP32 to make
it start to run the code. You can then open the serial monitor to check what is
happening in the background.
When your motherboard boots up for the first time, it will send a message to your
Telegram account: "Boot has been activated". Then, move your hand to the front of
the PIR motion sensor and check if you have received a notification that motion has
been detected.
At the same time, this is what you should get on the serial monitor.
63
Lesson 4 Use ESP32 with DHT11 temperature and humidity sensor
module
This tutorial introduces how to use DHT11 temperature and humidity sensor with ESP32 using
Arduino IDE. We will quickly introduce these sensors, pinouts, wiring diagrams, and finally the
Arduino sketches.
schematic diagram:
Connect the DHT11 sensor to the ESP32 development board as shown in the figure
below.
64
In this example, we connect the DHT data pin to GPIO 4. However, you
Installing Libraries:
To read from the DHT sensor, we’ll use the DHT library from Adafruit. To use this
library you also need to install the Adafruit Unified Sensor library. Follow the next
steps to install those libraries.
Open your Arduino IDE and go to Sketch > Include Library > Manage Libraries. The
Library Manager should open.
Search for “DHT” on the Search box and install the DHT library from Adafruit.
After installing the DHT library from Adafruit, type “Adafruit Unified Sensor” in the search box.
Scroll all the way down to find the library and install it.
65
After installing the libraries, restart your Arduino IDE.
dht.begin();
The loop() starts with a 2000 ms (2 seconds) delay, because the DHT22
delay(2000);
66
float variables h, t, and f to save the humidity, temperature in Celsius and
as shown below:
float t = dht.readTemperature();
float f = dht.readTemperature(true);
return;
After getting the humidity and temperature, the library has a method
that computes the heat index. You can get the heat index both in Celsius
(isFahreheit = false)
67
Finally, print all the readings on the Serial Monitor with the following
commands:
Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(hic);
Serial.print(F("°C "));
Serial.print(hif);
Serial.println(F("°F"));
Demonstration
Upload the code to your ESP32 board. Make sure you have the right board and COM
port selected in your Arduino IDE settings.
After uploading the code, open the Serial Monitor at a baud rate of 9600. You should
get the latest temperature and humidity readings in the Serial Monitor every two
seconds.
68
Lesson 5 : Using esp32 to control ssd1306 OLED display
This tutorial introduces how to use esp32 to control OLED display to display
characters. You can modify the code according to your own idea to make OLED
display what you want to display. The ESP board will use Arduino IDE for
programming.
69
Schematic diagram of the project:
For this project, you need to connect the OLED screen pins to the esp32 board. Follow the next
schematic.
n this example, we connect the pin data pin and clock pin of OLED screen to gpio21 and gpio22.
Note that wrong connection is not allowed. Wrong connection will cause OLED screen not to be
displayed.
70
#include <Wire.h> // Only needed for Arduino 1.6.5 and earlier
#include "SSD1306Wire.h" // legacy include: `#include "SSD1306.h"`
#include "OLEDDisplayUi.h"
#include "images.h"
The constructor of the class mentioned below receives the I2C address of the
device as the first parameter, namely, 0x3c. As the second and third
parameters, the constructor receives the number of SDA and SCL pins,
respectively. In our example, as shown in the diagram, we use pins 21 and 22
of esp32.
SSD1306Wire display(0x3c, 21, 22);
71
display->setFont(ArialMT_Plain_10);
display->drawString(0 + x, 34 + y, " and technology");
}
72
Lesson 6 How to use ESP32 to control a relay module
Introducing Relays
A relay is an electrically operated switch and like any other switch, it that can be turned on or off,
letting the current go through or not. It can be controlled with low voltages, like the 3.3V
provided by the ESP32 GPIOs and allows us to control high voltages like 12V, 24V or mains voltage
There are relay modules whose electromagnet can be powered by 5V and with 3.3V.
Both can be used with the ESP32 – you can either use the VIN pin (that provides 5V)
or the 3.3V pin.
Additionally, some come with built-in optocoupler that add an extra “layer” of
protection, optically isolating the ESP32 from the relay circuit.
73
On the left side, there are two sets of three sockets to connect high voltages, and the
pins on the right side (low-voltage) connect to the ESP32 GPIOs.
74
The relay module shown in the previous photo has two connectors, each with three
sockets: common (COM), Normally Closed (NC), and Normally Open (NO).
Control Pins
The low-voltage side has a set of four pins and a set of three pins. The first set
consists of VCC and GND to power up the module, and input 1 (IN1) and input 2 (IN2)
to control the bottom and top relays, respectively.
If your relay module only has one channel, you’ll have just one IN pin. If you have
four channels, you’ll have four IN pins, and so on.
The signal you send to the IN pins, determines whether the relay is active or not. The
relay is triggered when the input goes below about 2V. This means that you’ll have
the following scenarios:
75
Normally Closed configuration (NC):
HIGH signal – current is flowing
LOW signal – current is not flowing
Normally Open configuration (NO):
HIGH signal – current is not flowing
LOW signal – current in flowing
You should use a normally closed configuration when the current should be
flowing most of the times, and you only want to stop it occasionally.
Use a normally open configuration when you want the current to flow
occasionally (for example, turn on a lamp occasionally).
The second set of pins consists of GND, VCC, and JD-VCC pins. The JD-VCC pin powers
the electromagnet of the relay. Notice that the module has a jumper cap connecting
the VCC and JD-VCC pins; the one shown here is yellow, but yours may be a different
color.
With the jumper cap on, the VCC and JD-VCC pins are connected. That means the
relay electromagnet is directly powered from the ESP32 power pin, so the relay
module and the ESP32 circuits are not physically isolated from each other.
Without the jumper cap, you need to provide an independent power source to
power up the relay’s electromagnet through the JD-VCC pin. That configuration
physically isolates the relays from the ESP32 with the module’s built-in optocoupler,
which prevents damage to the ESP32 in case of electrical spikes.
76
Wiring a Relay Module to the ESP32
Connect the relay module to the ESP32 as shown in the following diagram. The diagram shows
wiring for a 2-channel relay module, wiring a different number of channels is similar.
In this example, we’re controlling a lamp. We just want to light up the lamp
occasionally, so it is better to use a normally open configuration.
The following code will light up your lamp for 10 seconds and turn it off for another
10 seconds.
77
const int relay = 26;
void setup() {
Serial.begin(115200);
pinMode(relay, OUTPUT);}
void loop() {
digitalWrite(relay, LOW);
Serial.println("Current Flowing");
delay(5000);
digitalWrite(relay, HIGH);
delay(5000);}
78
Control Multiple Relays with ESP32 Web Server
In this section, we’ve created a web server example that allows you to control as
many relays as you want via web server whether they are configured as normally
opened or as normally closed. You just need to change a few lines of code to define
the number of relays you want to control and the pin assignment.
To build this web server, we use the ESPAsyncWebServer library.
Installing the ESPAsyncWebServer library
Alternatively, in your Arduino IDE, you can go to Sketch > Include Library > Add .ZIP
library… and select the library you’ve just downloaded.
Code:
#include "WiFi.h"
#include "ESPAsyncWebServer.h"
79
#define RELAY_NO true
#define NUM_RELAYS 5
AsyncWebServer server(80);
<!DOCTYPE HTML><html>
<head>
<style>
80
h2 {font-size: 3.0rem;}
p {font-size: 3.0rem;}
.slider:before {position: absolute; content: ""; height: 52px; width: 52px; left:
8px; bottom: 8px; background-color: #fff; -webkit-transition: .4s; transition: .4s;
border-radius: 68px}
</style>
</head>
<body>
%BUTTONPLACEHOLDER%
<script>function toggleCheckbox(element) {
xhr.send();
}</script>
</body>
81
</html>
)rawliteral";
//Serial.println(var);
if(var == "BUTTONPLACEHOLDER"){
return buttons;
return String();
if(RELAY_NO){
if(digitalRead(relayGPIOs[numRelay-1])){
return "";
82
else {
return "checked";
else {
if(digitalRead(relayGPIOs[numRelay-1])){
return "checked";
else {
return "";
return "";
void setup(){
Serial.begin(115200);
// Set all relays to off when the program starts - if set to Normally Open (NO), the
relay is off when you set the relay to HIGH
pinMode(relayGPIOs[i-1], OUTPUT);
if(RELAY_NO){
83
digitalWrite(relayGPIOs[i-1], HIGH);
else{
digitalWrite(relayGPIOs[i-1], LOW);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
delay(1000);
Serial.println("Connecting to WiFi..");
Serial.println(WiFi.localIP());
});
84
server.on("/update", HTTP_GET, [] (AsyncWebServerRequest *request) {
String inputMessage;
String inputParam;
String inputMessage2;
String inputParam2;
if (request->hasParam(PARAM_INPUT_1) &
request->hasParam(PARAM_INPUT_2)) {
inputMessage = request->getParam(PARAM_INPUT_1)->value();
inputParam = PARAM_INPUT_1;
inputMessage2 = request->getParam(PARAM_INPUT_2)->value();
inputParam2 = PARAM_INPUT_2;
if(RELAY_NO){
Serial.print("NO ");
digitalWrite(relayGPIOs[inputMessage.toInt()-1], !inputMessage2.toInt());
else{
Serial.print("NC ");
digitalWrite(relayGPIOs[inputMessage.toInt()-1], inputMessage2.toInt());
else {
inputParam = "none";
85
}
Serial.println(inputMessage + inputMessage2);
});
// Start server
server.begin();
void loop() {
or normally closed (NC) configuration. Set the RELAY_NO variable to true for normally open os set
You can define the number of relays you want to control on the NUM_RELAYS variable. For
#define NUM_RELAYS 5
86
The number of relays set on the NUM_RELAYS variable needs to match
Network Credentials
Demonstration
After making the necessary changes, upload the code to your ESP32.
Open the Serial Monitor at a baud rate of 115200 and press the ESP32 EN button to get its IP
address.
87
LESSON 7 How to use IR obstacle avoidance sensor on ESP32
In this article, I will write how to use evasive infrared sensor on ESP32.
His sensor can be used to detect objects or obstacles ahead using reflected infrared
light.
The sensor has 2 main parts, namely IR transmitter and IR receiver. The infrared
transmitter is obligated to emit infrared light. When it hits an object, the infrared
light will be reflected. The function of the infrared receiver is to receive infrared
reflections.
When the infrared receiver receives the reflected infrared light, the output will be
"low". When the infrared receiver does not receive the reflected infrared light, the
output will be "high".
There are 2 LED indicators in the sensor. Power indicator light and output indicator
light. If the module is powered by current, the power indicator LED will light up. If
there is an object in front of the sensor or infrared receiver to receive infrared light
reflection, the output indicator LED will light up.
88
Use jumper wires to connect the IR sensor to the ESP32.
Infrared to ESP32
OUT ==> P2
Wiring diagram:
89
Code:
int pinIR = 2;
void setup(){
Serial.begin(115200);
pinMode(pinIR, INPUT);
Serial.println("Detect IR Sensor");
delay(1000);
void loop(){
if(IRstate == LOW){
Serial.println("Detected");
Serial.println("Not Detected");
delay(1000);
90
If you place an object in front of the sensor, the serial monitor will say "Detected".
if there is no object in front of the sensor, the monitor serial will say "Not Detected".
91
Lesson 8 How to use a photoresistor sensor on ESP32
In this lesson, I will show you how to interface ESP32 with a photoresistor (a type of
resistor whose resistance varies with the lighting level) and ESP32 to make the LED
light automatically. ESP32 is used to analyze the lighting level and turn the LED on or
off accordingly.
Photo resistors, also known as light dependent resistors (LDR), are light sensitive devices most
often used to indicate the presence or absence of light, or to measure the light intensity. In the
dark, their resistance is very high, sometimes up to 1MΩ, but when the LDR sensor is exposed to
light, the resistance drops dramatically, even down to a few ohms, depending on the light
intensity. LDRs have a sensitivity that varies with the wavelength of the light applied and are
nonlinear devices. They are used in many applications but are sometimes made obsolete by
other devices such as photodiodes and phototransistors. Some countries have banned LDRs
92
Light dependent resistor definition
Photo resistors are light sensitive resistors whose resistance decreases as the intensity of light
they are exposed to increases.
Characteristics
Types of photo resistors and working mechanisms
Based on the materials used, photo resistors can be divided into two types; intrinsic and extrinsic.
Intrinsic photo resistors use undoped materials such as silicon or germanium. Photons that fall on
the device excite electrons from the valence band to the conduction band, and the result of this
process are more free electrons in the material, which can carry current, and therefore less
resistance. Extrinsic photo resistors are made of materials doped with impurities, also called
dopants. The dopants create a new energy band above the existing valence band, populated by
electrons. These electrons need less energy to make the transition to the conduction band thanks
to the smaller energy gap. The result is a device sensitive to different wavelengths of light.
Regardless, both types will exhibit a decrease in resistance when illuminated. The higher the light
intensity, the larger the resistance drop is. Therefore, the resistance of LDRs is an inverse,
nonlinear function of light intensity.
Wavelength dependency
The sensitivity of a photo resistor varies with the light wavelength. If the wavelength is outside a
certain range, it will not affect the resistance of the device at all. It can be said that the LDR is not
sensitive in that light wavelength range. Different materials have different unique spectral
response curves of wavelength versus sensitivity. Extrinsic light dependent resistors are generally
designed for longer wavelengths of light, with a tendency towards the infrared (IR). When
working in the IR range, care must be taken to avoid heat buildup, which could affect
measurements by changing the resistance of the device due to thermal effects. The figure shown
here represents the spectral response of photoconductive detectors made of different materials,
with the operating temperature expressed in K and written in the parentheses.
93
Wiring diagram:
Code:
//cosntants for the pins where sensors are plugged into.
const int sensorPin = 26;
const int ledPin =2;
//Set up some global variables for the light level an initial value.
int lightInit; // initial value
int lightVal; // light reading
void setup()
{
// We'll set up the LED pin to be an output.
pinMode(ledPin, OUTPUT);
lightInit = analogRead(sensorPin);
//we will take a single reading from the light sensor and store it in the lightCal
//variable. This will give us a prelinary value to compare against in the loop
}
void loop()
{
lightVal = analogRead(sensorPin); // read the current light levels
//if lightVal is less than our initial reading withing a threshold then it is dark.
if(lightVal - lightInit < 50)
{
digitalWrite (ledPin, HIGH); // turn on light
94
}
//otherwise, it is bright
else
{
digitalWrite (ledPin, LOW); // turn off light
}
}
Experimental diagram:
95