Hello readers, hope you all are doing great. This is our 3rd tutorial in the ESP32 programming series. In our previous tutorial, we discussed the ESP32 Web server, where we created the ESP32 web server in STA mode.
ESP32 can be operated as an access point (AP) or a Wi-Fi station (STA mode). So, in this tutorial, we will create an ESP32 web server in access point (AP) mode. Here's the video demonstration of ESP32 WebServer in Access Point Mode:
As I mentioned above, in our 2nd tutorial, we already discussed the basics of the ESP32 web server. So, in this tutorial, we will only discuss how to create the ESP32 in access point mode.
For detailed information about the basics of the ESP32 web server and how client-server communication takes place, follow our previous tutorial (i.e., Create a Web Server with ESP32).
In Access Point Mode the ESP32 creates its own wireless Wi-Fi network in this mode, similar to the one provided by your existing router. In access point mode, we don't need to connect the ESP2 to a Wi-Fi network. In the Wi-Fi network it creates, the ESP32 Wi-Fi board can connect up to 5 devices.
Fig 1 ESP32 as an Access Point
So, in access point mode, nearby Wi-Fi devices such as mobile phones, laptops, or a secondary ESP32 module acting as a station can connect directly to the AP (ESP32 module) without the need for an external Wi-Fi router.
On the other hand, in Stationmode, the ESP32 wi-fi module connects to your Wi-Fi network through a router. The router acts as a conduit for communication between the web client and the ESP32. The Wi-Fi router provides the IP address. This IP address can be used by web clients to connect to the Web server on a local network.
To know about how to set up/operate Arduino IDE for ESP32 compilation, follow our first tutorial i.e., Introduction to ESP32 programming series.
ESP32 Web Server in Access Point (AP) Mode
Here we are using an inbuilt example from Arduino IDE(ESP32). You can modify the example code as per your requirements or can write your own code.
To find the Wi-Fi Access Point example in Arduino IDE :
Click on File from the top menu bar.
Place the mouse cursor on the example option from the list.
Look for the WiFi option.
There you will find the WiFiAccessPoint option, click on that and compile the program.
A screenshot is attached below to help you find the example code in Arduino IDE.
Fig 2 Wi-Fi access point example
The first task while writing the WiFi code is to add the required wifi header files or libraries in the code.
Here we are adding three libraries.
WiFi.h: This header file contains all the functions related to Wi-Fi activities like enabling the Wi_Fi, connecting to a wi-fi network etc.
WiFiClient.h: This header file is used to create a client that can connect with a specific IP address.
WiFiAP.h: This header file is used to configure and manage ESP32’s wifi module in Access Point (AP) mode.
Fig 3: Libraries
Define the LED pin or a GPIO (for peripheral interface) which we going to control through web server. Here we are using the inbuilt LED which is internally connected with GPIO2
Give a name (SSID) to the ESP32 Access Point and set the password for security purpose ( if you wish to).
While creating a web server we also need to assign a port and usually port 80 is used for local web server.
Arduino Setup() function
Inside the setup function, the LED pin is initialized as an output one and then initialized the serial monitor with a baud rate of 115200.
The next task is to configure the ESP32 Wi-Fi module in access point mode. For that, here we are calling a function called WiFi.softAP. Where we are passing two parameters, ssid and password, respectively.
After configuring the AP mode, we need to fetch the IP address of the access point by calling the WiFi.softAPIP() function and printing it on the serial monitor.
Then, after fetching the IP address, we will start the server using the server. perform.
Arduino Loop() function
After configuring the Access Point mode and initializing the server, the server will next wait for the station or client connection, which can be a mobile phone, a laptop, or another ESP32 board configured in STA mode.
Once the connection is established between the access point and the client device, the access point will wait for the data input.
A string type variable called currentLine has been defined to hold the incoming data from the client.
If there is a byte to be read from the client, then it will be stored inside the char type variable c.
HTTP header always starts with a response code e.g.: HTTP/1.1 200 ok
An HTML page will be created on the client’s browser, from where the client device can control (ON/OFF) the LED.
Different URLs will be created to turn ON and OFF the LED depending upon the HTML input received from the client device i.e., H (to turn ON the LED) and L ( to turn OFF the LED).
Client.stop() function is responsible for closing the connection between Access Point and client or station device.
Note: If you need any guidance regarding how to upload or compile a code for the ESP32 module in Arduino IDE, follow our first tutorial on the ESP32 programming series.
Testing ESP32 web server with hardware in Access Point with Arduino IDE
Here we are going to control the ESP32’s inbuilt LED through an ESP32 web server (AP mode).
We will connect our station or client device through Wi-Fi to the ESP32 module, which (ESP32) is currently acting as an access point (AP).
To establish the connection go to your mobile phone’s Wi-Fi setting.
The Access Point is advertising itself with a pre-defined SSID so that the station devices or clients can find the AP device and can communicate with each other.
If you find a wi-fi device (AP) named ESP32_AP (or as per your SSID) connect to that after entering the assigned password.
Fig. Scanning for available Wi-Fi devices in mobile phone
Fig. Connected with ESP32 AP
As we are using the inbuilt LED, no external components are required.
After connecting to the access point, you can find the IP address of the AP device printed on the Serial Monitor. As shown in the image below:
Fig.: Serial Monitor
Enter the IP address in the browser. Now you can turn the LED ON or OFF using the web page as shown in the images below.
A web page with URL 192.168.4.1/H will be displayed on the browser when LED is turned ON
Fig.: URL when LED is turned ON
LED is blue color represents the inbuilt LED which is connected to GPIO_2.
Fig.: ESP32 LED ON
Another web page with URL 192.168.4.1/L will be created when the AP will receive the input to turn OFF the inbuilt LED. As shown in the image below:
Fig.: Web page displaying the LED off state.
This concludes today’s tutorial. We hope you find it helpful.
In our next tutorial, we will discuss another ESP32 feature that is BLE (Bluetooth low energy).
Hello readers, I hope you all are doing well. Welcome to the Section 2 (ESP32 Features) of the ESP32 Programming Series. ESP32 is equipped with numerous built-in features and in each chapter of this Section 2, we will explore one of these ESP32 features in detail.
In the previous Section(Section 1: ESP32 IDEs), we installed different software IDEs to program ESP32 boards. Among these IDEs, we are going to use Arduino IDE for programming ESP32. So, I hope all of your tools are configured properly and you are ready to explore the built-in features of ESP32.
Today's the 1st Chapter of Section 2, and here we will discuss How to communicate with ESP32 Bluetooth Classic from a smartphone using Arduino IDE.
Here's the video tutorial for ESP32 Bluetooth Classic:
ESP32 is equipped with 3 wireless communication protocols:
Bluetooth Classic
Bluetooth Low Energy(BLE)
Wi-Fi
Before going forward, let's first have a look at the basic features of BT Classic:
What is Bluetooth Classic?
Bluetooth is a short-range communication(wireless) technology, used in electronic devices(i.e. mobile phones, computers, LED, headphones, speakers etc.) for wireless communication over a short distance, approximately 15m. Bluetooth operates at a 2.4GHz ISM band. Bluetooth uses low-energy radio waves for data communication between Bluetooth-enabled devices.
Now, let's design the code to communicate over ESP32 Classic BT:
ESP32 Bluetooth Classic
We are using Arduino IDE for code compiling and uploading to the ESP32 module. I hope you have already installed ESP32 Boards in Arduino IDE. So, let's design a simple project to understand the working of ESP32 Bluetooth Classic:
Project Description
First of all, we will install a "Serial BluetoothTerminal" App from the Google Play Store to communicate with the ESP32 Classic BT.
In this project, we will first enable the ESP32 Classic Bluetooth, so that we can connect it to our smartphone. After a successful connection, we will send data from our smartphone(Serial Bluetooth Terminal App) to the ESP32 Serial Terminal and vice versa.
So, let's first understand the ESP32 BT Code and then will install the Serial Bluetooth App from the Google Play Store:
Code for ESP32 Classic BT
Open Arduino IDE and navigate to "File > Examples > BluetoothSerial > SerialtoSerialBT".
This code utilizes BluetoothSerial Library, it's pre-installed with Arduino IDE but if you can't find it in the Examples, you can manually Download Bluetooth Serial Library and add it from Library Manager in Arduino IDE.
Upload this code to your ESP32 Microcontroller Board.
Here's the complete code:
#include "BluetoothSerial.h"
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to enable it
#endif
BluetoothSerial SerialBT;
void setup() {
Serial.begin(115200);
SerialBT.begin("TEP_ESP32_BT"); //Bluetooth device name
Serial.println("The device started, now you can pair it with bluetooth!");
}
void loop() {
if (Serial.available()) {
SerialBT.write(Serial.read());
}
if (SerialBT.available()) {
Serial.write(SerialBT.read());
}
delay(20);
}
Let's understand the code working:
How the Code Works
First of all, we added the Classic Bluetooth Library named "BluetoothSerial", it has all the routines/functions required to enable Bluetooth and to communicate with other devices.
#include "BluetoothSerial.h"
Next, we placed a check to ensure that Classic Bluetooth is configured properly and is discoverable to other devices:
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to enable it
#endif
Next, we created a Bluetooth object "SerialBT" of class BluetoothSerial to initialize the Bluetooth stack and communicate serially with ESP32 Classic Bluetooth:
BluetoothSerial SerialBT;
Setup() Function
Initial Configurations of the project are added in the Setup() function. In our code:
First, we initialized the Serial Port at a baud rate of 115200.
Next, we initialized the SerialBT object and assigned a unique name "TEP_ES32_BT" to our Bluetooth device, this name will appear in the Bluetooth Search List.
Finally, printed a welcome message on the Serial Monitor.
void setup() {
Serial.begin(115200);
SerialBT.begin("TEP_ESP32_BT"); //Bluetooth device name
Serial.println("The device started, now you can pair it with bluetooth!");
}
Loop() Function
The Loop() Function is an infinite loop and is equivalent to while(1) in normal C Language. In our code, we have placed two if checks:
The first "IF Check" is monitoring the ESP32 Serial Terminal.
If we send any data from the Serial Terminal, this data will be transmitted to the SerialBT.
The second "IF Check" is monitoring the SerialBT.
If we receive any data via ESP32 Classic Bluetooth, we will print it on the Serial Terminal.
void loop() {
if (Serial.available()) {
SerialBT.write(Serial.read());
}
if (SerialBT.available()) {
Serial.write(SerialBT.read());
}
delay(20);
}
So, I hope you have understood the working of this ESP32 Classic Bluetooth code. Now, let's install the Serial Bluetooth Terminal App from the Google Play Store:
Serial Bluetooth Terminal App
Make sure your mobile's Bluetooth is enabled.
Open the Google Play Store on your Smartphone and make a search for "Serial Bluetooth Terminal" and install it.
If we are connecting with the ESP32 BT for the first time, we need to pair it first.
Open the Serial Bluetooth Terminal app and click on the "Devices" tab.
It will scan the list of all the available Bluetooth devices:
[Image]
Now, Pair with the ESP32 Classic BT device named "TEP_ESP32_BT".
Click on Pair.
We have successfully paired the ESP32 BT with the smartphone's Bluetooth.
ESP32 BT to Smartphone - Data Testing
Open the Bluetooth Terminal App and click on the Connect Button at the top:
[Image]
Open the Serial Monitor in the Arduino IDE and set the baud rate to 115200:
[Image]
As shown in the below figure, when we send data from the Serial Monitor, it communicates over Classic Bluetooth and appears in the BT Terminal App.
Similarly, when we send data from the BT Terminal App, it appears on the Serial Monitor of Arduino IDE.
So, that's how we can communicate between ESP32 and smartphones over Classic Bluetooth. In today's lecture, we communicated simple text data to understand the working principle. In the upcoming lectures, we will send complex data(i.e. commands & sensor values) via Classic Bluetooth.
Now, let's have a look at some theoretical knowledge about Classic Bluetooth:
BLE vs Bluetooth Classic
Fig: BLE vs Classic Bluetooth
Bandwidth: Bluetooth can send a large amount of data, while BLE sends small chunks of data.
Compatibility: Classic Bluetooth and BLE are not compatible with each other. A Bluetooth-supported device can’t communicate with BLE supported device.
But, a device having BT V4 (Bluetooth version 4) can discover both BLE and Classic Bluetooth devices.
Power consumption: The classic Bluetooth consumes more power than BLE.
Pairing: In Bluetooth classic pairing is necessary before sharing data between Bluetooth devices for security purposes. On the other hand, BLE technology doesn't ask for pairing before data transmission.
Number of active devices: In traditional Bluetooth, a maximum of 7 slave devices can be connected with the master Bluetooth at a time. Though classic Bluetooth can connect with multiple nodes/slave devices at a time but it can exchange data with only a single node at a time.
Bluetooth Evolution
The initial Bluetooth version (V1.0) was riddled with bugs and limitations.
Bluetooth 2.0 was created as a result of various modifications and improvements to the basic version 1.0.
Bluetooth 2.0's most notable feature was the enhanced data rate (EDR).
Fast modulation technology and a data rate of up to 3Mbps are used in Enhanced Data Rate mode.
Despite improvements in the basic version, Bluetooth 2.0 lacks a security feature.
Bluetooth 2.1 added a security feature called "Pairing" as well as a faster data rate.
Another updated version, Bluetooth 3.0, included a Wi-Fi feature, but it was rarely used, and when it was, the features were similar to the Bluetooth 2.1 version.
Bluetooth 4.0 was the first version to include the Bluetooth low energy feature (BLE).
The most recent Bluetooth version is v5.2, which supports both Classic Bluetooth and BLE and consists of the following features:
EATT (enhanced attribute protocol)
LE (Low Energy) power control feature (LEPCF)
LE Audio
Bluetooth Network topology
Classic Bluetooth forms a piconet. A piconet has a single master and multiple(max 7) slaves. Each piconet has its own hopping sequence.
Fig: Classic Bluetooth Network topology
Classic Bluetooth can operate on both point-to-point and point-to-multi-point network topology. In traditional Bluetooth, a maximum of 7 slave devices can be connected with the master Bluetooth at a time. Though, classic Bluetooth can connect with multiple nodes/slave devices at a time, but it can exchange data with only a single node at a time.
Bluetooth Clock
In classic Bluetooth, the piconets are not synchronized.
The clock is one of the most important aspects of Bluetooth. In a Bluetooth connection, the master device has a clock that is used to split the time on each physical channel. Clocks on all slaves in a connection are synchronized to the master clock.
Bluetooth clock synchronization is essential because the radios must agree on when to transmit. Because Bluetooth uses precise timeslots for transmissions with devices alternating, if the clocks are not synchronized, there may be issues with devices transmitting at the incorrect time.
Classic Bluetooth transmitting power
It is defined in multiple classes:
Class 1: +20dBm maximum.
Class 2: Up to +4dBm.
Class 3: Up to +0dBm.
Classic Bluetooth Data transmission modes
Generally, there are two data transmission modes:
Basic Rate (BR): BR is the first Bluetooth protocol which is implemented in Bluetooth v1.0. It uses one of the FSK (frequency shift keying) modulation techniques known as Gaussian frequency-shift keying (GFSK) and communicates data at the 2.4 GHz ISM band.
Enhanced Data Rate (EDR): It's a Bluetooth specification that allows for a higher data rate or speed. It is not available in all Bluetooth versions, and its availability is dependent on the Bluetooth version and profile. EDR uses pi/4-DQPSK (differential quadrature phase-shift keying) and 8DPSK (differential phase-shift keying) modulation techniques with data rates of 2Mbps and 3Mbps respectively.
Bluetooth packet format
When two devices communicate data over Classic Bluetooth, they use SPP (Serial Port Profile)
Fig. Bluetooth packet format
Enhanced data rate packet sends the Access code and header using the basic rate and this process uses GFSK (Gaussian Frequency Shift Keying). The guard gives the time to change the modulation to EDR modulation and then the synch word (64 bits), payload, and Trailer (4 bits) bits are sent using EDR (enhanced data rate) modulation.
So, that was all for today. In the next lecture, we will communicate between ESP32 and smartphones via BLE(Bluetooth Low Energy). Till then take care. Have a good day!!!
Hello geeks, Welcome to our new project. As most readers have already seen the coffee vending machine or maybe you are drinking coffee while reading this article and if you are a tinker or a geek, it must have come to your mind how to make a coffee vending machine on your own. In today's tutorial, we are going to learn how to make a Smart Coffee Vending Machine using Arduino with Proteus Simulation for the same.
We can use this project for an engineering project’s showcase for electronics, electrical engineering students, and can be used in offices as well.
Coffee is the second most popular drink in the world and it is one of the oldest beverages of the world. According to Wikipedia, more than 2 billion cups of coffee are consumed every day in the whole world. As engineers or working professionals, we all know how coffee is very important for us. Having a good coffee makes our day better and refreshes the mood. Research shows coffee drinkers tend to live longer but when keeping it in moderate consumption. And making a good coffee is one of the most skillful jobs and time-consuming processes as we want our coffee in minutes. Now here our project comes to the picture, this smart coffee vending machine can make a good coffee in a couple of minutes. There are various flavors of coffee and our smart coffee vending machine can provide us with 4 different flavors which are the most commonly loved such as Latte, Cappuccino, Espresso, and Cafe Mocha. Here's the video demonstration of this project:
As we are going to design this project using Proteus Simulation, instead of using real components. As in the simulation, we can figure out the issue which may occur while working on real components and that can damage our components.
Proteus is the software for simulation and designing electronics circuits. As Proteus software has a big database of electronics components but still it does not have few modules in it like Arduino boards or LCD modules etc.
So we have to install the libraries, which we are going to use in this project:
Arduino Library for Proteus: We have to add the Arduino boards to the Proteus components list.
LCD Library for Proteus: We have to add the LCD module to Proteus Suite.
You can download this whole project for example Proteus Simulation and Arduino Code, by tapping the below button
Smart Coffee Vending Machine using Arduino
These are required components for Smart Coffee Vending Machine, as follows:
20X4 LCD display: It is used to display user-related messages like the state of the vending machine.
Arduino UNO: It is used as the brain of our project. All operations and decision-making will be done using this microcontroller.
DC motor: It is used for dispensing the ingredients of coffee and the mixer.
Buttons: It is used as a user interaction option.
As a suggestion, whenever we make a project, it should be like a product, as it should be user friendly and interactive, so considering that we have used an LCD module to display the messages related to available coffee flavors and their individual prices so that users can easily select them using buttons and DC motors to pour the ingredients related to coffee like water, sugar, coffee powder, and milk, and a mixer for blending the coffee.
We have connected the LCD using an I2C GPIO expander as we have limited GPIO pins to connect other peripherals with Arduino UNO. I2C Gpio expander requires only two pins as we know that I2C uses SCL(Serial Clock) and SDA(Serial Data) pins for communication.
Components Needed:
Arduino UNO
LCD display
4 Buttons
8 Motors
PCF8574
Components Details
Arduino UNO:
We can use any Arduino development board but here in this project, we have used an Arduino UNO board.
Arduino UNO is one of the programmable, open-source microcontroller boards of the Arduino family.
It contains an Atmel’s Microchip ATMega328 or ATMega328P microcontroller which has Harvard architecture 8-bit RISC processor core and 32 KB flash memory.
Arduino UNO comprises 14 digital I/O pins out of which 6 are PWM pins as well and 6 Analog I/O pins with 10 bits resolution(0-1024).
Arduino UNO has only 1 hardware UART pin(but we can use other pins also for UART communication using SoftwareSerial library in Arduino), 1 I2C, and 1 SPI.
PCF8574:
We have used this IC as a GPIO expander for our project as we have restrictions on the availability of GPIO pins in Arduino UNO.
It is an 8-bit I/O, silicon-based CMOS GPIO expander.
It can be used to write data on the pins and also can read data on those pins.
It uses the I2C protocol for communication with the master device.
As we know that I2C protocol uses the slave address to send or receive data from slaves, so for that it has 3 pins A0, A1, A2 for setting the slave address.
Slave address for PCF8574 starts from 0x20 to 0x27. That means we can add only 8 PCF8574 IC directly to a master controller.
The following image explains the logic of the slave address of PCF8574.
It is used for connection for the LCD module with Arduino UNO in our project.
If you want to learn more about IC PCF8574, you can refer to the datasheet using the following URL: PCF8574 Datasheet
LCD display
The LCD display is used to show the user-related messages in this project.
LCD is a short form of Liquid Crystal Display which is basically built using Liquid Crystal technology.
There are different sizes of LCDs available, in this project we have used 20X4 size.
Here 20X4 signifies that it can display 80 ASCII characters at a time.
There are 16 pins in the LCD. We will not use every pin of LCD in this project.
It has 8 data pins, 1 Read/ Write select pin, 1 Register mode pin, 1 Enable pin, 2 pins for backlight, and 2 pins for power supply, 1 contrast control pin.
There are mainly two types of register in the LCD: Command Register and Data Register.
When we set the RS(Register Select) pin to logic High then it will select the data register mode and in logic Low, it will select the command register.
To display the data on LCD we will set the RS pin to logic High.
Proteus Simulation of Smart Coffee Vending Machine :
Now, it's time to start designing the Proteus Simulation of our Smart Coffee Vending Machine.
Most importantly, ensure that Proteus is installed on your PC and download all the required libraries for Proteus ahead.
For this project, we are going to need libraries of Arduino and LCD modules.
Make sure that you have read about how to use libraries in Proteus software.
Let’s create a new project, open the new project in Proteus and import all the required components which we are going to use, and place them within the working area.
We need the following components, so select all of them from the Proteus component library.
Circuit Diagram and Working:
Now let’s design our circuit, first place all the selected components in the Proteus Workplace, as shown in the image below:
We will start connecting the LCD module and PCF8574, as we are using only 4-data pin-mode of LCD.
After that, we will start the GPIO expander PCF8574 I2C connections, connect the SDA, SCL pins of PCF8574 to Arduino UNO’s SDA, SCL pins which are A4, A5 pins of the development board.
As we know, we have to set the slave address of PCF8574 using A0, A1, A2 pins. And in this project we are going to use the slave address 0x20, therefore for that, we have to connect all pins to the ground. (As we have already seen in the above PCF8574 addressing image)
In the next step, we are going to connect the buttons to Arduino digital pins D2, D3, D4, D5 as "Latte", "Cappuccino", "Espresso", "Cafe Mocha" flavors respectively and another terminal of the buttons is connected to ground. As we are going to use the buttons inactive low condition which means, when we press the button it will give us a logical LOW state.
There may be a doubt in your mind why we have not used any PULL-UP resistors with buttons because we will handle that in our code. Arduino UNO comes with an internal PULL-UP resistor of 20-50 KOhms.
Now connect the dc motors for each container, Water, Coffee, and Sugar container’s motors are connected with Arduino’s digital pins D10, D12, D11 respectively. Connect the coffee outlet motors for each type of Latte, Cappuccino, Espresso, Cafe Mocha with digital pins D6, D7, D8, D9 respectively. And at last, connect the mixer with the D13 pin.
As we have mostly completed the wiring part, the first thing which we must make sure of before going to start our simulation is that all components should have adequate power supply and ground. And ground must be common in the whole circuit.
Now we hope you have understood the connections and you have already done it, so it is time to move to the coding part of our project.
Arduino Code for Smart Coffee Vending Machine
If you already know about the syntax and structure of Arduino sketch, it's a good thing, but if you have not been familiarized yet, no need to worry, we will explain it to you step-by-step.
Arduino coding language mostly follow the syntax and structure of C++ programming language, so if you are familiar with C++, then it would be like a cup of cake for you to understand the code but still if you don’t have any background knowledge, you don’t have to worry again, we have your back.
Arduino Coding follows a strict structure, it has mainly two sections. we have to write our code in those two functions.
void setup()
void loop()
As we are going to explain the Arduino code, it would be easy to understand if you have opened the code in the Arduino IDE already.
Declaration code:
When we start our code, we will first include all the required libraries which we are going to use in this project.
So our first step would be to download the required libraries if they are already not pre-installed in the Arduino IDE.
Mainly we will use only two libraries, one for LCD display and the other for I2C communication.
And I2C related functions come in the Wire library which will be pre-installed in Arduino ID, we don't have to install it explicitly.
For the LCD module, we will use the Liquid Crystal_I2C library that we have to install.
We can install libraries related to Arduino from the Arduino IDE by going to ‘Sketch > Include Library > Manage Library’. Now in the library manager, we can search for our required libraries. We can install the libraries using zip files also.
>> Now, as we have installed all the required libraries. Let’s include them in our sketch.
After that, we will define the pins which we are going to use in our project.
We have to define them globally so that we can use them in all functions.
You must be having a doubt why we have not defined pins for I2C.
Because those pins are pre-defined in the Wire library, we can not assign any other pins for I2C communication.
Now we will define and declare all the variables which are required in our project.
There is an array for the price of a coffee with the size of 4, as we will only provide only 4 types of coffees and a string type variable for storing the name of flavors of coffee.
Arduino Setup() Function:
In this Arduino Setup() function, we will write a section of code that will only run once.
So mostly we will write the declarations, define the type of pins and initialize the peripherals such as the LCD module.
We want to take user input from the buttons therefore we will declare them as INPUT type.
We have not connected PULL UP resistors in buttons as you have read above, we will handle that in the code therefore we have declared it as INPUT_PULLUP mode.
We have declared motor pins as OUTPUT mode because we want to control the motors.
After that we will initialize the LCD module then we will turn on the backlight of LCD, set the cursor to 0,0 index and using ‘lcd.print()’, we will print the welcome message on the LCD module.
In the setCursor function, the first argument is used for X-Axis and the second argument is for Y-Axis.
It will display the welcome message for 1 sec as we have given a delay for 1000 milliseconds after we clear the display.
Arduino Loop() Function:
Arduino Loop function runs after the the ‘void setup()’ function.
In this section, we will write the code which is required to run in a continuous loop. So we will write our main application code here.
So when the code reaches the void loop section, first we will display the flavor and the price of the coffee on LCD display as we want to show the user what type of coffee our vending machine makes and the price of those individually.
>> Now we will write the section for reading the user input from the buttons. As we have set that the condition will be true when the button will be logic LOW state.
>> Now when the user will press the button, the state of the button’s pin state will be changed to logic LOW state and then our ‘if condition’ will be true and code and our operation will enter in the ‘if condition’ section.
>> Here we will display to the user the current process stage of the coffee making. So we will clear the LCD display and then set the cursor to 0,0 index. After that we will display the message for collecting the ingredients.
As we have not cleared the display, it will display the same message.
After 1 second delay, we will start the water container motor for pouring the water for 2 seconds.
Thereafter we will set the water’s container pin to LOW and Sugar’s container motor pin to HIGH for 2 seconds, similarly for the coffee’s container pin.
Now we will start the motor for the selected flavor of coffee for 2 seconds and then stop it.
As now our selected coffee is getting ready so we will display the message for the same.
To display any new message, we have to clear our display with pre-occupied text.
Now we will start the mixer motor for 10 seconds to mix all the poured ingredients.
>> Now our selected coffee is ready. So we will clear the LCD display and set the cursor, and will print the message regarding the prepared coffee with the price of it.
Results/Working:
Below is the Flow diagram of coffee vending machine:
Let’s understand the code with an example, we will go with the starting step.
Power ON the device, the machine will display the welcome message that you can change from that code as per your choice.
That message will be shown for 1 second thereafter it will clear the display.
Now it will display the type of coffee as "Latte", "Cappuccino", "Espresso", "Cafe Mocha" and their respective prices.
Let’s suppose, the user wants to have a Latte today, so he/she will press the button for the same, thereafter our coffee-making process will start.
The first LCD display will show the message “Wait a Moment Collecting Ingredients” and it waits for 1 second.
Thereafter it will start pouring the water for 2 seconds, then it will stop that motor.
After that, it will start to pour sugar for 2 seconds, then stop that motor.
At last, it will start to pour the coffee for 2 seconds, then stop that motor.
It will start the motor of the selected type of coffee to dispense the coffee to the container and then it will wait for 1 second.
Now LCD will display the message for coffee getting ready as "Wait a Moment Your’s Rich Latte is getting ready…” as the user has selected Latte that’s why it shows “Latte is getting ready… “.
Now we will start the mixer to mix all the ingredients for 10 seconds.
Again we will clear the LCD display to show the message for prepared coffee as “ Your's Rich Latte is ready. Please Collect it Your's Amount - 5/-”.
Then it waits for 5 seconds and clears the display and again shows the price and the available types of coffee.
As Proteus requires the hex file of the code to run the simulation.
So for that, open the Arduino IDE and please verify your code before making a hex file by clicking on the ‘Verify’ button to remedy any errors.
To get the hex file from the Arduino IDE click on “Sketch > Export Compiled Binary”.
Your hex file will be generated successfully now put that hex file to the Arduino UNO board in the Proteus software.
Everything is now in place, it's time to run the simulation and get a nice virtual coffee.
I hope you have understood the whole working of our smart vending machine project and enjoyed it as well. I think we have explained pretty much everything but still if you have any doubts or improvements please let us know in the comment section.
Thanks for giving your valuable time for reading it.
Hello readers, today we will learn about the messaging protocol supported by ESP32(called MQTT protocol), which is used for IoT applications. The communication protocol to be used for data transmission and connectivity in web-enabled devices depends upon the type of IoT application.
The Internet of Things (IoT) is a network of interconnected computing devices like digital machines, automobiles with inbuilt sensors, having unique identifiers and the ability to communicate data over a network without the need for human intervention.
Before implementation, let's first have a look at what is MQTT Protocol?
MQTT stands for Message Queuing Telemetry Protocol and is a messaging or communication protocol used for IoT applications.
In MQTT protocol, a publisher sends a message to the broker with a specific topic tag, and the broker forwards this message to all the Subscribers of that mentioned topic.
So, in order to understand MQTT Protocol, we need to discuss these 4 terms:
MQTT Topic
MQTT Publisher
MQTT Broker
MQTT Subscriber
Note:
The OASIS technical committee is the in-charge of MQTT specifications. The OASIS or the Organization for the Advancement of Structured Information Standards is a non-profit organization dedicated to the development, convergence, and implementation of electronic business standards.
Fig 1: ESP32 MQTT Protocol
MQTT Topic
In MQTT protocol, a Topic is simply a UTF-8 string i.e. "Arduino", "ESP32", "Beginner Tutorials" etc.
MQTT Clients can subscribe to these Topics and are called Subscribers to that Topic.
MQTT Broker sends messages to the Clients based on their Topic subscription.
A topic may have multiple levels, separated by a forward slash.
MQTT Publisher
MQTT Publisher(also called MQTT client), as the name suggests, publishes the message on a specific topic and sends it to the broker.
In simple words, a publisher sends a message(normally a string) to the MQTT Broker, and this message also contains the Topic information.
MQTT Broker
MQTT Broker(also called MQTT server) acts as a coordinator between the subscriber and the publisher in order to create communication.
The broker's job description is as follows:
Receiving messages from the publisher
Filtering received messages based on assigned Topics from the publisher.
Determining the interested subscriber in each message based on the assigned Topic
Finally forwarding the messages to subscribers
MQTT Subscriber
MQTT Subscriber(also called MQTT client), subscribes to the MQTT Topics and receives the messages from the MQTT broker, sent by the Publisher.
How does MQTT Work
This messaging protocol follows the Publish and Subscribe model. The Publisher and Subscribers of the message, communicate via Topics and are separated from one another. The broker is in charge of their communication. The broker's job is to filter all incoming messages and distribute them to the subscribers in the most efficient way possible. The broker pushes the information to the client whenever something new becomes available, so the client doesn't have to pull the information.
Because there are so many ready-to-use brokers and client applications, getting started with MQTT is a breeze.
Fig 2: MQTT Publish and Subscribe architecture
MQTT Features
Light Weight
It is a lightweight and versatile IoT communication and data transfer protocol aimed at IoT developers who want to strike a compromise between flexibility and network resources.
All the MQTT messages have a small footprint which adds a lightweight feature to this protocol.
In MQTT every message has:
2-byte header (fixed)
A 256 MB message payload
A 2-byte variable header (optional)
Security
MQTT protocol implementation will allow you to use your User name and password for security purposes. If you added the authentication feature while creating the MQTT server then stranger clients can’t communicate to your MQTT server.
Bidirectional communication
There is no direct link between clients in MQTT.
A broker connects the subscriber and the publisher in this messaging protocol. As a result, the subscriber and publisher can converse about any issue that the broker handles.
Eliminate polling
Polling is a procedure in which the controlling devices wait for input from an external device to determine whether the device is ready to broadcast data. MQTT protocol follows instantaneous push-based delivery. So there is no need to continuously check or poll before sending data which results in reduced network traffic.
Storage and forwarding
MQTT supports the storage and forwarding of persistent messages on the broker. Clients can ask for the broker to keep messages after they've been published. When this feature is used, any persisted message will be broadcast to a client who has subscribed to a topic. The most recent persistent message is the only one that gets saved. Unlike typical messaging queues, however, the MQTT broker prevents these persisted messages from being backed up inside the server.
Decouple and scale
It enables changes in communication patterns and functionality without causing a system-wide ripple effect.
Simplifies communication
As we have already discussed that MQTT follows Subscriber and Publisher architecture where the broker acts as an interface between the clients. So there is no need of computer to computer interface hence providing simplified communication.
Dynamic targeting
It also supports authentication, publishing, subscribing, keep-alive pings.
It runs on top of Internet protocol and TCP.
Quality of service
Quality of service is a kind of indicator which ensures that messages are exchanged between the sender and the receiver. There are three levels of QoS:
just once - this level is not reliable but is the fastest one
at least once - this level is the default mode
just once - this level is the most reliable, but slowest
MQTT Applications
MQTT protocol is mostly used in IoT(internet of things) applications for data transmission. The data can be read from some sensors or some temperature value.
Fig 3: MQTT Applications
Some other applications where you can use it are :
Security and surveillance
Industries & energy
Logistics
Medical & healthcare
How to Publish a message using ESP32 MQTT?
The MQTT protocol is another functionality supported by the ESP32 module. To implement MQTT, we're utilizing the Arduino IDE.
If you're not sure where to begin coding with the ESP32, check out our prior tutorial, Introduction to the ESP32 Microcontroller Series.
Code Description
Global Declarations
Adding libraries will be the initial stage.
To use ESP32 MQTT to send a message, you'll need two libraries.
#include <WiFi.h>#include <PubSubClient.h>
PubSubClient library is not available in ESP32’s library list. You need to download the library first and add the library into Arduino IDE.
Fig 4: Adding library to Arduino IDE.
Click on Add. Zip Library.
Browse for the downloaded library file and add.
PubSubClient library and Wi-Fi library
We covered Wi-Fi in detail in our previous tutorial, ESP32 web server.
PubSubClient is a client library that may be used with MQTT applications.
Add your SSID and Password to create a wi-fi connection. Follow our previous tutorial, ESP32 web server, to learn more about ESP32 Wi-Fi.
const char* ssid = "public"; //add your SSIDconst char* password = "ESP32@123";// add your password
Initialize the Wi-Fi. (follow the previous tutorial for more details about (ESP32 Wi-Fi)
Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); }
Print Wi-Fi status on serial monitor
Serial.println("Connected to the Wi-Fi network");
Define the MQTT server's address and port address.
To do so, we use the PubSubClient object's setServer function.
The address and port, both defined early in global variables declaration, will be passed to this procedure as the first and second arguments, respectively.
setCallback method to define a handling function.
When a MQTT message is received on a subscribed topic, this handling function is called. This function's code will be saved for later.
client.setServer(mqttServer, mqttPort); while (!client.connected()) { Serial.println("Connecting to MQTT..."); if (client.connect("ESP32Client", mqttUser, mqttPassword )) { Serial.println("connected to MQTT"); } else { Serial.print("failed to connect "); Serial.print(client.state()); delay(2000); } }
Publish a topic
client.publish("esp/test", "ESP32");
Subscribe for the topic you want to.
client.subscribe("esp/test");
Finally, we'll subscribe to the topic we're interested in. Other clients' communications will be published on that topic, and we will receive them this way. For that purpose, we use the subscribe method, which takes the name of the topic we want to subscribe to as an argument.
Arduino loop() Function
The next task will be to connect with the MQTT server which will happen in the main loop
Here, the device will keep trying to connect with the server unless it establishes a connection.
In order for the client to process incoming messages and maintain the connection to the MQTT server, the function should be invoked on a regular basis.
MQTT Testing
For testing purposes, we will use MQTT_lens which is a Google Chrome application to establish a connection with the broker.
Here are some screenshots of the MQTT lens broker:
Create a connection after adding the following details:
Connection, Hostname, Port etc.
Fig: MQTT_lens broker
This concludes today’s tutorial, hope you find it helpful.
Hello readers, I hope you all are having fun in your lives. Welcome to the 2nd Chapter of Section-2 in the ESP32 Programming Series. In today's lesson, we'll go over another built-in feature of the esp32 module that helps it stand out from the competition: BLE or Bluetooth Low Energy.
In the previous tutorial, we discussed the Classic Bluetooth in ESP32, which is considered the predecessor of Bluetooth Low Energy(which we are going to discuss today). We will first look at, what is BLE? and why is it used?, and then will design some examples to utilize the ESP32 BLE in Arduino IDE.
There have been numerous adjustments and upgrades to Bluetooth's characteristics since its inception, where Bluetooth 4.0(also called BLE or Bluetooth Smart) is the most influential.
BLE or Bluetooth Smart is also known as Wibree. The Wibree protocol was designed by Nokia in 2006 and was later included in Bluetooth 4.0 as Bluetooth Low Energy in December 2009.
Bluetooth Low Energy is a slightly different protocol from Classic Bluetooth, which is used in phones, headphones, TVs etc. Rather than continuously streaming data, BLE "servers" can "notify" clients to send the data chunks on a regular basis(which makes it preferable over traditional Bluetooth). As a result, BLE is better suited to low-power IoT applications that don't require significant volumes of data.
Both the server and clients now utilize a "service UUID", to determine which server and client needs to be connected. There are various "characteristics" that can be found inside these services.
Bluetooth Low Energy was developed and promoted by the Bluetooth Special Interest Group (SIG) for use in healthcare, beacons, fitness, home entertainment etc. It does not work with standard Bluetooth and does not have any compatibility, although it can coexist with BR/EDR and LE.
The Bluetooth Special Interest Group (SIG) recognizes several industries for low-energy technology, including smart homes, health, sport, and fitness.
Difference b/w traditional Bluetooth and BLE
Bluetooth Technology was created with the intention of allowing data to be streamed indefinitely. That implies you can send and receive a large amount of data over a short distance with Bluetooth.
It's crucial to discuss power usage while discussing the differences between Bluetooth and Bluetooth Low Energy. Bluetooth Low Energy is intended to transfer data only when the client is available to receive the data from the server; otherwise, the BLE device will go into low energy or sleep mode. Thus, use significantly less power as compared to traditional Bluetooth, while retaining a similar communication range.
Bluetooth Low Energy uses the same 2.4 GHz radio frequencies as traditional Bluetooth, but a different FHSS (Frequency Hopping Spread Spectrum) technique.
Classic Bluetooth uses Scatter-net topology whereas BLE uses Star topology.
Although Bluetooth Low Energy differs from the previous Bluetooth Basic Rate/Enhanced Data Rate protocol, both can be supported by the same device: the Bluetooth 4.0 specification allows devices to implement any or both of the LE and BR/EDR systems.
Because both, Bluetooth Low Energy and traditional Bluetooth use the same 2.4 GHz radio frequencies, allowing dual-mode devices to use a single radio antenna.
How does BLE work?
BLE Client & Server
Any BLE device can operate as both a server and a client.
Server ESP32 will announce its presence to nearby clients so that clients can establish a connection with the BLE server for communication.
Broadcast mode and mesh networks both are also supported by BLE.
In broadcast mode, only the BLE server transmits data to all the connected clients.
In mesh mode, all the devices are connected to each other. Therefore, all devices can communicate with all other available devices.
GATT
GATT is an acronym for Generic Attributes.
It defines a data structure that is visible to all BLE devices linked to it. GATT defines how BLE devices can communicate with each other. Understanding this structure is crucial to understand the working of BLE.
The GATT protocol includes a set of commands that allow the client to learn more about the server.
Read through all of the descriptors for a specific characteristic.
Find out everything there is to know about a specific service.
Find qualities that match a UUID.
Find UUIDs for all major services.
Find a service using a UUID.
For a particular principal service, locate subsidiary services.
BLE Service
A service is nothing more than a collection of data, such as data from a temperature sensor.
A profile, which is made up of multiple services, is at the top of the structure. Typically, a BLE-supported device will have multiple services.
The SIG has preset services for a variety of data kinds, such as battery level, weight, blood pressure, heart rate, and so on.
Every service has at least a single feature and can also refer to different services.
BLE Characteristics
The characteristic attribute is always held by a particular service, and it is where the hierarchy's real data is stored.
The characteristic has two attributes:
Characteristic value.
The characteristic declaration contains the metadata.
It essentially consists of the operations that can be used like Indicate, read, write, notify, broadcast etc.
UUID or Universally Unique Identifier
In a Generic Attribute (GATT) profile, the UUID is a universally unique 128-bit or 16-byte integer that is used to identify profiles, services, and data kinds.
Note:
In the code description, we will provide a link where you can generate a new UUID.
BLE network topology
BLE uses Star and mesh topology for communication.
A Broadcast Type or a Connection Type communication between two BLE devices is possible. The 'broadcaster' BLE Device sends data to any 'observer' BLE Device in broadcasting. It's a data transfer that only goes one way.
A 'Connection' between the BLE Devices is required for two-way communication. A Central (Master) BLE Device continuously checks for advertising data packets sent by a Peripheral (Slave) BLE Device.
BLE Applications
BLE is ideal for applications that need to exchange modest amounts of data on a regular basis.
BLE is used extensively in healthcare, fitness, tracking, beacons, security, and home automation etc.
Bluetooth Low Energy is natively supported by mobile operating systems such as iOS, Android, and Windows Phone, as well as macOS, Linux, Windows 8 & 10.
ESP32 BLE
You can use ESP32 BLE either as a BLE server or a client.
Examples are available in the ESP32 BLE library(Arduino IDE) which you can use to implement BLE services.
Note:
The Arduino IDE must have the ESP32 board manager file and libraries installed. If you haven't previously prepared your Arduino IDE to operate with the ESP32, then read our previous tutorial, i.e., Introduction to ESP32 Programming Series.
BLE Server Code Description
For coding, we are using Arduino IDE’s inbuilt example and will make the required changes in that code only.
I will also explain the code in detail for beginners to understand.
In this code, ESP32, BLE will be used as a server.
Import the necessary/required libraries for the BLE application.
Define a UUID for the Service and Characteristic.
To generate UUIDs, go to the following link:
https://www.uuidgenerator.net/
You can either use the default UUIDs if you wish to or go to the above link to generate random UUIDs as per your services and attributes.
Call back or acknowledge the server whether the client is connected or not
Arduino Setup() Function
Serial Communication at a baud rate of 115200.
Create a name for your BLE device for identification, we named it Wibree.
Set the BLE device as a server.
Create a service for the BLE server with the UUID defined earlier.
The characteristic for that service is then set. As you can see, you're still using the UUID you created previously, and you'll need to supply the properties of the characters as arguments. It's read and write in this scenario.
You can also add other services like battery, indicate, notify etc.
The setValue() method can be used to set the value of a characteristic.
The above value can be changed to whatever you like. This could be a sensor reading.
Finally, activate the service and advertising so that other BLE devices can scan and locate this BLE device.
Arduino Loop() Function
Here we can check if the device is connected to the client or not
If connected then do some tasks like transmitting data or receiving input from the client.
Data Size Per Packet
20 bytes per packet.
Unfortunately, BLE isn't built to handle large amounts of data. The maximum data size per packet in the BLE specification is 20 bytes, so if you wish to communicate more, you'll have to divide it up into many packets. Fortunately, this isn't a challenging task. Simply put, use a delimiter like "!" or "*" or something unique at the end of your whole message to signal the app that the message is done and to start listening for future communications. If you want to send + > 20 bytes cumulatively, for example, you can send and then proceed with the next message if needed.
Testing ESP32 BLE Server
After creating a BLE server using ESP32, we can use a BLE application available on the Play store for testing purposes.
Demonstration with BLE scanner app:
Go to the play store
Search for the BLE scanner and download the app
After installing the app turn on the Bluetooth.
Open the app and search for nearby devices.
Now connect to ESP32 BLE by clicking on the ESP32 device.
In our case, we named the device ‘Wibree’.
Now you can use the various services provided by BLE like writing and reading data packets, checking battery levels etc. and a lot more.
This concludes the tutorial. I hope you find it helpful.
Hello readers, I hope you all are doing great. Today, we are going to start the second section of the ESP32 tutorial series and today's our first tutorial, where we will have a look at How to Create a Web Server with ESP32. In our previous tutorial, we introduced you to the basics of the ESP32 microcontroller. where we discuss How to set up Arduino IDE to program ESP32. In this tutorial, we will discuss creating a web server using the ESP32 module.
One of the most interesting features of the ESP microcontroller series is its wireless connectivity via WiFi & Bluetooth. Wireless connectivity protocols supported by ESP32 are:
A web server is software or hardware that stores, processes, and delivers web pages to users on request. In other words, it serves users all over the World Wide Web (www). The web server uses the hypertext transfer protocol (HTTP or HTTPS) for communication with the clients(normally, web browsers). We know that HTTP is a set of rules to format and exchange messages.
The following are some important features of a web server:
Features of a Web Server
A web server, either physical or virtual, is a computer that hosts one or more websites.
The HTTP protocol is the foundation of any data exchange within the network when using the server. So a web server uses it to communicate with the client.
The web server uses static content and the files do not change dynamically. Some such files used in a web service are:
HTML files
Images
Stylesheets
JavaScript files
The web server has multiple settings to avoid unnecessary attacks. This helps to maintain the health and integrity of a website. There are multiple types of web security attacks, such as:
DDoS attacks
SQL injection
Cross-site scripting (XSS)
Hence, a web server has multiple features to serve the users on the web.
Web Server & Client Communication
A client is an entity that initiates communication with the web
server and then the server provides the information required. In simple
words, the client is a program, device, or user that requests services
or resources from the devices, such as the web server. The communication
and relationship between these two is called the server-client model.
The following are the general server-client model steps that will help
to understand the whole scenario:
The client sends an HTTP request to the server. The request includes the URL of the web page that the client wants to retrieve.
The
client (when the user requires data) sends an HTTP request to the
server. This request may include the URL of the web page from which the
client wants to retrieve the information.
The server receives
the request instantly and processes it. It does it when it looks up the
URL saved in its database to find the corresponding web page file a
client requires.
If the web page file is found, the server sends
it back to the client in the form of an HTTP response. This response
also includes other important types of information, such as the page's
content type and expiration date, etc.
The client then receives
the response and renders the web page on the user's screen. The client
uses the content type information to determine how to display the web
page.
If the page is not found in the URL database, the server shows the error.
Web browsers like Chrome, Firefox, and Safari are examples of clients.
ESP32 as a Web Server
The ESP32 is a microcontroller famous for its wireless capabilities, which makes it ideal for a large number of fields, especially IoT. We are talking about WiFi connectivity as a web server and here are the key features of this module related to it:
The ESP32 is made under the IEEE 802.11b/g/n standards; therefore it has a 2.4 GHz frequency band. Therefore, it can be used as:
Common WiFi routers
Access point
The built-in WiFi capabilities of the ESP32 allow it to be used as a server and carry out the easiest and most effective communication at a distance without any physical connection.
It has three operating modes:
In station mode, the ESP32 is operated as a WiFi client. It means it can be connected to the existing Wi-Fi network. (We are covering today)
In access point mode, it is operated as a WiFi access point; therefore it allows other devices to create a connection with it. (will be covered in the next lecture)
In dual mode, it can act as a server and as a client and allow the features of both at the same time. (will be covered in the 3rd lecture of section 2)
It has a dual processor that helps in handling multiple tasks at the same time. Therefore, ESP32 is more capable of managing a large network of devices and making it responsive for concurrent connections.
It has asynchronous web server libraries, such as “ESPAsyncWebServe” to handle the HTTP requests asynchronously. These are useful because they allow it to effectively manage the connections without blocking the execution of other tasks.
ESP32 has multiple security protocols that are used when creating the web server. As a result, it provides secure and protective communication between the devices.
It has over-the-air updates, which means it can update the device's firmware without physically accessing it. It helps with remote updates and maintenance.
The ESP32 is suitable for use as a server because of its multiple features, including:
It can serve static files
It can handle different HTTP methods (GET, POST, etc.)
It supports features like server-side scripting
The WebSockets feature of ESP32 allows it to carry out bi-directional communication between servers and clients. You will learn about both of these in just a bit.
The ESP32 supports WiFi Direct, which is also referred to as the Peer to Peer (P2P); therefore, it can form a direct connection with other devices with no need for an external WiFi network.
ESP32 WebServer Working Principle
We know that the ESP32 has a built-in WiFi feature. This makes it suitable to use as a server. The example of the server-client relationship we have just discussed shows the internet connection of the whole world. The ESP32 can be used for the intranet connection, which is defined as:
"An intranet is a private network that has limited functionalities and is only accessible to users within a specific organization/location."
Usually, this network may consist of different devices, such as mobile phones, computers, laptops and tablets. The Arduino IDE is for the programming of the ESP32, just like we have done in the previous session. If your Arduino IDE is ready with the boards and ports, then let us try the built-in example of the ESP32 to use as a server.
What is an SSID?
An SSID is a service set identifier that is the unique name of a wireless local area network (WLAN).
It can be 32 characters long.
It may include numbers, letters, and signs.
The SSID can be set by the user as well.
In simple words, the SSID is the name of the WiFi connection people use for their connection.
In the experiment we are just performing, the user has to replace the SSID with their own SSID to connect with the ESP32.
Using the ESP32 Server Built-in Example
Using the ESP32 as a server is easy with the web server example. It has the basics, and here are the steps to follow:
Open the Arduino IDE.
Connect the esp32 to your system through the cable. Make sure the ESP32 is connected accurately.
Click on tools>boards>ESP32>Node32s. This is my board and you can choose according to the model of ESP32.
Go to the files> examples>examples of Nose32s>WiFi and from the side menu, choose “SimpleWifiServer".
It will create a new project with the code in it to run the ESP32 (connected to your system) as a server.
Press the encoder (EN) button of the ESP32.
Change the SSID and password according to your choice. In my case, it is PTCL-BB.
Go to lines 38, 103, and 106 by one and replace the pin “5” digit with pin “2” because the built-in light is at pin 2.
Replace lines 70 and 71 with the following:
client.print("Click <a href=\"/H\">here</a> to turn the LED on pin 2 on.<br>");
client.print("Click <a href=\"/L\">here</a> to turn turn the LED on pin 2 off.<br>");
All the instructions are given in the code. Go to line 30 and place your SSID there.
Go to line 31 and enter the password of your choice.
Read the code carefully and hit the “verify” button.
Once the code is compiled, press "Boot" on the ESP32 when the uploading process is carried out.
Wait for the loading to complete.
Click on the “Serial Monitor” button at the upper right corner of the screen to open the monitor. You can go to Tool>Serial Monitor for the same task.
Choose the baud rate of 115200 from the drop-down menu at the right corner of the monitor.
Right now, the monitor is blank:
Click the EN button on the EPS32 to see the information.
Now that the monitor has data and is loading, it starts to connect with the WiFi connection of the system.
Once the loading is complete, it will provide the IP address. Copy this address.
Go to the new tab in the browser and paste the address there.
You will see that merely placing the “H” or “L” just after the IP address (as given in the code comment) will turn on and off the LED on ESP32 according to the URL.
Note: Make sure you have installed the port and board before you try this code and have selected all the right options; otherwise, you can face errors.
ESP32 Server as Messenger
The ESP32 can be used to send the message through the browser.
The microcontroller connects to the internet connection of the system.
The serial monitor shows the IP address.
The ESP32 acts as a server and through the URL of the browser, the user will send the message to the Arduino IDE.
This message will be shown on the serial monitor.
The user can change the message through the URL pasted in the web browser.
Material Required
Internet connection
System (e,g, laptop)
ESP32 microcontroller
Connecting cable
Code for ESP32 as Server
#include <WiFi.h>
const char *ssid = "My-SSID";
const char *password = "My-Password";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop() {
WiFiClient client = server.available();
if (client) {
Serial.println("New Client.");
while (client.connected()) {
if (client.available()) {
String request = client.readStringUntil('\r');
client.flush();
// Check if the request contains a specific message
Make sure you have the respective port and board installed successfully.
Connect the right port and board.
Paste the code given above into the new project.
"Verify" the code by using the button.
Once verified, compile and upload the code.
Once the code is compiled, press the Boot button.
Once the installation is completed, go to the serial monitor.
Press the EN button.
The serial monitor will show the information. Copy the IP address shown on the end of loading.
The general ULR for sending the message through the server is given as: http://esp32-ip-address/message?message=Hello
To send the “Hello” message to the ESP32 through the browser, use your IP address and the message. In my case, I am pasting the following URL in the browser: http://192.168.43.251/message?message=Hello
Once reloaded, go to the serial monitor and check for the message:
For the demonstration purpose, we will create a webpage and will launch it through our ESP32 module, so ESP32 will be acting as a web server, serving the page.
This webpage will have 3 Buttons on it, which will be controlling three LEDs, we will turn ON or OFF respective LEDs using these buttons.
WebServer Page is shown in the below figure:
Now the question arises, how will ESP32 understand which Button has been pressed?
For that, we have created multiple links i.e. the HomePage Url will look like:
http://192.168.43.188/
When a user will click on LED 26 ON Button, we will redirect the user to:
http://192.168.43.188/26/on
Now, when the client wants to turn OFF the LED, we will redirect to:
http://192.168.43.188/26/off
So, actually, we are checking the request from the client and based on that request we are turning ON or OFF the respective LED.
Moreover, we are providing the same webpage to all the links but with the change in the state of each button i.e. if it's ON then Blue, otherwise Green.
If it looks too complicated, don't worry. These things will get more clear when we will cover the Arduino coding.
ESP32 Wi-Fi module includes a number of useful characteristics, including the ability to use a soft access point mode, a station mode, or both modes at the same time. Only station mode will be discussed in this session. I'll also cover how to use this board in soft access mode in future tutorials.
Station Mode: The ESP32 board connects to your Wi-Fi network via a router in Station mode. The router serves as the communication channel between the web client and the ESP32. The IP address is obtained from the Wi-Fi router. Web clients can connect to the Web server using this IP address across a local network.
Access Point Mode: In this mode, the ESP32 creates its own wireless Wi-Fi network, similar to the one provided by your existing router. We don't need to connect the ESP2 to a Wi-Fi network in this mode. This Wi-Fi board can link up to 5 devices to the Wifi network it creates.
Controlling peripherals Using ESP32 Web Server
Connect the peripherals to the ESP32 board which you want to control through the ESP32 Web Server.
Here, we are going to control two external LEDs connected to LED1 (GPIO 26), LED2 (GPIO 27), and an inbuilt LED.
The following are the requirements for creating an ESP32 webserver to control peripherals:
ESP32 module
Internet connection
LEDs
Resistors
Connecting Wires
Arduino IDE Code
Using the Arduino IDE, upload the following code to the ESP32 module:
#include
// Replace with your network credentials
char* ssid = "ESP32"; //enter SSID
char* passphrase = "asdfgf@123"; // enter the password
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// Auxiliar variables to store the current output state
String output26State = "off";
String output27State = "off";
String builtin_led_state = "off";
// Assign output variables to GPIO pins
const int output26 = 26;
const int output27 = 27;
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
void setup() {
Serial.begin(115200);
// Initialize the output variables as outputs
pinMode(output26, OUTPUT);
pinMode(output27, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
// Set outputs to LOW
digitalWrite(output26, LOW);
digitalWrite(output27, LOW);
digitalWrite(LED_BUILTIN, LOW);
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, passphrase);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop(){
WiFiClient client = server.available(); // Listen for incoming clients
if (client) {
// If a new client connects,
currentTime = millis();
previousTime = currentTime;
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
currentTime = millis();
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// turns the GPIOs on and off
if (header.indexOf("GET /26/on") >= 0)
{
Serial.println("GPIO 26 on");
output26State = "on";
digitalWrite(output26, HIGH);
}
else if (header.indexOf("GET /26/off") >= 0)
{
Serial.println("GPIO 26 off");
output26State = "off";
digitalWrite(output26, LOW);
}
else if (header.indexOf("GET /27/on") >= 0)
{
Serial.println("GPIO 27 on");
output27State = "on";
digitalWrite(output27, HIGH);
}
else if (header.indexOf("GET /27/off") >= 0)
{
Serial.println("GPIO 27 off");
output27State = "off";
digitalWrite(output27, LOW);
}
else if (header.indexOf("GET /LED_BUILTIN/on") >= 0)
{
Serial.println("BUILTIN LED on");
builtin_led_state = "on";
digitalWrite(LED_BUILTIN, HIGH);
}
else if (header.indexOf("GET /LED_BUILTIN/off") >= 0)
{
Serial.println("BUILTIN_LED off");
builtin_led_state = "off";
digitalWrite(LED_BUILTIN, LOW);
}
// Display the HTML web page
client.println("");
client.println("");
client.println("");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println("");
// Web Page Heading
client.println("
ESP32 Web Server
");
// Display current state, and ON/OFF buttons for builtin led
client.println("
LED_BUILTIN - State " + builtin_led_state + "
");
// If the LED is off, it displays the ON button
if (builtin_led_state=="off")
{
client.println("
");
}
else
{
client.println("
");
}
// Display current state, and ON/OFF buttons for GPIO 26
client.println("
LED_1 - State " + output26State + "
");
// If the output26State is off, it displays the ON button
if (output26State=="off")
{
client.println("
");
}
else
{
client.println("
");
}
// Display current state, and ON/OFF buttons for GPIO 27
client.println("
LED_2 - State " + output27State + "
");
// If the output27State is off, it displays the ON button
if (output27State=="off")
{
client.println("
");
}
else
{
client.println("
");
}
client.println("");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
Note:
You need to modify the SSID and password with your network credentials.
Code Description:
Here, we'll take a closer look at the code to see how it works.
The first task is to add a Wi-Fi library.
As mentioned previously, you must type your SSID and password inside the double quotes in the following lines.
As we are creating a web server, so we need to assign a port to it and normally we use port 80 for a local webserver.
So, in the below code, Port 80 is assigned to the webserver and then initialized a few variables:
String header: variable to store the header of the HTTP request.
Below the header variable, we have variables to store the current state of connected peripheral LEDs and built-in LED. If you wish to add more peripherals and save their states, you need to create more variables. By default, all LEDs are in the OFF state.
Next, assigned GPIOs to each peripheral device or component. Here we are using GPIO 26(LED1) and GPIO 27(LED2). You can use any other suitable GPIOs.
Lastly, we have initialized a few variables to check the connection timeout, we will check their working soon.
Arduino Setup() Function
Now let's first have a look at the Arduino setup loop.
First, we have initialized our Serial Port at a baud rate of 115200, so that we could monitor the results at the serial terminal.
Define the GPIOs as OUTPUTs and set them to LOW, as by default LEDs will be off.
To set up a wifi connection, we called the WiFI.begin() and here we have provided our SSID and passphrase as variables.
Now our ESP32 will try to connect to the provided WiFi connection.
As you can see, we have a while loop, where we are checking the WiFi Status.
If ESP32 gets connected with WiFi, the while loop will break and a message will get printed on the Serial Monitor "WiFi Connected".
Now our ESP32 is connected to the WiFi, so the router must have assigned an IP address to ESP32 and we are printing it on Serial using WiFi local IP Function.
Finally, we begin our server, to which we have assigned Port 80 at the start.
Arduino Loop() Function
Now, we are done with all the basic settings in the setup function. Let's have a look at the code in the Loop function:
At the last line of the Setup function, we have started our webserver, so now ESP32 is acting as a webserver and is waiting for incoming clients.
But what will happen, when someone will hit the IP Address of this webserver?
So, in the loop function, first of all, we are listening to the incoming client using the server.available() function.
If any client is available i.e. someone has entered our IP Address in the browser then we will print the HTML page.
So, we are going to write the rest of our code in this IF loop.
AS you can see in the below code, if the client is available, we have printed "New Client" on Serial Monitor.
After that, we have a while loop checking for client connection, so as long as we have a connection with the client, we will remain in this loop.
Inside this while loop, we have an If loop, checking if the client is available.
Now, if we are connected to the client, we need to read for the incoming request.
So, If there are any bytes to read from the client, read those bytes:
The client request ends at New Line Character \n, so we are checking for that.
Once we received the New Line Character, we are sending the response back to the Client.
In response, we have first sent the HTTP header, which is the default for webpages so that browsers should understand the response type.
Checking Request Type
As we discussed earlier, on each button press, we are redirecting our client to its respective link.
Depending on which button is pushed, we make requests to different URLs to turn the LEDs on and off using if else statements, as shown below:
As you can see in the above code, we are repeating the same code three times for 3 LEDs.
In the first block, we are simply checking the header response and if it's a GET request and from "/26/on", we have turned that Pin HIGH, changed the LED state variable to "on" and sent a message on the serial monitor.
So, if a client clicks on the LED 26 ON button, ESP32 will understand the GET request and glow the LED.
The other buttons work in the same way. If you wish to add more outputs, you'll need to change this section of the code.
HTML to display a web page
We have designed the output part i.e. what we are going to do when a user clicks any button.
And now we are going to design those buttons themselves i.e. we are designing the webpage.
As you can see in the below figure, we have standard HTML tags at the start.
After that, we have some CSS text to design the buttons and the appearance of the web page. We use the Helvetica font and set the information to be shown as a block with the center aligned.
Next, displaying Web page heading i.e. "ESP32 Web Server".
Next, comes the If Loop for the first Button, we are checking the LED state variable and based on LED state, we are displaying our Button.
So, if the LED state is OFF, we are redirecting the user to /LED_BUILTIN/on and vice versa.
That's how we are changing the Buttons on the webpage, as you can see buttons are using different CSS classes for on and off states.
Similar loops are used to display the states on other connected LEDs.
Finally, we are closing the web connection and clearing the header that was used to store the HTTP request header using client.stop() function.
Printing information about the closed web connection on the serial monitor.
Uploading Web Server Code to ESP32
Please reread the previous instruction, "Introduction to ESP32 programming series," if you are unfamiliar with the procedure of uploading code in the Arduino IDE.
After uploading the code, open the Serial Monitor with a baud rate of 115200.
Enable the ESP32 by pressing the EN (enable) button. The ESP32 establishes a Wi-Fi connection and the Serial Monitor displays the ESP32 IP address. To connect to the ESP32 web server, you'll need that IP address.
Note:
Make sure you have selected the right board and COM port.
Getting IP address and Access ESP32 web Server
After successfully uploading the code in esp32 module.
Open Serial Monitor from the top right corner of Arduino IDE screen as shown in figure below:
The IP address required to connect to the ESP32 point will be displayed on the Serial Monitor. It's 192.168.43.223 in this scenario.
To access the webserver, type the IP Address of the ESP32 into a Web Browser on a laptop or a mobile phone. It's 192.168.43.223 in our case.
You should be able to see a simple web page served by the ESP32's Web Server if everything goes well.
A screenshot of a Web Browser on a laptop accessing the ESP32 Web Server is shown below.
The image below is displaying the ONstate of the inbuilt LED.
The inbuilt LED is Blue in color.
The below image is displaying the OFF State of the inbuilt LED
Hence, We have done a lot of work on the ESP32 by using it as a server. In the beginning, we saw what is a web server and studied its features in detail. After that, we saw that ESP32 can be used as a server and we saw the feature that makes it ideal for this task. Then we experimented to learn the concept, in which we saw the built-in example of ESP32 as a server in Arduino IDE. We saw the step-by-step procedure to experiment and once it was completed, we moved on to a more complex example. I hope you find this tutorial useful and have performed it by yourself but if you are stuck at any point, you can ask in the comment section.
Using the ESP32 web server and the preceding process, you can control the peripherals linked to the ESP32 module from any mobile, tablet, or computer. The only need is that all of the devices to be linked to the same network.
This concludes the lesson. I hope it becomes useful to you. In the next tutorial, we will have a look at How to work the ESP32 BLE, so stay tuned. Have a good day. :)
Hello friends, I hope you all are doing great. In today's tutorial, we are going to design a Proteus Simulation for Automatic Plant Watering System using Arduino. We have designed this project for engineering students as it's a common semester project, especially in electrical, electronics and mechatronics engineering.
The two most significant hazards to the agriculture industry are the need for extensive labor and a scarcity of water. According to the World Wildlife Fund (WWF) organization, water shortages might affect two-thirds of the world's population by 2025, putting both the ecosystem and human health at risk. The use of automatic plant watering systems eliminates both of these problems by watering plants at specified times and amounts while monitoring their hydration levels through measuring moisture in the soil surrounding the plants. Automatic plant watering systems can be used in homemade gardens and can also be deployed in fields for large-scale use. Whenever designing an automatic watering system, it is important to keep in mind that the system should be expandable, allowing for the simple integration of new devices in order to broaden the applicability of the system.
We are not designing this project using real components, instead, we are going to design its Proteus simulation. So, first of all, you should Install Proteus Software itself. Proteus software has a big database of electronics components but it doesn't have modules in it. So, we need to install Proteus Libraries of a few components, so that we could simulate them. So, these are the PRoteus libraries which you should install first, before working on this project:
You can download this complete project i.e. Proteus Simulation & Arduino Code, by clicking the below button:
Download Complete ProjectNote:
You should also have a look at these other Proteus Libraries:
Three main components of an autonomous watering system are:
Water Level Sensor: monitors the water reservoir level.
Moisture Sensor: monitors the soil moisture level.
RTC module: responsible for supplying water to the plant at predetermined intervals or at a predetermined time.
Arduino UNO: serves as a hub for connecting and controlling all these components.
It is necessary to integrate the water level sensor with the microcontroller before it can be installed within the water reservoir. The location of the water level sensor within the reservoir is variable and is determined by the user and the application for which it is being utilized. The Arduino receives continuous data from the water level sensor and warns the user when the water goes below a certain level, either by an alarm or a buzzer, as appropriate.
The soil moisture sensor operates in a manner similar to that of the water level sensor. The tip of the sensor is inserted into the soil near the plant, and the sensor is activated. In the case of a moisture sensor, the closeness of the sensor to the plant is also variable, and the user may adjust it depending on the features of the plant for which it is being used. In vast agricultural fields, a single sensor may be used for numerous plants if they are closely spaced and their hydration levels can be determined by measuring the soil moisture at one location that overlaps with another spot on the soil surface.
The RTC module operates on the same concept of time monitoring in the background as other electronic devices such as computers and smartphones; even when these devices appear to be turned off, they continue to keep track of the current time. The RTC module, on the other hand, is capable of exchanging time information with the Arduino board. On a specific day of the week, at a specific time of day, the Arduino is pre-programmed to turn on the water pump and turn off the water pump after a specified length of time.
Components Needed:
Arduino UNO
Water Level Sensor
Moisture Sensor
RTC Module (DS1307)
LCD
4 LEDs
Buzzer
Relay
Water Pump
PCF8574
Component Details:
Arduino UNO:
Arduino UNO is a programmable microcontroller board.
It contains Atmel's ATMega328 as is based on that microcontroller.
The Arduino board also contains an in-built voltage regulator to protect it from burning out and supports serial communication to help programmers.
The Arduino board is culturally programmed through the Arduino App designed by the board's developers and the programming is done in C language.
The Arduino App compiles code and interfaces the firmware into the Arduino hardware.
Arduino UNO has 14 digital I/O pins out of which 6 are PWM pins as well.
Arduino also takes analog inputs and has 6 analog input pins.
Figure # 1: Arduino UNO
Soil Moisture Sensor:
The soil moisture sensor is a resistive sensor that consists of two electrodes with a small charge and the resistance in those electrodes is measured and then the resistance in between the soil is used to find the moisture levels.
A soil moisture sensor normally comes equipped with an amplifier such as LM393. It has a VCC, GND and analog output pin.
Figure # 2: Soil Moisture Sensor
Water Level Sensor:
The water level sensor is a module that helps calculate the amount of liquid in a container.
When a liquid is present in the tank, the Submersible level sensor detects the hydrostatic pressure generated by the liquid.
Since hydrostatic pressure is a measure of two variables, the first of which is the density of the fluid and the second of which is the height of the fluid, it is a useful tool.
Figure # 3: Water Level Sensor
RTC Module:
RTC stands for real Time Clock and as the name suggests the module keeps track of time even when the external power supply is cut off.
It has a battery cell installed within it for that purpose, moreover, it is capable of communication with other devices such as Arduino too.
Figure # 4: RTC Module
Relay:
Relays are basically electrical or electromechanical switches that operate on the principle of magnetic field controlling the switching within the relay.
A relay has two modes of operation, normally open and normally closed.
Figure # 5: 12V Relay
PCF8574:
The PCF8574 is a silicon-based CMOS integrated circuit.
Using the two-line bidirectional bus enables general-purpose remote I/O extension for the majority of microcontroller families (I2C).
It is used in our project for I2C communication of LCD.
Figure # 6: PCF 8574
Proteus Simulation of Plant Watering System
Now, let's design the Proteus Simulation of Plant Watering System first and then will work on the Arduino Code.
First of all, make sure that Proteus is installed on your computer and download all the necessary libraries for Proteus beforehand.
For this project, you will need libraries for Arduino, LCD, RTC Module, Water Level Sensor and Soil Moisture Sensor. Make sure that you read how to use each library in Proteus as well.
Open a new project on Proteus, import all the components required and place them within the working area or the blue line of Proteus.
Select below components from Proteus Components' library:
Circuit Diagram and Working:
Now, place these components in your Proteus workspace, as shown in the below figure:
For the water level and moisture sensor, place a variable POT(potentiometer) at the test pin and place an RC filter at the output pins. (This is only for simulation purposes)
Start with the input side of Arduino and connect the soil moisture, water level output pins to the A1 and A0 pins of Arduino respectively.
To use the LCD for I2C communication, Place PCF8574 and connect with LCD.
Connect the SDA and SCL pins of PCF8574 and the SDA and SCL pins of the RTC module with the SDA and SCL pins of Arduino.
For the output side of Arduino, Connect the D7 to the relay controlling the pump.
Connect the buzzer at D2 and the LEDs to their respective Arduino pins as well.
Make sure appropriate power and ground are provided to each component. With that the making of the circuit on Proteus is complete.
Figure 7 shows the circuit diagram of the system. Proteus was used to simulate the circuit and Arduino App was used for the simulation of the Arduino code. The circuit was designed in a way that is easy to understand and further integrated easily. We will now go through a step-by-step guide on how the circuit was built.
Figure # 7: Proteus Circuit diagram
Arduino Code for Plant Watering System
A normal Arduino code has two main segments:
void setup
void loop
We will look at both of them separately here.
Declaration Code
The first step in setting up our code is defining libraries, download if you don’t have any libraries already integrated in the Arduino App.
Figure # 12: Arduino Code
The next step in the code is tone definition for buzzer and pin definition of variables being used in the project.
Figure # 13: Arduino Code
After pin definition, the variables used must be defined so that Arduino knows where to find them and how to identify them.
Figure # 14: Arduino Code
The next step is defining the system messages that will appear on the LCD.
It is not necessary to define those messages in the setup, they can be easily defined within the main code but it is an easier way to define those beforehand and call them whenever needed.
This is especially useful when a system message is used multiple times in the code.
Figure # 15: Arduino Code
Now we define the objects being used in the project.
The two objects being defined are the RTC module and LCD. In the syntax below we used 20x0 in the argument for the LCD, that is because there are no libraries for I2C LCDs and we had to turn a simple LCD into an I2C LCD by the means of PCF8574.
Figure # 16: Arduino Code
Void setup:
Now we start the programming of void setup.
At first is the initialization of various components, such as initializing the RTC module and setting the time and date of RTC with respect to our computer.
Wire initialization and library are used for I2C communication.
Figure # 17: Arduino Code
The next step is defining the digital pins of Arduino being used as input or output pins and displaying the initial message on our LCD.
Figure # 18: Arduino Code
Void Loop:
The first step in the loop is to read the date and time from the computer through the RTC and read the values from the sensor.
Since this part of the program runs in the loop, Arduino will keep reading and refreshing the sensor inputs every time the loop starts.
Figure # 19: Arduino Code
In the next segment of the code, we will check various conditions of the sensor values and RTC and actuate our outputs on the basis of these conditions.
At first, we check the water level of the container, if it is below the set level, Arduino will actuate the buzzer to alarm the user of low tank on LCD.
Figure # 20: Arduino Code
In the next step, we check the values of the moisture sensor and place the conditions in three categories, namely, moist soil, soggy soil and dry soil.
The Arduino will light up the respective LED whenever its condition is true. Red LED for dry soil, yellow LED for soggy soil and green LED for moist soil.
The LCD will also display respective messages for each of those conditions.
The following code is for the condition of dry soil.
Figure # 21: Arduino Code
The following code is for the condition of moist soil.
Figure # 22: Arduino Code
And finally the code for the condition of soggy soil.
Figure # 23: Arduino Code
In the next step of the code, we check the condition of time, whether it is time to water the plants or not and the condition of the water reservoir to see its level as well.
Figure # 24: Arduino Code
If you see the code closely, you may see the function of the right hour, which is called various times in the main code. The function code in itself is written at the bottom of the main code. This function is used for displaying the time and date on the LCD and also for fixing the date and time.
Results/Working
Open Arduino and generate a hex file for that program.
Put the hex file in the Arduino UNO board placed in Proteus.
Run the simulation.
Figure # 8: Proteus circuit simulation when soil is soggy
Figure # 9: Proteus circuit simulation when soil is moist
Figure # 10: Proteus circuit simulation when soil is dry
Figure # 11: Proteus circuit simulation when soil is dry and it is time to water the plant
As you can see from figure 8 that our simulation is running according to the program set at Arduino. You can increase or decrease the values coming from the sensors through the Potentiometer.
So, that was all for today. I hope you have enjoyed today's lecture. If you have any questions, please ask in the comments. Thanks for reading.
Hello everyone, I hope you're all doing well. In the previous lecture(Chapter 0: ESP32 Pinout), we discussed the ESP32 features & specs in detail. Today, we are officially starting this ESP32 Programming Series. In this ESP32 Programming Series, we will start with basic concepts and
will gradually move towards complex topics. I will try to keep this
ESP32 series as simple as I can. But still, if you encounter any issues,
please ask in the comments, will try to resolve the issues as soon as
possible.
As ESP32 has numerous features & applications, so I have divided this series into different sections. I have named the 1st section "ESP32 IDEs". In this section, we will discuss different IDEs used to program ESP32 boards. In each Chapter of this section, we will install one of these ESP32 IDEs and will test a simple LED Blinking Code in it. We will set up the ESP32 Development Environment for Windows, Mac, and Linux users.
As I am sharing the 1st Chapter today, so first we will unbox the ESP32 board, set up the most commonly used ESP32 IDE i.e. Arduino IDE, and test a simple WiFi Scan Code on the ESP32.
IDE is an abbreviation of Integrated Development Environment. IDE is a software package used to write & compile the code. As ESP32 is one of the most popular microcontroller boards, there are numerous third-party IDEs available to program it, and each IDE supports its own programming language. So, if you are a C# developer or an Arduino expert, you can quickly and easily get your hands dirty with ESP32. The below table shows the most commonly used ESP32 IDEs along with their supported programming language:
ESP32 IDEs
No.
ESP32 IDEs
Programming Language
1
Arduino IDE
Arduino C
2
Thonny IDE
MicroPython
3
Visual Studio Code
Arduino C
4
PlatformIO IDE
C++
5
ESP-IDF(official IDE by EspressIF)
C
6
nanoFramework
C#
In today's lecture, we will install the Arduino IDE and configure it for ESP32 Programming. So, let's get started:
Install ESP32 in Arduino IDE
First of all, we need to install the Arduino IDE itself. To program ESP32 with Arduino IDE, we need to install the ESP32 Boards
in Arduino IDE. Before installing the ESP32 Boards, we first need to add
a JSON File containing information about ESP32 Boards. JSON format is
used to share information between two computers. So, this JSON file will
add the information of ESP32 boards in the Arduino IDE. So, let me summarize these 3 steps in proper order:
Installing Arduino IDE
Adding ESP32 JSON File
Installing ESP32 Boards
Installing COM Port Driver for ESP32(if COM Port not detected automatically)
Installing Arduino IDE
We need to first download & install the Arduino IDE.
Download Arduino IDE from its official website, make sure to download the latest version.
Installing Arduino IDE is quite simple, but if you are having issues, have a look at this Arduino IDE Installation Guide.
After installing the Arduino IDE, we need to add the ESP32 JSON File in it. So, follow the below steps:
Open Arduino IDE and navigate to "File > Preferences", as shown in the below image:
In the Arduino Preferences Window, you will find a textbox named "Additional boards Manager URL".
Add the ESP32 JSON File link(provided above) in it, as shown in the below figure:
If you have already added any third-party board URLs, then add a comma (,) between the JSON links OR click on the button and it will open up a new window, add URL in the new row, as shown below:
Click "OK" to close the Preference Window.
Once you close the Preference Window, Arduino IDE will extract the information of all ESP32 boards by downloading the ESP32 JSON file.
Now, we are ready to install the ESP32 Boards in Arduino IDE:
Installing ESP32 Boards in Arduino IDE
In the Arduino IDE, click on "Tools > Board > Board Manager", as shown in the below figure:
It will open up a Board Manager Window in Arduino IDE.
From this Board Manager, we can install the packages for third-party modules.
In the Board Manager, make a search for "ESP32" and you will get many third-party ESP32 packages.
Here, we need to install the "ESP32 by Espressif Systems" as it's the official package, I have highlighted it in the below image:
So, click on the Install button to install ESP32 boards in Arduino IDE.
Arduino IDE will take some time to install the ESP32 package.
Once installed, click on "Tools > Boards > esp32" and you will find a list of newly added ESP32 boards, as shown in the below figure:
From this list, we will select "ESP32 DEV KIT V1", it's the most commonly used ESP32 board.
In the COM Port, select the available COM Port, in our case, it's COM5:
In some cases, the Arduino IDE won't automatically detect the ESP32 COM
Port, so here we need to install the COM Port driver for ESP32. Let's do it:
Installing ESP32 COM Port in Arduino IDE
If you don't find the ESP32 COM Port in the Port Section of Arduino IDE, then you need to install the COM Port Driver manually. So, follow the below steps:
Download the Windows COM Port Driver by clicking the below button and install it on your computer:
If you are using 32-bit Windows, then install the x86 version and if working on 64-bit Windows, then install the x64 version.
After installing this COM Port Driver, restart your Arduino IDE and it's recommended to restart your computer as well.
So, we have successfully installed the ESP32 Boards in the Arduino IDE. Now, let's upload a simple LED Blinking Code in the ESP32:
Code Upload to ESP32 from Arduino IDE
Now that the Arduino IDE is ready to handle the ESP32 Dev Kit module, you can write the code for the ESP32 module. We will just upload a simple WiFi Scan Code to verify that our ESP32 installation is correct.
Open Arduino IDE and navigate to "File > Examples > WiFi > WiFiScan".
Click on the Tools and verify that you have selected the correct ESP32 board and the COM Port.
Now, click the "Upload
" button to upload the code to the ESP32 board.
If the code is uploaded successfully in the ESP32 board, you will get the confirmation message in the Output pane, as shown in the below figure:
Now open the Serial Terminal and you will start receiving the List of all available WiFi connections, as shown in the below figure:
That concludes today's discussion. We hope you found this post informative. In the next tutorial, we will install the ESP32 Boards in the Visual Studio Code. If you have any questions, please ask in the comments. Take care. Have a good day.
Security systems are widely suggested for homes as well as other locations. Everybody wants to take necessary steps to prevent infiltration at home, thus this security is necessary. Intruders nowadays may take advantage of almost any illegal activity and wreak havoc on a property's security. The security of one's home is a critical concern that everyone faces in the current day.
While there are certain devices on the market that may considerably help protect your house, some of them are excessively costly and need constant maintenance. Many devices regarding smart home security systems are available in the market but these are not user friendly according to the budget, the device we designed provides the user with a better interface with the help of LCD. We have used enough sensors that make sure the security protocol.
So in this way, we designed a reasonable security system that has the features of gas and flame detection with the help of MQ-2 Gas Sensor and flame sensor respectively and also have installed a Motion detector sensor known as PIR sensor to detect the intruder's motion. For a better user interface an LCD and Alarm are installed to alert the user. The whole system is programmed using Arduino UNO. A proteus circuit is designed for this project as shown below:
You can download the complete project i.e. Proteus Simulation and Arduino Code by clicking the below button:
For the home security system, we have used 3 sensors which are briefly explained as follows:
Flame Sensor
The flame sensor is used to detect the fire, it has 3 pins (Ground, VCC, OUTPUT) with operational voltages ranging from 3.3V to 5V.
This sensor may be constructed using an electrical circuit and a receiver similar to that used for electromagnetic radiation.
This sensor employs the infrared flame flash technology, which enables it to operate through a layer of oil, dust, water vapor etc.
There are several wavelengths of flame sensors normally in the range of 700 to 1100 nm from the source.
Normally flame sensors have an operating temperature ranging from -25? ~ 85? with several features like adjustable sensitivity, fast response time and ease to use.
MQ2 gas sensors detect the presence of gases such as LPG, methane, ethanol and carbon monoxide in the air ranging up to 10000 ppm using electricity.
It is also known as chemiresistor for the MQ2 gas sensor.
The resistance of the sensing material changes depending on the amount of gas present.
When it comes to detecting gas, sensors use variations in resistance value that generates the output voltage.
When a sensor material is heated to a high temperature in the air, oxygen is adsorbed on the surface.
Because current can flow via the sensor, its analog voltage values may now be read.
The voltage values reported here may be used to compute the concentration of a gas. When the gas concentration is high, the voltage values are greater.
This whole project is designed to provide a security system for the home in which multiple safety sensors can be installed with a Buzzer and LCD for a better user interface.
We won't design this project in real, instead, we are going to design its Proteus simulation.
If you are working on an electronics/embedded project, then it's always a best practice to design its simulation first.
In simulations, it's easy to debug your code and thus you can program quickly.
Once you are satisfied with your project's working, you can move forward to hardware designing.
So, let's design our Proteus Simulation for Smart Home Security System:
Proteus Simulation
These are the components, which we are going to use for designing our Proteus Simulation:
So, select these components from Proteus Components Library and place them in your workspace, as shown in the below figure:
Next, we need to connect these components' pins to complete our circuit, as shown in the below figure:
As you can see in the above simulation, we have used three sensors in total, which we have discussed above.
So, now we are going to design the Arduino Code for this simulation:
Arduino Programming Code
We have designed the circuit in our Proteus Simulation and next, we need to design its Arduino Code, in order to make it work.
LCD Initialization Code
First of all, we are going to interface LCD with Arduino UNO and will display the Project's name on the screen.
The code is shown in the below figure:
As you can see in the above figure, we have first initialized the variables.
Arduino board is programmed using Arduino IDE software which has mainly 2 sections void setup and void loop.
Before void setup, we have to declare the pins of sensors and actuators that we are using in our project.
Depending on the nature of sensors (analog or digital) the pins of sensors are connected to Arduino UNO accordingly.
#define is used to declare the pins of Gas, PIR, FIRE and BUZZER.
Initially, all the sensors have zero value that is stored by an integer variable.
In the void setup section, input and output sensors are defined.
GAS, PIR, and FIRE sensors are employed as input sensors to detect and activate the BUZZER, which is an output component.
LCD 20×4 is used and lcd.begin is used to initiate the LCD.
lcd.setCursor is used to cursor position on LCD and the name of the project is displayed on LCD Screen using lcd.print command.
Now, let's run our simulation to check the results, shown in the figure below:
Sensors Interfacing with Arduino
In Arduino IDE code execution, void setup runs once while the void loop executes again and again.
analogRead and digitalRead commands are used to read the value of analog and digital sensors respectively, while analogWrite and digitalWrite commands are used for sending commands or data.
As shown in the above figure, first, we have read the sensors' data and if all sensors are in LOW state, then have displayed the message "You are safe".
Let's run the code to check the output:
As you can see in the above figure, all sensors are at a LOW state and thus LCD is displaying the safe message.
Next, we have added the if loop for the case where all sensors are giving HIGH value:
The rest of the code has similar if loops for various conditions of sensors.
You can download the complete code and Proteus Simulation from the link, given at the start of this tutorial.
Now, let's run our final simulation and test the sensors and if everything goes fine, you will get results as shown in the below figure:
Future Recommendations
It deters the crime and notifies the user about the gas or fire problem. Home security systems are mostly utilized for safety reasons in residences, businesses, and educational facilities. Another option is to use a mobile device or the internet to send data to a remote location. Other modules, such as a wind sensor or a fire sensor, might be added to the system in the future. Voice alarm modules may also alert you to an intruder or a gas leak if you use them. We can increase the number of sensors to make it better. We can use the latest technology of the Internet of Things that makes our system wireless. A growing number of devices and goods are being connected to the Internet, which is referred to as the Internet of Things by the phrase. We can use the Internet of Things to produce a low-cost security system for residential and industrial applications that is especially useful for home security. When the door is opened or an unauthorized entry is detected, the system will send an alert to the owner. The user may take action after getting the notification. ESP8266 Wi-Fi module will connect to and interact with the Internet, while an Arduino Uno microcontroller keeps track of the system's status, as well as a magnetic Reed sensor for sounding the alarm. The principal advantages of this system are ease of installation, low costs, and low maintenance requirements.
So, that was all for today. I hope you have enjoyed today's project. If you have any questions, ask in the comments. Thanks for reading. Take care !!! :)
Hello everyone, we are back with a new project and we hope you all are doing well. In this article, we will discuss a project named Smart Irrigation System using Arduino UNO. We will use different sensors to measure the environmental and crop parameters which are responsible for good production. We will also make the water pump system automatic which will open the water valve automatically according to the soil moisture of the crop.
We will discuss all points and concepts briefly in this article and also provide a Proteus Simulation to observe how it will work in the real world. Complete fully explained code and simulation are also provided below as you go ahead in this article. You can download it from there.
In the late decades, there has been a quick advancement in Smart Agricultural Systems. Show that agriculture has great importance worldwide. Indeed, in India for example, about 70 % of the people rely upon the vital sector of agriculture. In the past, irrigation systems used to be dependent on the mills to irrigate the farm by conventional methods without knowing the appropriate quantities of these crops.
These old systems are a major cause of the waste of large quantities of water and thus destroy some crops because of the lack of adequate quantities of water. However, with the recent technological developments, there have been innovative systems for irrigation without the farmer interfering in the irrigation process. We will discuss it in brief below.
We will do a simulation on Proteus 8 Professional Software.
Working
The working of this project is like, we will use a Soil Moisture sensor for measuring the moisture of Soil according to which water valves are controlled. When the moisture level gets below a threshold value, valves will open with the help of a relay or solenoid till the soil is well moisturized.
The BMP180 sensor will measure the Atmospheric Pressure.
The DHT11 sensor will measure the temperature and humidity of the climate.
The MQ135 sensor will measure the Air Quality Index of the environment.
LDR will measure the sunlight intensity.
We will use a 20x4 LCD Screen for displaying the data gathered from the sensors.
And the main thing, we will use an Arduino UNO microcontroller as the brain of the project.
In a used case, when the moisture level gets below a threshold value, valves will open with the help of a relay or solenoid for a required time interval.
Block Diagram
Here's the Block Diagram of Smart Irrigation System:
Components Required
Here's the list of components used in this project:
Arduino UNO
BMP180 Sensor
DHT11 Sensor
LDR Sensor
MQ135 Gas Sensor
Soil Moisture Sensor
20x4 LCD Display
PCF8574 remote 8-bit I/O expander for the I2C bus
Breadboard.
Jumper wires (Male to Male, Male to Female, Female to Male.)
Since we are designing a prototype of this project, we will use jumper wires instead of soldering.
Power Supply
You can use a Battery, Adapter or any DC source of 5-8v(recommendable).
Circuit Diagram
Since we are making a prototype of this project, we will make connections on the breadboard and avoid soldering the components. We will use male to male, male to female and female to female jumper wires.
Pins Connections
These are the pin connections of all components.
Pin Connections of Smart Irrigation System
No.
Sensor
Pinout
1
Soil Moisture Sensor
Data - A0 (Arduino)
2
LDR Sensor
LDR-Resistor Junction - A2 (Arduino)
3
MQ135 Gas Sensor
Out - A1 (Arduino)
4
DHT11 Sensor
Data - D2 (Arduino)
5
BMP180 Pressure Sensor
SDA-SDA (Arduino)
SCL - SCL (Arduino)
Arduino Libraries Required
You need to install these third-party Arduino Libraries, in order to interface sensors:
Adafruit_BMP085.h
DHT.h
LiquidCrystal_I2C.h
We have added comments in the code for better understanding so it can be understood easily.
Note - Change the Address of the LCD Screen while you run the code in Proteus, change it to 0x20 instead of 0x27 or anyone else. In the real experiment, we can alter the address of the LCD by changing the configurations of A0, A1 and A2 pins of the PCF8574 module.
Proteus Libraries Required
We will show you a demo of this project as a simulation. We are using Proteus 8 Professional Software for the simulation.
This potentiometer defines the soil water content in the proteus simulation.
When the resistance is maximum at the test pin, the circuit shows zero volts across the voltmeter, which means the sensor is either in the dry ground or taken out of the ground, i.e. giving zero moisture value of the water content.
And when resistance is zero, the circuit will show the maximum voltage across the voltmeter which indicates the sensor is inserted in a wet ground i.e. water contents in the soil are too high.
This is important. We have attached the output pin with an LC filter. This filter is not required in real hardware implementation.
We are using it in Proteus Simulation only as Proteus gives the peak-to-peak value and we have to convert that PP value into Vrms.
If you are working on a real sensor then you don’t need to add this LC circuit.
Similarly for Gas sensor, as we increase the potentiometer, in simulation it means good air quality.
Steps for Simulation
These are the steps for simulation. Follow them to create a fully working simulation.
Download the Zip Files given at the start of this tutorial.
Extract them in the LIBRARY folder. You will find it inside the Labcenter Electronics Folder.
Go to Arduino IDE and open the code, go to Tools and select the board Arduino UNO.
Go to Sketch and Click on Export Compiled Binary. It will create a compiled .hex file of the code which will be used as the main program in the simulation ahead.
Open Proteus software and add components by searching like Arduino, DHT11, BMP180, 20x4 LCD, etc.
You can see the components listed here.
Note - We used a simple LED instead of the valve because the valve component is not available in the Software, simply replace the LED with a valve in a real project. Make connections according to the circuit diagram and add virtual terminals to Serial pins to see the readings and Data.
Paste the Program File here for all the sensors.
Paste the Compiled Binary File as a Program file of Arduino UNO.
Run the simulation and you can see the readings by opening the virtual terminal.
Observations and Results
In this simulation and project, you can see the sensor's information first in the terminal.
After that, we are getting well organized and easily understood data on the terminal by every sensor according to code.
According to the code, when the value of the soil moisture sensor gets less than a threshold value, the LED gets on.
This means when the soil gets dry the valve will open and water will be provided to the crops.
Syed Zain Nasir
I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>