ESP32 Bluetooth Classic in Arduino IDE

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:

Where To Buy?
No.ComponentsDistributorLink To Buy
1ESP32AmazonBuy Now

ESP32 Wireless Features

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:
    1. EATT (enhanced attribute protocol)
    2. LE (Low Energy) power control feature (LEPCF)
    3. 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:

    1. 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.
    2. 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!!!

    ESP32 MQTT

    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?
    Where To Buy?
    No.ComponentsDistributorLink To Buy
    1ESP32AmazonBuy Now

    What is MQTT?

    • 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:
      1. MQTT Topic
      2. MQTT Publisher
      3. MQTT Broker
      4. 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:

    1. 2-byte header (fixed)
    2. A 256 MB message payload
    3. 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:

    1. just once - this level is not reliable but is the fastest one
    2. 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 SSID const char* password = "ESP32@123"; // add your password
    • Add the details about MQTT broker
    const char* mqttServer = "m11.cloudmqtt.com"; const int mqttPort = 1883; //12948; const char* mqttUser = "public"; const char* mqttPassword = "ESP32@123";

    Arduino setup() Function

    • Initialize the serial monitor.
    • 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.

    ESP32 BLE (Bluetooth Low Energy)

    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.

    Where To Buy?
    No.ComponentsDistributorLink To Buy
    1ESP32AmazonBuy Now

    What is BLE?

    • 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

    1. Here we can check if the device is connected to the client or not
    2. 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:

    1. Go to the play store
    2. Search for the BLE scanner and download the app
    3. After installing the app turn on the Bluetooth.
    4. 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.

    Create a Web Server with ESP32

    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:

    • Wi-fi: 802.11b/g/n/e/i
    • Bluetooth : BLE(Bluetooth low energy) and V4.2
    Where To Buy?
    No.ComponentsDistributorLink To Buy
    1ESP32AmazonBuy Now

    What is a Web server?

    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

            if (request.indexOf("GET /message") != -1) {

              int startPos = request.indexOf("message=") + 8;

              int endPos = request.indexOf("HTTP/1.1") - 1;

              String message = request.substring(startPos, endPos);

              Serial.println("Received message: " + message);

              // Send a proper HTTP response

              client.println("HTTP/1.1 200 OK");

              client.println("Content-type: text/plain");

              client.println("Connection: close");

              client.println();

              client.print("Message received!");

              // Close the connection

              client.stop();

              Serial.println("Client disconnected.");

              break;

            }

          }

        }

      }

    }

    Procedure

    • Connect the ESP32 to the system using the cable.
    • Open the Arduino IDE.
    • Create a new project and remove the current code.
    • 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:
    • You can change the message through the URL.

    http://192.168.43.251/message?message=I_am_using_The_Engineering_Projects

    • This will create the following output:

    How ESP32 WebServer works with hardware?

    • 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.

    Note:

    ESP32 server Modes:

    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.

    1. 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.
    2. 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:
    1. String header: variable to store the header of the HTTP request.
    2. 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.
    3. 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.
    4. 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 ON state 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. :)

    ESP32 Programming Series: Install ESP32 in Arduino IDE

    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.

    Here's a video lecture for better understanding:

    Where To Buy?
    No.ComponentsDistributorLink To Buy
    1ESP32AmazonBuy Now

    ESP32 IDEs

    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:

    1. Installing Arduino IDE
    2. Adding ESP32 JSON File
    3. Installing ESP32 Boards
    4. Installing COM Port Driver for ESP32(if COM Port not detected automatically)

    Installing Arduino IDE

    We need to first download & install the Arduino IDE.

    After installing the Arduino IDE, we need to add the ESP32 JSON File in it. So, follow the below steps:

    Adding ESP32 JSON File in Arduino IDE

    Steps to install ESP32 JSON File in Arduino IDE:

    • 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:

    CP210x_Windows_Drivers

    • 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.

    WiFi Temperature Monitor with ESP8266 and DS18B20

    Hello friends, I hope you all are doing great. Today, we will create a wifi temperature monitoring system. For reading, we will use the DS18B20 sensor. For data processing and webpage creation, we will use our already known ESP8266.

    The project will be built as follows:

    1. Circuit assembly
    2. Code for reading the DS18B20 sensor (we will use Serial for tests).
    3. Creation of the webpage (we will use SPIFFS to store in FLASH).

    But first, let's know a little about the sensor and the communication model it uses.

    Where To Buy?
    No.ComponentsDistributorLink To Buy
    1ESP8266AmazonBuy Now

    Materials

    For this project, we will need the following items: For this project, we will need the following items:

    • 1 x ESP8266
    • 1x DS18B20 Sensor
    • 1x Breadboard
    • 1x 4k7 Ohms resistor

    DS18B20

    • DS18B20 is a digital temperature sensor with good precision, good customization, practical use, reliable and low cost. Good combination?
    • The sensor monitors temperatures in the range: -55°C to +125°C (-67°F to + 257°F), with an accuracy of +-0.5°C in the range -10°C to +85°C (outside that range, this inaccuracy increases, but nothing absurd).
    It uses three pins for operation:
    • VDD (Power Supply)
    • GND (Ground)
    • DQ (Digital Communication)

    VDD operates with values from 3V to 5.5V and can even be omitted. The sensor has a Parasite Mode, using only the DQ and GND pins, and its power comes from the communication pin. This mode works well but is more susceptible to noise.

    Data communication takes place over the 1-Wire (OneWire) protocol, using the DQ pin. We'll discuss the protocol later, but now it's important to know that, despite having only one wire, it allows two-way communication.

    The reading is performed actively, the microcontroller sends a command and receives back a packet with the information.

    In addition to the reading request, the sensor can also receive alarm configuration and data format commands. The DallasTemperature library already handles most of this for us. Including offering us some additional features, such as receiving reading in Faraday.

    The most common models on the market are found in the TO-92 package (looks like a transistor) and the waterproof package. This second is more common due to its practical application, 1m long cable with stainless steel tip. It can be used to control water temperature, for example. The reading is performed actively, the microcontroller sends a command and receives back a packet with the information.

    In addition to the reading request, the sensor can also receive alarm configuration and data format commands. The DallasTemperature library already handles most of this for us. Including offering us some additional features, such as receiving reading in Faraday.

    The most common models on the market are the TO-92 package (looks like a transistor) and the waterproof package. This second is more common due to its practical application, 1m long cable with stainless steel tip. It can be used to control water temperature, for example.

    OneWire

    OneWire (or 1-Wire) is a communication method designed by Dallas Semiconductor that transmits data using just one line, with a system of signaling who sends and when.

    The method is very similar to i2C, but it has a much more limited data transfer speed. Another difference is that in the 1-wire case, it is possible to omit the power pin, using the data pin in parasite mode (by now, you may have noticed that despite the name, the method needs at least two wires: Data and GND).

    Communication is done in master-slave mode, in which the microcontroller sends all requests, and the other devices only send data when nominally requested.

    Each device has a unique address/name. This allows us to connect multiple devices on the same data line. The requests are sent in broadcast, the device that recognizes itself in it responds.

    Circuit

    The circuit for our application is simple. We will connect the VDD pin of the sensor to the 3V3 of the NodeMCU, GND with GND, and we will use the D4 pin for the sensor data. It could be any other digital pin.

    Additionally, a 4k7 ohm resistor must be placed between the data pin and the 3V3 to increase stability.

    Finding the DS18B20 address

    As we saw earlier, each sensor has a unique address and, this address is essential for communication. We can understand this as a manufacturing serial number. But how to identify this number? We will create a helper code to find this address. In this case, the code scans any devices connected to pin D4. We will use the Serial Monitor to visualize the result.

    We started with importing the OneWire and DallasTemperature libraries (do not forget to maintain order). If any import error occurs, you can add them to Arduino IDE's library manager.

    Next, we start a OneWire object on pin D4 and create a sensor using that object. From that moment on, the “sensors” object has all the properties and functions offered by the DallasTemperature library.

    And we will make use of two functions Search(), which performs a search for devices in OneWire, and reset_search() which restarts this search.

    What our code does is start a search, save the result in the addr variable and, if the variable is not empty, write it in the serial.

    We found the result on the Serial Monitor. If there are other devices, they will appear here too. Keep the address, we'll need it.

     

    Sensor reading by Serial Monitor

    Now that we know the sensor's address. Let's start our main code for reading the temperature. The objective here is to start the sensor and take a reading every 10s.

    We started in the same way, but this time we created the sensor1 variable with the collected address.

    In the readDs18b20() function we will use two functions:

    • requestTemperatures() - This function does not specifically communicate with any sensors, but with all. It's like it says: If you're a ds18b20, run a new read now and wait for my ” And what the sensor does.
    • getTempC(address) - Here we send information directed to each sensor of interest, which responds to us with the last reading

    Inside the Setup() function we started the sensor with the begin() function, it performs a reading automatically, if you didn't make new requests, the sensor would still respond to the getTemp() function, but with an outdated value.

    In the loop, we have a timer with the millis() function so that the reading takes place every 10s.

    On the serial monitor, we should get the following result:

    Note that on line 15, we added one more parameter to the Serial.println() function. With that, we define the number of decimal places.

    Creating the monitoring page

    With our reading ready, let's create a web page to view this information in the browser. Remember that later we will put these files in FLASH ESP8266 with SPIFFS.

    We will build the following screen:

        And for this, we will use two files:
    • index.html
    • style.css

    The page structure is not the focus of this article, but basically, we have the index.html file creating the page itself and triggering a javascript function to update the reading.

    The style.css file improves the appearance of the page but does not interfere with its functioning.

    Both files must be in the data folder within the project folder and be transferred using the ESP8266 Sketch Data Upload.

    Complete Code

    With the page saved to FLASH, we need to create the structure to serve the page.

    • Connect on wifi
    • Create a web server
    • Create call-backs for requests to this

    This step is nothing new for us, but it is worth noting a few points.

    Now the readDs18b20() function also updates a variable of type String. We do this because server call-back functions do not accept integer or float variables.

    For the server, we have three routes:

    • “/” will send the html file with the latest sensor reading.
    • “/styled.css” will send the css file
    • “/state” will return the temperature variable to be updated.
    • And now in Serial Monitor, we have the IP to access at http://yourIP.

    Conclusion

    The DS18B20 is an extremely efficient and easy-to-use sensor. The application we developed today could be used to monitor the ambient temperature, or perhaps the temperature of a water reservoir. And the ESP8266 extends the range of that monitoring as far as we want.

    ESP8266 – Serial Communication

    Today we will talk about an extremely powerful tool in the use of microcontrollers. The Serial communication, specifically the USART (Universal Synchronous Asynchronous Receiver Transmitter) standard. The system works using two wires. RX (Receiver) and TX (Transmitter), connecting two devices. The RX of one is connected to the TX of the other. If the choice is for a synchronous connection, it may be necessary to add one or two more pins to operate as a “traffic light”. But most current microcontrollers can operate asynchronously, which saves us the expense of pins. Data is sent, as the name implies, in a series of bits. ESP8266 provides us with two ports, one of them converted to USB in the NodeMCU module.
    Where To Buy?
    No.ComponentsDistributorLink To Buy
    1ESP8266AmazonBuy Now

    Applications

    The range of uses of serial communication is limited only by creativity. Here I will mention three more general scenarios and detail some applications within them.

    1. Communicating with computers

    With a USB cable, we were able to connect the NodeMCU with a computer via Serial. Arduino IDE already gives us the first use. With Serial Monitor, we can send commands or debug the functioning of our code. But the integration with other software is pretty powerful. Imagine, for example, access control in which a circuit with ESP8266 reads an RFID card and sends it via Serial to a Permission Validation System. Or even an LED panel that receives a software display text.

    2. Communicating with microcontrollers

    Probably the most common application. Whether to integrate into a preexisting circuit or to distribute functionality between microcontrollers. This integration can be done between different microcontrollers. As long as they operate with the same voltage (3.3V) or use a level converter. An application example is to integrate the ESP8266 wifi with the analog ports of an ATMEGA328 to build an IoT toxic gas sensor. We already know that the ESP8266's analog port is quite inefficient. Then it is possible to perform the analog reading on the ATMEGA328 and send the information to ESP8266 by Serial.

    3. Communicating with industrial machines

    This, without a doubt, is the most interesting way to integrate industrial machinery with WEB systems. The older industrial equipment that allows some automation, provides RS232 or RS485 ports for integration with PLCs. In these cases, the commands are pretty plastered, but hopefully, well documented. The voltage level is 12V or 24V, but there are converters and logic levels to solve this. The industry 4.0 paradigm has been operating to make this kind of integration. Some PLCs are already developed with wifi modules. And on that account, circuits with the ESP8266 have the immense advantage of low cost. The vision behind this is to be able to remotely monitor or control an entire industrial plant. Tracking KPIs for predictive maintenance, doing recalibrations, and managing production.

    Main Functions

    The Serial library has a good variety of functions for Serial communication, but most are for very specific uses. We will discuss the most common ones and may return to others in the future as needed by the projects.

    Serial.begin()

    The first function to be used. It initializes Serial communication informing the data transfer speed (in bits per second) and, optionally, a configuration parameter. By default, Serial is configured to send data in 8-bit packets plus a terminator, not including parity. The best way to imagine this communication is to imagine a train, where each byte (8 bits) sent is a car, and the terminator is the connection between them. This standard is used in most devices, but if you need to integrate a device with another standard, the config parameter allows you to change the number of bits in the packet (from 5 to 8), the number of stop bits (1 or 2 ) and enable or disable parity (a packet integrity check). The speed uses some preset values. The fastest that remains stable for the ESP8266 is 115200 changes per second. So we could start with: Serial.begin(155200) The function below presents the same result, making the config parameter explicit. Serial.begin(115200, SERIAL_8N1)

    Serial.available()

    The function returns an integer with the number of bytes available in the read buffer. The maximum of bytes in the buffer is 64. This function is very useful for monitoring incoming information. Value = Serial.available()

    Serial.read()

    The function returns the most recent byte in the input buffer and removes it from the buffer. It is ideal if your communication is byte-to-byte. For example, if you are receiving input from a keyboard, the function would return the key you typed. It returns an integer with byte or -1 if no data is available.

    Serail.readString()

    This function is best suited for reading strings. Like words. It is the equivalent of calling the read() function continuously until it reads all the information from the buffer. The function returns a string with the data.

    Serial.print() and Serial.println()

    The two functions are very similar. It takes a value and sends it serially in ASCII format. It is also possible to define the numerical base before sending (binary, decimal...) and the number of decimal places. The function can be used either in the format: Serial.print(value) And the format: Serial.print(value, format) The table below presents some usage examples. The println function works pretty much the same, but it adds the return character ‘\r’ and newline ‘n’ at the end of the packet. It's the equivalent of typing in a text editor and pressing the "Enter" key.

    Serial Monitor

    The Arduino IDE provides a very powerful tool for debugging and testing Serial communication. The Serial Monitor. The tool is pretty intuitive, but let's take a look at its fields.
    • Sending data: This allows us to send commands directly to the microcontroller
    • Autoscroll: Very useful when we've already received enough information to fill the screen
    and don't want to move it down manually.
    • Terminator: Choose whether or not to include the new line and carry return characters at the end of the message before
    • BaudRate: Defines the communication It must be the same as the microcontroller, or
    packet loss or character misreading problems will occur.

    Controlling and monitoring an LED

    Let's make a simple code to control and monitor the NodeMCU LED from the Serial monitor. The code will monitor the Serial, and each time it receives the command “ON”, it will turn on the LED, when it receives “OFF”, it will turn off the LED when it receives “STATUS”, it will return the status of the LED in the Serial. We will create three functions to perform the actions.
    • turnOn() : To turn on the
    • turnOff() : To turn off the
    • statusLED() : To read the pin status and return information in the serial.
    We initialize the Serial in the Setup function. In the loop() function, we check if there is any data in the input buffer of the serial, if there is, it saves the buffer values in the variable “payload”. Finally, we check the payload value to decide the action. Here it is important to note that we use an equality comparison and that “ON” is different from “ON “. For this reason, when sending the information through the Serial Monitor, we choose the “No line ending” option. And so is our final code. Compiled, written to nodeMCU. Open the Serial Monitor, remember to put the correct baud rate and the "No Line ending" and send one of our 3 commands. This is simple code, but very powerful. So, that was all for today. I hope you have enjoyed today's tutorial. If you have any questions, please ask in the comments. Thanks for reading.

    ESP8266 – Knowing the NodeMCU GPIOs or Pinout

    Where To Buy?
    No.ComponentsDistributorLink To Buy
    1ESP8266AmazonBuy Now

    Introduction

    When the subject is ESP8266, it is normal that our attention is on the Wifi module. We've already discussed some applications in previous articles, and there's still a lot of cool stuff to see in the future. We've looked at how the ESP8266 communicates with the world via wifi, and now we'll look at how it does it through its pins.

    We will make a decision here. The ESP8266 is found in several modules. Each module with its pin provision. ESP-12 modules provide the most features. To make better use of these features and have a more protoboard-friendly module at hand, we will analyze the NodeMCU module with the ESP-12E.

    Overview and Electrical Data

    The NodeMCU pins are available in two rows with a spacing that allows them to fit on a breadboard (in particular, I find the pins a little thicker than they should be, and I think if they had more length and less width, it would be even more efficient).

    • The NodeMCU interferes just a little with ESP-12 pins. It does an untreated exposure of each of them.

    It is interesting to see what NodeMCU adds or changes to the ESP-12.

    Power Source

    ESP8266 operates on 3.3V, ESP-12 exposes the VDC pin for direct power. The NodeMCU incorporates a voltage regulator (usually the AMS1117) that can receive a 5V to 10V input and deliver a stable 3.3V supply to the ESP-12.

    But what advantage does this give us? nodeMCU is a development module. Choosing pins that fit the breadboard shows us this. Being able to receive 5V greatly increases the practicality of the power supply. 5V is the standard used on USB, so even a cell phone charger can keep everything running.

    The power can be supplied directly via the USB connector (standard USB = 5V) or the Vin pin (5V to 10V). The regulator provides a maximum of 500mA.

    The pins involved in the power are:

    • Vin: Positive voltage Operates with voltages from 5V to 10V.
    • GND (G): Reference voltage for voltage input and
    • 3V (3V): Output voltage with a value of 3.3V
    • VU: On some models, this pin is not connected to But Lolin's V3 model provides a 5V output provided directly by USB.

    Some important considerations to keep in mind:

    • The 3V3 regulator provides a maximum of So be careful what you feed the 3V3 pins.
    • The Module can be powered by either USB or Vin But it is not recommended that it occur for both at the same time.

    Serial – USB Adapter

    The ESP-12 provides us with two UARTs, with UART0 (pins RXD0 and TXD0) being used in programming. The NodeMCU Module integrates a Serial-USB converter that greatly facilitates our work.

    The USB connector can be used for power and data communication via Serial. For this reason, it is a sufficient condition for recording the ESP8266.

    A point of attention here: The RXD0 and TXD0 pins are available as GPIO pins (respectively GPIO3 and GPIO1). But they need to be used very carefully. Enabling these pins as GPIO disables USB.

    Digital Pins (GPIO)

    Digital pins or GPIO (General Purpose Input Output) are pins intended for binary control. It can have a HIGH or LOW state and can operate both, as an input (for reading digital states) and as a digital control (turning on LEDs, for example).

    If you take a look at the nodeMCU image, you will notice that it talks about 13 GPIOs (From GPIO0 to GPIO15). So we have 13 pins for input and output control? Not exactly.

    Most microcontroller pins have more than one function, this function is defined through registers. In the case of NodeMCU, some GPIOs are already in use. And if we configure it as a digital pin, we lose some functionality.

    Let's look at it on a case-by-case basis:

    • GPIO4 and GPIO5: Starting with the easiest. These two have only the GPIO function. It can operate as Input or Output.
    • GPIO0 and GPIO2: These pins play a very specific role in the ESP8266 startup. For that reason, they can only operate as
    • GPIO1 and GPIO3: As we have seen, these pins are used by USB so they are not recommended for use as GPIO in
    • GPIO9 and GPIO10: ESP8266 uses an external FLASH memory chip and communicates with it with a 4-bit SDIO interface. These two pins are on the list. By default, both are used in this But it is possible to set it to 2-bit mode and release these two pins. You gain in the number of pins, but you lose in memory access speed.
    • GPIO12, GPIO13, GPIO14, GPIO15: These pins can be used in other modes, but by default, they are free GPIOs for use as Input or

    Ah, an important point to mention: ESP's GPIOs operate at 3.3V.

    Analog Pinout

    The Esp8266 only provides one analog input (ADC0 pin), and that's probably its biggest weakness.

    Although the module operates with 3.3V, the analog input operates from 0 to 1V. Which significantly limits the resolution.

    Main functions for GPIO in the Arduino IDE

    To control the GPIOs, the Arduino IDE provides us with some functions. Among the main ones, times:

    pinMode(pin, mode)

    pinMode() defines the mode in which the pin will act. The possible modes are:

    • INPUT: The pin will be configured as a digital input
    • OUTPUT: The pin will be configured as digital output
    • INPUT_PULLUP: The pin will be configured as a digital input with a pull-up Here I leave a study recommendation for pull-up and pull-down circuits but simply put. It forces a value when nothing is connected to the pin. If it's a pull-up, it's HIGH, and if it's pull-down, it's LOW.

    As an example, if we want to use gpio4 as an output, we will have:

    pinMode(4, OUTPUT)

    digitalWrite(pin, value)

    The digitalWrite() function changes the value of the informed pin. Possible values are: HIGH or LOW.

    As an example, if we want to change the value of gpio4 to HIGH, we will have:

    digitalWrite(4, HIGH);

    One point we need to note is that there is an expected logical sequence to control the pin. First, we define it as OUTPUT and only then send a command to change the state. But what happens if we forget to use pinMode or set it to INPUT?

    For these cases, the digitalWrite() command automatically enables the INPUT_PULLUP mode. This procedure protects the microcontroller from short circuits.

    digitalRead(pin)

    The function reads the digital value of the selected pin, returning the HIGH or LOW value. As an example, to read the status of gpio4, we will have:

    value = digitalRead(4)

    Of course, the value variable needs to be declared before it can be used. And if the pin is not connected to anything, the value will vary randomly (unless pullup is enabled).

    analogRead(pin)

    This function reads the analog pin. Or almost. The function returns a value between 0 and 1023, with 0 being the equivalent of the GND voltage and 1023 being the value referring to the VCC.

    As an example, to read the status of adc0, we will have:

    value = digitalRead(A0)

    Constants

    There are some predefined constants to refer to the pins more practically. When using either function, you can use either the gpio number or the related constant.

    Differences in other modules

    Here we look at the pin arrangement of the nodeMCU Lolin V3 board. There are slight differences on other cards. In Lolin itself there are versions with the ESP-12E module and others with ESP-12F. In this case of Lolin, the most significant difference is a change of position between GPIOs 4 and 5.

    ESP8266 Operational WiFi Modes

    In previous articles, we connected the ESP8266 to a pre-existing WIFI network. It is the commonly used method in projects, especially when there is interest in internet access.

    For these cases, the ESP8266 operates as a “station” on the network. But we can find scenarios where there is no WIFI network to connect. Can we still use the ESP8266 in these cases? Yes, we can!

    Where To Buy?
    No.ComponentsDistributorLink To Buy
    1ESP8266AmazonBuy Now

    ESP8266 Operational Modes

    The ESP8266 WiFi module can operate in 2 different modes:

    • STA (the module operates as a station and is available to connect to an Access Point).
    • AP (the module creates a network with customizable SSID and Password. We will discuss how each mode works, its limitations, and how to use

    STA Mode

    We use the STA mode to connect the ESP8266 to a pre-existing Wi-Fi network. This connection is made from an Access Point, which will be responsible for managing information traffic.

    For configuration and use on the Arduino platform, we use the ESP8266WiFi.h library. Simple to use and extremely powerful, this library offers us all the tools to configure the WiFi module, without overloading us with flags and registers.

    For our configuration, there are two more relevant functions, begin() and config().

    begin() function

    The begin() function needs some parameters necessarily and others optionally. This is because this function is of type overload, which provides more flexibility when calling the function. For a better example, let's look at the begin() function in its full form and its minimal form:

    • Complete form: begin(ssid, password, channel, bssid, connect)
    • Minimum Form: begin(ssid, password)

    Same function, two ways to call it. And both works. This is because it was built with more than one declaration format in the library.

    Let's take a look at the parameters it accepts:

    • SSID: The name of the network we want to connect to. Required field, and can contain up to 32
    • password: password for the chosen Required field, must be between 8 and 64 characters.
    • channel: Defines the bandwidth to be This parameter is optional and can be useful in areas with many different networks. Choosing a good channel can minimize interference and increase network range. If omitted, it will be selected automatically.
    • bssid: One more optional parameter. If set to true, the function will return the MAC of the AP it was connected
    • Connect: A Boolean parameter which, if set to false, will save the parameters defined in the function, but will not connect to the

    This information will be saved in a reserved area of FLASH and in case of loss of connection, the attempt to reconnect will occur automatically.

    Another important point is that, by default, the station is configured as a DHCP (Dynamic Host Configuration Protocol) client. This means that when connecting, the ESP8266 will ask the Access Point for an IP address. If the AP has DHCP enabled, we will receive a random IP within the network range configured there.

    Config() function

    The config() function is not mandatory for a connection such as a station. But you will need it if you want to connect to the network with a fixed IP address. The function has the following format:

    • config(local_ip, gateway, subnet, dns1, dns2) Where the parameters represent:
    • local_ip: IP address we want to assign to the
    • gateway: Access Point IP address.
    • Subnet: IP mask of the network where we will
    • dns1 and dn2: optional fields for IP address of DNS servers (Domain Name Server).

    When we call the config() function, the DHCP mode is automatically disabled. Then the station will force the use of the address we choose. This method is useful when connecting over a network that does not have a DHCP server, or when having a fixed address is an essential project requirement.

    You need to be careful when choosing the IP address and the subnet, as if it's incompatible with the network configuration, we will connect, but we won't be able to interact with anything.

    In the image, we have a code for configuration and connection as a station.

    Access Point Mode (AP)

    In AP mode, the ESP8266 creates its WiFi network, allowing stations to connect to it. The figure below should help you better understand how it works. The ESP8266 configured as AP, replaces the role of the router in the network (with some limitations, but the principle is the same).

    Strictly speaking, the name of this mode is Soft Access Point, because the functionality as an AP does not use any hardware resources equivalent to that of a common AP. It's like a Virtual AP. This does not impact health, but it does severely impact performance.

    The main limitation is the number of connections it can manage. Although the manufacturer suggests up to 8 stations connected, you will have serious problems if you go beyond 5. If your application has a heavy data flow, I recommend that you limit it to 4 connections.

    Another limitation is that the created network is not connected to the internet. So keep in mind that this is a model for applications that work well on local networks and for a few devices.

    An example application for this format is an access control system. Approach with your cell phone, connect to the ESP8266 network, and be authorized to open a door.

    Setting up this mode is very similar to that of a station. We have an overload function for begin and another one for configuration.

    softAP() function

    It would be the equivalent of our station mode begin() function.

    • softAP(ssid): to create an open network, without a password.
    • softAP(ssid, password, channel, hidden, max_connection): to create a protected network.

    Let's take one for each parameter:

    • SSID: The name of our network, can contain a maximum of 63 This is the only mandatory field in the role and cannot be empty.
    • password: This field contains the password that the station needs to enter to connect. If not informed, the network will be open and can be accessed without any security. If you include one, it must contain a minimum of 8 characters, following the WPA2-PSK network security standard.
    • Channel: As we discussed for the station, this field defines the wifi operation It must receive a numeric value from 1 to 13. If not informed, it will receive 1 as the default value.
    • Hidden: If set to true, the SSID will be invisible and cannot be detected by identifiers (in your mobile's WiFi network list, for example. The network can still be connected if the station writes
    • Max_connection: Defines the maximum number of stations allowed. Receives values from 0 to 8, with 4 as the default.

    softAPConfig() Function

    This function sets some parameters referring to IP addresses. It has the format: WiFi.softAPConfig(local_ip, gateway, subnet)

    Where the parameters represent:

    • Local_ip: IP address of the access point
    • Gateway: IP address of the gateway (this is what stations will use as a switch)
    • Subnet: Defines the IP range to be

    With the code, you will configure a simple access point visible to your cell phone or computer.

    STA + AP Mode

    As the name suggests, the esp8266 will operate both as a station (being able to connect to a network) and as an Access Point (allowing stations to connect to it) at the same time.

    The purpose behind this method is to use esp8266 in mesh network configurations. The idea is interesting, but if the performance is not already excellent operating as AP, imagine as AP and STA.

    The documentation for this format is very scarce and, in a way, abandoned by the manufacturer itself. Espressif, when launching the successor of ESP8266, ESP32, included a specific library for MESH.

    Create Webserver with ESP8266 using SPIFFS

    Hello friends, I hope you all are doing great. In today's tutorial, we will have a look at How to Create Web Server with ESP8266 using SPIFFS.

    We've already seen how to create a web server and how to provide an HTML page on our ESP8266. We use the PROGMEM command to store an HTML code in FLASH memory. For a simple page, this works fine, but what if we have a more complex webpage? With a better style? What if we want to include images?

    Today we will learn how to use SPIFFS with ESP8266 to store files (regardless of type) in FLASH memory.

    Where To Buy?
    No.ComponentsDistributorLink To Buy
    1ESP8266AmazonBuy Now

    What is SPIFFS?

    • SPIFFS (SPI Flash File System) is a system designed for managing SPI flash memory in embedded devices. Its main goal is to use minimal RAM to access files. It's very useful when using pen drives, memory cards, and the ESP8266's flash memory.
    • SPIFFS allows you to access files (create, read, write, delete) just like on a computer. But with a much simpler folder structure.
    • To show how the tool works, we will create a web server with a styled page and an image. Then when accessing the webserver, the browser will receive the HTML file, the CSS file, and the images.

    Create Webserver with ESP8266 using SPIFFS

    • For that, we will need two things:
      • Library to manage SPIFFS.
      • Tool to load the files in FLASH.
    • The upload tool is a plugin called ESP8266fs that integrates python into the Arduino IDE.
    • Download the ESP8266FS-0,5.0.zip file from Github and unzip the files into Arduino's tools folder ( Possibly C:\program files x86\arduino \tools).
    • Restart Arduino IDE and the tool should appear available as shown in the image.
    • Now let's take a look at how it works.
    • Your sketch will always be saved inside a folder. The Arduino IDE cannot open an .INO file if it is not inside a folder with the same name.
    • Our upload tool will look inside that folder and look for another folder called “data”. Everything inside that folder will be transferred to the ESP8266's FLASH memory.

    Our page will have 3 main objects:

    • An image that will change depending on the status of the LED.
    • A text with the status of the LED.
    • A button to change the status of the LED.

    Files on Webserver

    And to build this page we will use 4 files:

    • html, which will contain the page itself.
    • css, containing the styling to make the page more beautiful.
    • Image of the lamp
    • Image of the lamp
    • The two images were chosen from the pixabay repository. You can use another one. But I recommend not using very large files as it takes a little longer to load. I also recommend using some service to resize the image, such as tinypng.
    • In our index.html file, we will have:
    • In our style.css file, we will have:

    Understanding ESP8266 Webserver Code

    • Created and saved, we used ESP8266 Sketch Data Upload to load the file into FLASH memory.
    • Before we look at the code, it's important to understand how the browser behaves when accessing a page.
    • When accessing the web server address, the browser sends an HTTP GET command in the path “/” and waits for an index file in response.
    • Inside index file it can be informed that it needs other files. What happens in our code.
    • In line 7 of the index.html file, it is informed that the style.css file will also be needed and that it is of type text/css.
    • Then the browser sends another HTTP GET command with the path “/style.css” and expects to receive a file with that name.
    • In line 13, the <img> tag informs the path to an image, and the browser sends another HTTP GET command to the address “/bulb-off.png”, this time the browser expects an image file.
    • The browser will send GET commands each time we click the Toggle button (“/toggle” path) and every 1 second to receive an updated status (“/state” path).
    • Doing yet another GET to the lit lamp image (path: “/bulb-on.png”).

    So we will need to handle it in our .INO code the GET requests in the paths:

    • “/”
    • “/style.css”
    • “/bulb-off.png”
    • “/bulb-on.png”
    • “/toggle”
    • “/state”

    Our style.css file sets sizes, alignments, and colors for components. We start our .INO file by importing four libraries:

    • h – That will take care of our WiFi connection.
    • h and ESPAsyncWebServer.h – Which will manage the webserver (including HTTP GET commands).
    • h – File System Library that will take care of our SPIFFS.

    We define the pin for our LED. We create variables with SSID and password of the wifi network where we will connect. We created our server on port 80 and a variable to monitor the LED status.

    • The wifiConnect() function will connect the ESP8266 to the chosen wifi network by printing the IP address on the serial monitor.
    • Pay attention to this number. You will need to access the webserver from the browser.
    • The processor() function is responsible for updating the variable with the status of the LED.
    • We will use it in handling our GETs.
    • The toggleLed() function toggles the LED state. We will use it in the GET “/toggle”.
    • And finally, our setup() function. We start by setting our LED to OUTPUT (otherwise, our toggle won't work.
    • Next, we start Serial with a baud rate of 115200 to view the IP address on the Serial Monitor.
    • With SPIFFS.begin(), we initialize our filesystem in flash memory.
    • If an error occurs, our code stops here and reports on Serial Monitor. In that case, upload the files again.
    • And finally, we've included our GETs.

    The “server.on” structure is an event manager provided by the ESPAsyncWebServer.h library. In short, we inform a route, a method (HTTP-GET, for our case), and action when receiving the request. But we need to take a closer look at some variations of the function.

    • The server receives a request for the “/” route with the HTTP GET method.
    • In request->send, we inform that the response is a SPIFFS file with the name index.html and that it will be sent in string format.
    • The last two fields (“false” and “processor”) inform that the index.html file is a template that depends on more information. This information will be provided by the processor() function.

    It is necessary to send the index file with the updated LED state value.

    For style files and images, we use a similar principle, but these files are not being changed before they are uploaded. So we only inform the origin, name, and type (if you want to know a little more about file types in HTTP, I recommend a study on MIME TYPES. Any type of file can be sent, but MIME standardizes what browsers can understand).

    Lastly, we have the “/state” returning the stateValue variable on each update and the “/toggle” which changes the state before sending the same variable. The response format has a small change. As we are sending only one variable, we inform the MIME TYPE “text/plain”, the response code 200 (default for success over HTTP), and the variable converted to a string.

    Results

    • With the code compiled and recorded, check the IP of the webserver in the Serial Monitor and access it in the browser.
    • Example: for IP: 10.10.10.11 access: http://10.10.10.11.
    • Attention: As we use port 80 on the web server, we use HTTP and not HTTPS. The result on the screen should look like the images below:

    So that was all for today. I hope you have enjoyed today's lecture because it will improve the presentation of your project. If you got any queries, ask in the comments. Thanks for reading!!!

    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>

    Share
    Published by
    Syed Zain Nasir