IoT Based Motion Detection with Email Alert using ESP32

The IoT is the interconnection of physical objects or devices with sensors and software accessing capabilities to communicate data or information over the internet.

To build an IoT network, we need an interface medium that can fetch, control, and communicate data between sender and receiver electronics devices or servers.

Espressif Systems created the ESP32 Wi-Fi chip series. The ESP32 module is equipped with a 32-bit Tensilica microcontroller, 2.4GHz Wi-Fi connectivity, an antenna, memory, and power management modules, and much more. All of these built-in features of this ESP32 module make it ideal for IoT applications.

Hello readers, I hope you all are doing great. In this tutorial, we will learn another application of ESP32 in the field of IoT (Internet of Things). We are using a PIR sensor to detect motion and an Email alert will be generated automatically whenever a motion is being detected.

Fig.1

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

Overview

The HCSR-501 sensor module is used with ESP32 to detect the motion. So whenever a motion is detected, the PIR sensor will generate a HIGH output signal which will act as an input to the ESP32 module. In the absence of motion, the output of the PIR sensor will remain LOW. If a HIGH input signal is generated from the PIR sensor module, the LED (either peripheral or inbuilt) will be turned ON and along with that, an Email will be generated to the receiver’s email address as per the program instructions.

Software and Hardware requirements

  • ESP32 development board
  • HCSR-501 PIR sensor module
  • LED
  • Resistor
  • Connecting Wires
  • Sender’s email account details
  • Receiver’s email address
  • ESP-Mail-Client Library

What is HCSR-502 PIR sensor module and how does it work?

Fig. 2 PIR Motion Sensor

PIR stands for Passive Infrared sensors. It detects heat energy in the surrounding environment using a pair of pyroelectric sensors. Both sensors are placed next to each other, and when motion is detected or the signal differential between the two sensors changes, the PIR motion sensor returns a LOW result (logic zero volts). It means that in the code, you must wait for the pin to go low. The desired function can be called when the pin goes low.

There are two potentiometers available in the HCSR-501 PIR motion sensor module. One of the potentiometers is to control the sensitivity to the IR radiations. Lower sensitivity indicates the presence of a moving leaf or a small mouse. The sensitivity can be changed depending on the installation location and project specifications.

The second potentiometer is to specify the duration for which the detection output should be active. It can be programmed to turn on for as few as a few seconds or as long as a few minutes.

PIR sensors are used in thermal sensing applications such as security and motion detection. They're commonly found in security alarms, motion detection alarms, and automatic lighting applications.

SMTP

The simple mail transfer protocol (SMTP) is an internet standard for sending and receiving electronic mail (or email), with an SMTP server receiving emails from email clients.

SMTP is also used to establish server-to-server communication.

Gmail, Hotmail, Yahoo, and other email providers all have their own SMTP addresses and port numbers.

Fig. 3 SMTP

How does SMTP work?

To send emails, the SMTP protocol, also known as the push protocol, is used, and IMAP, or Internet Message Access Protocol (or post office protocol or POP), is used to receive emails at the receiver end.

The SMTP protocol operates at the application layer of the TCP/IP protocol suite.

When the client wants to send emails, a TCP connection to the SMTP server is established, and emails are sent over the connection.

SMTP commands:

  • HELO – This command is sent only once per session and it is used to identify the qualified domain names and the client to the server.
  • MAIL – used to initiate a message
  • RCPT – Identifies the address
  • DATA – This command is responsible for sharing data line by line

SMTP server parameters for email service

There are various email service providers available like, Gmail, Yahoo, Hotmail, Outlook etc. and each service provider have unique service parameters.

In this tutorial, we are using the Gmail or Google Mail service.

Gmail is the email service provided by Google and Gmail SMTP server is free to access and anyone can access this service, who has a Gmail account.

  • SMTP server: smtp.gmail.com
  • SMTP port: 465
  • SMTP sender’s address: Gmail address
  • SMTP sender's password: Gmail Password

Create a new Gmail account (Sender)

It is recommended to create a new email account for sending emails using ESP32 or ESP8266 modules.

If you are using your main (personal) email account (for sending emails) with ESP and by mistake something goes wrong in the ESP code or programming part, your email service provider can ban or disable your main (personal) email account.

In this tutorial we are using a Gmail account.

Follow the link to create a new Gmail account : https://accounts.google.com

Fig. 4 create new gmail account

Access to Less Secure apps

To get access to this new Gmail account, you need to enable Allow less secure apps and this will make you able to send emails. The link is attached below:

https://myaccount.google.com/lesssecureapps?pli=1

Fig. 5 permission to less secure apps

Interfacing ESP32 and HCSR-501

Table 1

Fig. 6 ESP32 and HCSR-501 connections

Arduino IDE Programming

We are using Arduino IDE to compile and upload code into ESP32 module. To know more about ESP32 basics, Arduino IDE and how to use it, follow our previous tutorial i.e., on ESP32 programming series. Link is given below:

https://www.theengineeringprojects.com/2021/11/introduction-to-esp32-programming-series.html

Necessary Library

To enable the email service in ESP32 it is required to download the ESP-Mail-Client Library. This library makes the ESP32 able to send email over SMTP server.

Follow the steps to install the ESP-Mail-Client library:

  1. Go to the link and download the ESP-Mail-Client library:

https://github.com/mobizt/ESP-Mail-Client

  1. Open your Arduino IDE.
  2. Then to add the ZIP file go to Sketch >> Include Library >> Add.ZIP Library and select the downloaded ZIP file.

Fig. 7 Adding ESP-Mail-Client Library

  1. Click on

Arduino IDE Code

//To use send Email for Gmail to port 465 (SSL), less secure app option should be enabled. https://myaccount.google.com/lesssecureapps?pli=1

//----Add the header files

#include <WiFi.h>

#include <ESP_Mail_Client.h>

//-----define network credentials

#define WIFI_SSID "public"

#define WIFI_PASSWORD "ESP32@123"

//--add the Server address and port number with respect to a particular email service provider

#define SMTP_HOST "smtp.gmail.com"

#define SMTP_PORT esp_mail_smtp_port_587 //port 465 is not available for Outlook.com

 

//----The log in credentials

#define AUTHOR_EMAIL "techeesp697@gmail.com"

#define AUTHOR_PASSWORD "Tech@ESP123"

//----The SMTP Session object used for Email sending

SMTPSession smtp;

//---Declare the message class

SMTP_Message message;

//---Callback function to get the Email sending status

void smtpCallback(SMTP_Status status);

const char rootCACert[] PROGMEM = "-----BEGIN CERTIFICATE-----\n"

"-----END CERTIFICATE-----\n";

int inputPin = 4; // connect with pir sensor pin

int pir_output = 0; // variable to store the output of PIR output

void setup()

{

pinMode(inputPin, INPUT);

pinMode(LED_BUILTIN, OUTPUT);

Serial.begin(115200);

pir_output = digitalRead(inputPin);

Serial.println();

Serial.print("Connecting to AP");

WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

while (WiFi.status() != WL_CONNECTED)

{

Serial.print(".");

delay(200);

}

Serial.println("");

Serial.println("WiFi connected.");

Serial.println("IP address: ");

Serial.println(WiFi.localIP());

Serial.println();

/** Enable the debug via Serial port

* none debug or 0

* basic debug or 1

*

* Debug port can be changed via ESP_MAIL_DEFAULT_DEBUG_PORT in ESP_Mail_FS.h

*/

smtp.debug(1);

/* Set the callback function to get the sending results */

smtp.callback(smtpCallback);

/* Declare the session config data */

ESP_Mail_Session session;

/* Set the session config */

session.server.host_name = SMTP_HOST;

session.server.port = SMTP_PORT;

session.login.email = AUTHOR_EMAIL;

session.login.password = AUTHOR_PASSWORD;

session.login.user_domain = "mydomain.net";

/* Set the NTP config time */

session.time.ntp_server = "pool.ntp.org,time.nist.gov";

session.time.gmt_offset = 3;

session.time.day_light_offset = 0;

/* Set the message headers */

message.sender.name = "ESP Mail";

message.sender.email = AUTHOR_EMAIL;

message.subject = "Email Alert on Motion detection";

message.addRecipient("Anonymous",

"replace this with receiver email adderss");

String textMsg = "Motion Detected!!!!!";

message.text.content = textMsg;

message.text.charSet = "us-ascii";

message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;

message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;

/* Set the custom message header */

message.addHeader("Message-ID: <abcde.fghij@gmail.com>");

/* Connect to server with the session config */

if (!smtp.connect(&session))

return;

}

void loop()

{

if (pir_output == HIGH)

{

//----Start sending Email and close the session

if (!MailClient.sendMail(&smtp, &message))

Serial.println("Error sending Email, " + smtp.errorReason());

digitalWrite(LED_BUILTIN, HIGH);

Serial.println("Motion detected!");

Serial.println("Email sent");

}

else {

digitalWrite(LED_BUILTIN, LOW);

Serial.println("No Motion detected!");

}

delay(1000);

ESP_MAIL_PRINTF("Free Heap: %d\n", MailClient.getFreeHeap());

//to clear sending result log

smtp.sendingResult.clear();

}

/* Callback function to get the Email sending status */

void smtpCallback(SMTP_Status status)

{

/* Print the current status */

Serial.println(status.info());

/* Print the sending result */

if (status.success())

{

Serial.println("----------------");

ESP_MAIL_PRINTF("Message sent success: %d\n", status.completedCount());

ESP_MAIL_PRINTF("Message sent failled: %d\n", status.failedCount());

Serial.println("----------------\n");

struct tm dt;

for (size_t i = 0; i < smtp.sendingResult.size(); i++)

{

/* Get the result item */

SMTP_Result result = smtp.sendingResult.getItem(i);

time_t ts = (time_t)result.timestamp;

localtime_r(&ts, &dt);

ESP_MAIL_PRINTF("Message No: %d\n", i + 1);

ESP_MAIL_PRINTF("Status: %s\n", result.completed ? "success" : "failed");

ESP_MAIL_PRINTF("Date/Time: %d/%d/%d %d:%d:%d\n", dt.tm_year + 1900, dt.tm_mon + 1, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec);

ESP_MAIL_PRINTF("Recipient: %s\n", result.recipients);

ESP_MAIL_PRINTF("Subject: %s\n", result.subject);

}

Serial.println("----------------\n");

//You need to clear sending result as the memory usage will grow up as it keeps the status, timstamp and

//pointer to const char of recipients and subject that user assigned to the SMTP_Message object.

//Because of pointer to const char that stores instead of dynamic string, the subject and recipients value can be

//a garbage string (pointer points to undefind location) as SMTP_Message was declared as local variable or the value changed.

smtp.sendingResult.clear();

}

}

Note: The exact code cannot be used. As a result, before uploading the code, you must make some changes such as replacing the SSID and password with your network credentials, email address of sender and receiver, SMTP setting parameters for respective email service providers, and so on. We'll go over these details as well during the code description.

Code Description

  • The first step is adding the required header files or libraries.
  • Here we are using two libraries:
    • The first one is h, which is used to enable the Wi-Fi module and hence wireless network connectivity.
    • Another library file required is the h to enable email service over SMTP (simple mail transfer protocol).

Fig. 8

  • Enter the network credentials in place of SSID and PASSWORD.

Fig. 9

  • Enter the SMTP parameter of the respective email service provider like, Gmail, Yahoo, Outlook, Hotmail etc. (In this tutorial we are using Gmail service).
  • Parameters used below are for Gmail.

Fig. 10

  • Enter the sender’s email login details (email address and password ).

Fig. 11

  • Insert recipient’s email address.

Fig. 12

  • SMTPSession object is used for sending emails.

Fig. 13

  • Next step is declaring a message

Fig. 14

  • This smtpCallback() function is used to get the email sending status.

Fig. 15

  • This function also includes printing the results like success and failure of email sent.

Fig. 16

  • Next we are defining a variable to store the GPIO pin number to which the PIR sensor is to be connected.
  • Next variable pir_output is used to store the current state of PIR output and initially it is fixed to zero.

Fig. 17 Variable for PIR sensor

Setup()

  • Initialize the serial monitor at 115200 baud rate for debugging purpose.
  • Set the mode as INPUT for the GPIO pin to which PIR module is to be connected i.e., GPIO 4.
  • We are using the built-in LED (LED turns ON when a motion is detected.
  • The digitalRead() function is used to read the output of PIR sensor module, by passing the GPIO pin (to which PIR sensor is connected) as an argument and results will be stored inside pir_output

Fig. 18

  • begin() function is used to initialize the Wi-Fi module with Wi-Fi credentials used as arguments.
  • The While loop will continuously run until the ESP32 is connected to Wi-Fi network.

Fig. 19

  • If the device is connected to local Wi-Fi network then print the details on serial monitor.
  • localIP() function is used to fetch the IP address.
  • Print the IP address on serial monitor using println() function.

Fig. 20

  • debug() is used to enable the debug via Serial port where ‘0’ and ‘1’ are used as arguments where;
    • 0 - none debug
    • 1 - basic debug
  • Inside ESP_Mail_FS.h header file, ESP_MAIL_DEFAULT_DEBUG_PORT can be used to change the Debug port.
  • Set the callback() function to get sending results.

Fig. 21

  • Setting session configuration includes, assigning the server address, port number of the server (here we are using Gmail services), email login details of the sender etc.

Fig. 22

  • Next step is setting the message header.
  • Message header will be set inside the setup() function which includes, sender’s name, subject, sender’s email address, receiver’s email address and name.
  • A string type variable textMsg is defined to to store the message to be transferred over email.

Fig. 23

  • connect() function.is used to connect to server with session configuration.

Fig. 24

Loop

  • ESP32 is continuously checking for the input from PIR sensor inside the loop function.
  • If the input received from pir sensor is HIGH the ESP32 will generate an email to the client for that sendMail() function is used and if mail transmission is failed then that will be printed on the serial monitor along with the reason.
  • The inbuilt LED on ESP32 will be turned ON and the respective results will be printed on the serial monitor.

Fig. 25 ‘If motion detected’

  • If the input received from the PIR sensor is LOW then the LED will remain LOW/OFF and no email alert will be generated.

Fig. 25 No motion detected

  • Finally, clear the email log to avoid excessive memory usage.

Fig. 26 Clear the email log

Testing

  • Open the Arduino IDE.
  • Paste the above code into your Arduino IDE.
  • Make the required changes in the code like, network credentials, email service parameters of the respective email service provider, sender and receiver email address and define the message you want to share over SMTP server.
  • Select the right development board and COM port for serial communication.

Fig. 27 select development board and COM port

  • Compile and upload the program into the ESP32 development board.
  • Connect the HCSR-501 module with the ESP32 as per the circuit/connect details given above.

Fig. 28 ESP32’s Inbuilt LED is turned ON when a motion is detected

  • Open the serial monitor with 115200 baud rate.

Fig. 29 Serial monitor

  • Check the receiver email account.

Fig.30 received email on motion detection

This concludes the tutorial. We hope you found this of some help and also hope to see you soon with a new tutorial on ESP32.

ESP32 with 16x2 LCD in Arduino IDE | Data Mode & I2C Mode

Hello readers, we hope you all are doing great. Welcome to the 1st lecture of Section 4 in the ESP32 Programming Series. In this section, we will interface the ESP32 module with common Embedded modules(i.e. LCD, Keypad, RTC etc.).

In today's tutorial, we will interface ESP32 with a 16x2 LCD and will display data using both Data Mode and I2C Mode. LCD is the most commonly used embedded module in IoT Projects. It is used to display different types of data i.e. sensor readings, warning messages, notifications etc.

Before going forward, let's first have a look at what is LCD and How it works:

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

16x2 LCD Module

LCD(Liquid Crystal Display) is a type of electronic display module that is used in a wide variety of applications and devices such as calculators, computers, mobile phones, TVs, etc. There are different types of LCDs available for commercial use. Today, we are going to use the most simple one i.e. 16x2 LCD, shown in the below figure:

This 16x2 LCD has 16 columns and 2 rows, so in total of 32 blocks to display characters. Each Block can display a single character at a time. We can display text in different styles on this LCD i.e. blinking, scrolling etc. Another variant of this LCD is 20x4 LCD and as the name suggests, it has 20 columns and 4 rows and so can display 80 characters at a time. The operating principle of both of these LCDs is quite similar. So, if you are working with a 20x4 LCD, you can still follow this tutorial.

Let's have a look at the LCD pinout:

LCD Pinout

Both 16x2 and 20x4 LCDs have 16 pins each, used to control 7 write on these LCDs. Among these 16 pins, we have:

  • 8 Data Pins(Pin7-14)
  • 2 LCD Power Pins(Pin1 and 2)
  • 2 Backlight LED Power Pins(Pin15 and 16)
  • 1 Contrast Pin(Pin3)
  • 1 Enable Pin(Pin6)
  • 2 Selection Pins(Pin4 and 5)

LCD Pinout and its working is shown in the below table:

LCD Pinout
Pin No. Name Working
1
GND(Ground)
Connected to Ground Terminal.
2
Vcc(+5V)
Connected to +5V.
3
VE
To Control the LCD Contrast.
4
RS(Register Select) If RS=0(GND), LCD operates in Data Mode and we can write characters on the LCD.
If RS=1(+5V), LCD Command Mode gets activated and we can send commands to LCD i.e. erase, new line etc..
5
R/W(Read & Write) R/W=0(GND) enables the write operation on the LCD. (So, we normally keep this pin LOW, as we are interested in printing on the LCD).
R/W=1(+5V) enables the read operation on the LCD.
6
EN(Enable)
Enables the LCD to operate, so it should be kept HIGH.
7
Data Pin 0
LCD has a total of 8 Data Pins(D0-D7)
8
Data Pin 1
9
Data Pin 2
10
Data Pin 3
11
Data Pin 4
12
Data Pin 5
13
Data Pin 6
14
Data Pin 7
15
LED+
Connected to +5V. Turn on the backlight LED.
16
LED-
Connected to GND.

Now, let's interface the LCD with ESP32:

Interfacing LCD with ESP32

There are two methods to interface ESP32 with a 16x2 LCD:

  • Data Mode
  • I2C Mode

In the Data Mode, we use the LCD Data Pins and send data serially, while in the I2C mode, we solder an I2C adapter with the LCD, which acts as a bridge and maps I2C data coming from the microcontroller to the Data Pins. Let's first interface ESP32 and LCD via Data Pins:

LCD with ESP32 in Data Mode

As we discussed earlier, LCD has 8 Data Pins used to communicate with the Microcontroller. There are two ways to send data from the Microcontroller to the LCD:

  1. 4-Pin Method: In this method, we use 4 Data Pin of LCD(D0-D3) to get data from the microcontroller.
  2. 8-Pin Method: In this method, we use all the 8 Data Pins of LCD(D0-D7) to communicate with the microcontroller.

In complex projects, where you are dealing with multiple sensors & modules, its quite difficult to spare 8 Pins for LCD interfacing. So, normally 4-Pin method is preferred, which we are going to design next:

    Components Required

    Here are the components required to interface LCD with ESP32:

    1. ESP32 Development Board
    2. 16x2 LCD
    3. Potentiometer(To set the LCD Contrast)
    4. Jumper wires
    5. Breadboard

    Now, let's design the ESP32 LCD Circuit Diagram:

    Circuit Diagram

    • The circuit diagram of LCD interfacing with ESP32 via data pins is shown in the below figure:

    [Image]

    As you can see in the above figure:

    • Pin1 of the LCD is connected to the GND of ESP32.
    • Pin2 of the LCD is connected to the VIN of ESP32.
    • Pin3 of the LCD is connected to the Output Pin of the potentiometer,  the other two Pins of the Potentiometer are connected to Vcc and GND. So, we can change the voltage at this Pin3 from 0-5V by rotating the potentiometer's knob. You have to manually set its value to make the LCD text visible.

    Here's our hardware setup for ESP32 LCD Interfacing:

    [Image]

    Now let's design the Programming Code to print a simple message on the LCD:

    ESP32 Code for LCD

    We are using Arduino IDE to compile and upload code in the ESP32 module. If you haven't installed it yet, please read How to Install ESP32 in Arduino IDE. Here's the code to print a message on the LCD:

    #include 
    LiquidCrystal lcd(22,23,5,18,19,21);
    
    void setup()
    {
        lcd.begin(16, 2);
        lcd.clear();
    
        // go to row 0 column 5, note that this is indexed at 0
        lcd.setCursor(5,0);
        lcd.print("ESP32");
    
        // go to row 1 column 0, note that this is indexed at 0
        lcd.setCursor(0,1);
        lcd.print (" TheEnggProjects");
    }
    
    void loop()
    {
    }

    Code Description

    • The first step is to include the required library files. LiquidCrystal is the official Arduino Library to control the LCD.
    #include 
    • Next, we are initializing an "lcd" object of type "LiquidCrystal",  it takes the data and control pins as arguments.

    LiquidCrystal lcd(22,23,5,18,19,21);
    

    Setup() Function

    In the Setup() Function:

    • First of all, we initialized the 16x2 LCD using the begin() function. It takes the no of columns & rows of the LCD as an argument.

    lcd.begin(16, 2);
    

    So, if you are using a 20x4 LCD, you should change its arguments to 20 and 4, as shown below:

    lcd.begin(20, 4);
    • Next, we cleared the LCD screen, so if there's any garbage data printed on the LCD, it will be removed:

    lcd.clear();
    • setCursor command is used to set the LCD cursor at the specified position. Its first argument is "column position" and the second argument is "row position". In our case, we have set the Cursor at 6th Column and 1st Row. So, now when we print our message, it will be printed from this position.

    lcd.setCursor(5,0);
    • Finally, we printed our first message on the LCD using the print() command. The message string to be printed on the LCD is provided as an argument.

    lcd.print("ESP32");
    • At the end, we set the cursor.at 1st column & 2nd row, and printed the text:

    lcd.setCursor(0,1);
    lcd.print (" TheEnggProjects");
    

    As you can see, the LCD code is quite simple and I hope now you can easily print on the LCD. So, let's check the results:

    Results

    • Select the right development board from Tools >> Boards >> DOIT ESP32 DevKit V1 in Arduino IDE.
    • Compile and upload the code into ESP32 using Arduino IDE.
    • IF everything goes fine, your text messages will get printed on the LCD at the specified locations, as shown in the below figure:

    Common Errors faced while working on 16*2 LCD:

    • Texts are not visible: Backlight is ON but the texts are not visible (after uploading the code) as shown in the image below. To resolve this issue:
      • Check the potentiometer, whether it is connected properly or not.
      • Adjust the value of potentiometer to control brightness of the display.

    Fig. 6

    Only a single row with dark blocks is visible.

    Sol. : Check the EN pin.

    Fig. 7

    This concludes the tutorial. We hope you found this of some help and also hope to see you soon with a new tutorial on ESP32.

    Up Down Counter using Arduino & 7-Segment Display

    Hello geeks, welcome to our new project. In this project, we are going to make a very interesting project which is an Up-Down counter. Most of us who have an electronics background or studied digital electronics must know the counter. Counter is a simple device which counts numbers. As per the digital electronics, there are two types of counter, the Up counter which counts in increasing order and another is Down counter which counts in decreasing order. And every counter has a reset limit, on which the counter resets to its initial value and starts the counting again. The limit of every counter depends on the bits of counter. For example, we have a 8 bit Up counter which means it will count upto 255 and afterwards it will reset and will start again counting from zero.

    Where To Buy?
    No.ComponentsDistributorLink To Buy
    17-Segment DisplayAmazonBuy Now
    2Arduino UnoAmazonBuy Now

    Software to install

    In this project, we will need two softwares first is the Arduino IDE which is used for Arduino programming. As we are going to make this project in simulation, we will use Proteus simulation software. Proteus is a simulation software for electronics projects. In this software, we can run the real time simulation of electronics circuits and debug them without damaging any real components.

    And it is a good practice to make any circuit in the simulation first if we do that for the first time.

    And Proteus has a very large database for electronics components but it lacks some new component libraries, for that we have to install some libraries for those components. In this, we have to install a library for the Arduino UNO module.

    We should first download the Arduino UNO library.

    Components required

    We will need the following components for this project

    • Arduino UNO
    • 7 Segment LED display
    • Two push buttons
    • 2 Resistors

    Components details

    Arduino UNO

    • Arduino UNO is an open source development board developed by Arduino.
    • It uses the ATmega328 microcontroller made by ATMEL.
    • ATmega328 has an 8 bit RISC based processor core with 32Kb flash memory.
    • Arduino UNO has 14 digital input/output pins and 6 analog input/output pins.
    • It has 1 UART, 1 SPI and 1 I2C communication peripheral on board.
    • It has a 10 bit ADC which can give value from 0 to 1023.
    • Operating voltage of ATmega IC is 5 volts but on the Arduino board, using the DC power jack, we can connect upto 9-12 voltage power supply.
    • We can power Arduino UNO using the DC power jack or Vin on the Arduino UNO module.
    • Here, we used the Arduino UNO as the main controller which works as a counter here and displays the same on the 7 segment LED display.

    7 Segment LED display

    • It is an LED display module, in which there are seven LEDs arranged in the rectangular form on which we can display single digit numbers from 0-9 and some alphabets as well.
    • It has two types, one is common ground and another is common Vcc.
    • There are 7 different pins for each LEDs and one common pin, this pin can be common ground or common Vcc depending upon type of the display.
    • The pins on the display are noted as a,b,c,d,e,f,g.
    • Common ground is also known as Common cathode, and common Vcc is also known as Common anode .
    • In Common cathode type display, the LEDs will glow when LEDs pins are connected to logic HIGH.
    • In Common anode type display, the LEDs will glow when the LEDs pins are connected to logic LOW.
    • As they are simple LEDs so while using them in the circuit, it is mandatory to use some protection resistors with each of them if we are using Common ground type display and single resistor with the Common Vcc pin if we are using the Common Vcc type display.
    • For the counter, we will follow the truth table of display for showing the numbers.

    Push buttons

    • In this we have used a simple momentary push button for setting the counter in UP counting or in DOWN counting.
    • There are two pins in the push button.
    • As we will use the push buttons in active low condition which means one side will be connected to ground and other terminal will be connected to the Arduino.
    • So when we press the push button, it will close the circuit and set the pin.
    • While using any push button, it is mandatory to use a pull-up or pull-down resistor with it, otherwise there will be some glitches in the operation.
    • Because when the button is released, the circuit will be open and if there is no pull-up or pull-down connected to the other pin of the push button, then that pin will be in floating state and will give any random voltage, which will create an issue.
    • Here, in this project we have used the pull-up resistor so that when the push button is released, the pin state will be in logic HIGH state.

    Project overview

    As we know counters are simple electronic circuits which count some values and after reaching the maximum value they will reset. In this project, we will make an Up-Down counter which means our counter will count from 0-9 and again after 9-0.

    We will use the 7 segment display for showing the counter values. In this project, we have used the common ground type of LED display. And two push buttons to start the counter in up counting or in down counting. When we press the UP push button, then the Arduino will activate the pins as per the up counting and LED will display numbers from 0-9 and when we press the DOWN push button then the Arduino will activate the pin as per the down counting and LED will display numbers from 9-0.

    To control the LEDs, Arduino will set the pins as HIGH and LOW as per the truth table for the common ground display.

    Arduino will set the pins and LED will display the numbers.

    Circuit diagram and working

    Now we know the working of our counter so let’s make the circuit for the same:

    • Open the new project in the Proteus and import all the required components in the workspace.
    • Now let’s connect the push buttons with Arduino, for the push button we will use Arduino UNO’s digital pins D11 and D12.
    • Connect the one side of the push buttons with the Vcc and another side with the Arduino UNO and on that side we will connect the pull-down resistors.
    • Connect the pull down resistors with the Ground.
    • Now, connect the pins of the 7 segment display with the Arduino UNO.
    • Connect the pins of the LED display in the same order as A-2, B-3, C-4, D-6, E-7, F-8, G-9 and DP -5. Otherwise it will show the wrong data on the display.

    Arduino Code for Up-Down counter

    Now we will start writing the code of the Up-Down counter. The code of this project will be divided into three major parts. In the first part, we will declare all the required variables and pins. In the second part, we will set the modes of pins and set the initial states to pins and do the required configuration if needed and the last part we will write our main functionality of our project which we want to run continually.

    • So let’s declare all the required variables. First of all, declare the variables for pins of the seven segment display and Up counter push button and down counter push button.
    • Now declare all the required variables which we will use in this code.
    • Now we declared all the required variables and pins so let’s start with the void setup function.

    Void setup()

    • It is one of the most important functions in the Arduino code structure. Without this, our code will not compile successfully and will show the error.
    • In this, we will set the pin mode of each pin and set them to their initial values.
    • This function only runs once every time when we restart the code so that we will write the part of code which we want to run only
    • We will set the pinmode of seven segment LEDs to output mode as we want to control the LEDs from them.
    • And set the pinmode of push buttons as input as we want to read their state in the application.
    • For debugging purposes initialise the serial monitor also.
    • After this, we will write the void loop function.

    Void loop()

    • This is also one of the most important functions as per the structure of the Arduino code, we can not write the code without using this function.
    • In this function, we will write the code which we want to run in the continuous loop, so we will write our main application code in this section.
    • As per the application of our code first of all, we will read the Up and Down counter push button states and when the state changes we will trigger the counter.
    • Write the condition for the Up counter button, when the button is pressed then the state of the button changes and we will check the state of the push button. If it is HIGH then we will start incrementing the counter variable and using the “changeNumber()”, we will display the numbers on the seven segment LED display.
    • Similarly, for the down counter push button, when the push button is pressed then the state changes and when the state of the button is high then we will start decrementing the counter variable and display the number on the seven segment display using the “changeNumber()” function

    Void changeNumber(int buttonpress)

    • This is a user defined function.
    • We will use this function to display the number on the seven segment LED display.
    • This function will set the state of the LED’s pins as per the number we want to display.
    • It takes an argument as the number and with the help of switch-case, it will set the state of pins as per respective number.
    • The state of pins is decided by the truth table of the seven segment LED display mentioned in the above image of the truth table.

    Result and test

    After the circuit and the coding part, we are all set to run the simulation:

    • To run the simulation, we have to add the hex file of our application code.
    • We have to generate the hex file from the Arduino IDE.
    • To generate the hex file , goto “Sketch >> Export compiled binary” after that it will compile our application code and the hex file will be generated and will be saved in the same folder of the project.
    • Now include that to the Arduino UNO module in the simulation.
    • To add the hex file, click on the Arduino UNO module, then a window will be opened, from there browse to the location of the hex file and add that.
    • Now run the simulation.
    • At the start the LED display will show ‘0’.
    • So, when we press the Up push button, then the counter variable will be incremented by one on every press and when we push the Down push button, then the counter variable will be decremented by one on every push and the same will be displayed on the Seven segment LED display.

    Conclusion

    I hope we have covered all the points related to this project. I think it will be a useful project for learning purposes and gives an understanding about working of counters. Please let us know in the comment section if you have faced any issues while making this project.

    Thanks for reading this article. See you in the next project.

    Water Level Indicator using Arduino

    Hello geeks, welcome to our new project. Here, we are going to make a very useful project which we can use for ourselves or we can use this as a product as well on an industry level.

    In this project, we are going to make a water level indicator. We all know it is one of the most essential products because there are many water tanks in every house or office, and most of them are not easily accessible to check the level of water in it and I think most of us faced the problem such as shortage of water as we do not have anything to monitor the exact amount of water available in the tank and this causes many problems on our daily lives.

    Where To Buy?
    No.ComponentsDistributorLink To Buy
    1LEDsAmazonBuy Now
    2Arduino UnoAmazonBuy Now

    Software to install

    As we are going to make this project in the simulation first, for that, we will use the Proteus simulation tool. It is a tool used for electronic projects in which, we can run the real-time simulation of any electronic project and we can debug it in real-time without making any damage to real components.

    Proteus has a very big database for electronic components which comes in the installation package of Proteus, but still, sometimes we have to install packages or libraries for some modules which are not pre-installed in it.

    As in this project, we are going to use Arduino which is not pre-installed in the Proteus software. So we can download the Arduino module package from the link given below:

    Components Required

    In this project, we will use the following components
    • Arduino UNO
    • LEDs
    • Water level indicator

    Components details

    Arduino UNO

    • Arduino UNO is an open-source microcontroller of the Arduino family.
    • We have used this as the main controller of this project.
    • Using this we can measure the readings of the water level sensor and indicate the user accordingly.
    • It has 14 digital input/output pins which can be used for controlling any digital components or can be used to read digital sensors.
    • It has 6 analog input /output pins which are used for analog read and write functions.
    • The ADC used for analog pins is 10 bits which range from 0-1023.

    Note- While uploading the code on the Arduino UNO, disconnect any wire which is connected to Rx(D0) and Tx(D1) pins, otherwise it will give an error while uploading the code.

    Water Level Sensor

    • The water level indicator works on the principle of the potentiometer.
    • It has three pins as Vcc, Gnd, and Signal.
    • There are two kinds of exposed copper strips on the sensor which are Vcc and sensor line.
    • When it emerges in the water tank, the conductivity increases and the resistance decreases due to that, it increases the output voltage on the sensor pin of the water level sensor.
    • The output value of the sensor changes with the height of the water level in the water tank.
    • And this gives the analog output so that we will use the analog pin of the Arduino UNO for reading the sensor value.
    • As this will have analog values, we have to calibrate the sensor before using it in the project.
    • We will talk about calibration later in the article.

    LEDs

    • LED stands for light-emitting diode.
    • They are used for indication purposes in this project.
    • LEDs are like normal diodes, they will allow the current to pass from only one direction.
    • They come in different colors and the color of LEDs differs as per the used material in its manufacturing.
    • There are two terminals in the LEDs, the larger one is the cathode and another one is the anode.
    • Using the length of the terminals, we can figure out the polarity of the LED but if in case both terminals are the same size then there is a flat side on the LED, that side is the negative terminal and another is the positive terminal.

    Project overview

    The water level indicator works on the principle of change in the resistance of the water level sensor due to a change in the amount of water in the container.

    Basically, there are two parallel strips in the water level sensor, one for the power supply and another is for the sensor strip. As we know, water is a conductor of electricity so when we increase the amount of water in the container then more length of the sensor emerges in the water and that will increase the conductivity between the strips therefore, it increases the voltage on the sensor pin as well. We will read that voltage on the Arduino UNO.

    To get the exact amount of water level in the container, we have to calibrate the sensor with the water because we can not be assured that the output voltage will be the same for every water because we know that there are lots of materials dissolved in the water so it will vary for a different source of water, therefore, we have to calibrate it first.

    For calibration of the sensor, we will take a container with the water and we will read the values from the sensor by changing the level of water in the container. We will perform this action till the container gets filled with water and we will note down all the reference values and mark them as thresholds for each level.

    As in this project, we are making it in the simulation so it would not be possible for changing the values as per the water level therefore we have used the potentiometer and we have chosen the threshold values randomly.

    No need to worry while making this project with the real components as the sensor values from the water level sensor will be in the same format as the output of the potentiometer.

    Now that we know the working principle of the water level indicator let’s go for the circuit diagram of the project.

    Circuit diagram

    As we know the required components which we are going to use in this project.

    • First of all, start a new project in the Proteus simulation software.
    • Import all the listed components in the Proteus workspace.
    • For sensor simulation, we will import one potentiometer.
    • Connect the output pin of the potentiometer with the analog pin of the Arduino UNO. In this project, we are using the A0 pin.
    • And other pins with the ground and 5volt Vcc.
    • Now start connecting the LEDs, for controlling the LEDs, we will use the digital pins of Arduino and they are D2, D3, D4, D5 pins.
    • While connecting the LED pins, keep the sequence the same otherwise there will be an error in the indication of levels.
    • Connect the positive terminal of the LED with the digital pins of the Arduino and the negative pins with the ground.
    • Now we have completed the connection of our project. Let’s move to the coding side of this project.

    Arduino code of water level indicator

    For coding, we will use the Arduino IDE. It is a built-in IDE for Arduino developments.

    Arduino code is divided into mainly three parts: declaration of function and variables, second is void setup section, and third is void loop.

    First of all, declare the variables and pin number which we are going to use in this project.

    • Declare five variables for storing the pin numbers of LEDs and one variable for storing analog pins for reading the sensors.

    Void Setup()

    • This is the most important function in Arduino programming because our code will not compile successfully without using this function in the code.
    • When Arduino code starts this is the first function that runs.
    • This function runs only once when the code restarts.
    • So here, we will write the code which requires only one time to run.
    • In this function, we will basically declare the pin modes of the pins which we will use in the project.
    • Declare the pin mode of LEDs as output mode and sensor pin as input mode. Because we want to control the LEDs so that they must be in output mode and to read data from the sensor as input then it should be declared as input mode.

    Void loop()

    • This is the second most important function of Arduino code structure.
    • This function also must be in the code without it our code will not compile successfully.
    • In this function, we will write the main application code which we want to run continuously.
    • First of all, we will read the sensor value because we will make the decisions on the sensor values.
    • And for debugging purposes, we will print that value on the serial monitor.
    • As the sensor will give the analog output data, we will use the analogRead function for reading the sensor data.
    • After reading the sensor value, set the LEDs as per the threshold which we have calculated while calibrating the sensor for each level.
    • We will divide the values into five conditions for each level we set the LEDs accordingly.
    • First, we write the condition for when the container is full then, let’s assume the value will be more than 760. Then switch on all the LEDs.
    • After that, set the condition for the second level when the sensor value is lesser than 760 but greater than 720. Here we will set the 5th LED to low state and other LEDs to a high state.
    • Next check the condition for the third level when the sensor value is in the range of 615 to 720 and here we will set the 5th and 4th LED to low state and other LEDs to a high state.
    • Next check the condition for the fourth level when the sensor value lies in the range of 615 to 410. Here we will set the 3rd, 4th, 5th LEDs to low state and the rest two LEDs to a high state.
    • After that, check the condition for the fifth level when the sensor value lies in the range of 410 to 250, and here we will set 5th, 4th, 3rd, 2nd LED to low state and remaining one LED to a high state.
    • Last check the condition for when the container is almost empty when the sensor value lies in the range of 250 to 0. Here we will set all five LEDs to a low state.
    • After that give a delay of 1 second for settling of sensor values and calibration.

    Results and working

    Now we have completed our code and circuit, it's time to run the project.

    • To run the simulation, we have to include the hex file of the Arduino code.
    • We will generate the hex from the Arduino IDE.
    • To generate the hex file, go to the Sketch >> Export compiled binary, after that, it will compile the code and in the project folder, there will be two files one is binary and the other is hex file.
    • Now we have to include the hex file in the Arduino module in the Proteus software.
    • Click on the Arduino UNO module, then a window will pop up where you can add the hex file of the project.
    • Now we are all set to run the project, click on the Run button in the software to start the simulation.
    • To change the water level in the simulation, we will change the value on the potentiometer and as the values from the potentiometer change then the LEDs will also respond accordingly.
    • First check the condition when the water level is very low, mostly when the container is empty.
    • When the water level is very low then there will be very less conductivity or maybe no conductivity, in this case, the output voltage from the sensor will be very less.
    • So in this condition, all LEDs will be off.
    • In the image, we can see that the voltage at the analog pin is 0.5 volts.
    • Now when the water level increases then in that condition the conductivity will also increase so does the output voltage from the sensor.
    • So let’s increase the water level to the first level.
    • Here we can see the output voltage increased to 1.5 volts and the first led is glowing.
    • Now similarly increase the water level for next levels.
    • Check water for the second level. The output voltage is iincreased to 2 volts.
    • Now check for the next level.
    • Now check for when the container is filled. Then all LEDs will glow.

    Conclusion

    I hope we have covered all the points related to this project, and I think it will be very useful in daily life and it will give us ease of monitoring water in our water tanks. After this project, we don’t have to take the headache of how much water is available in our tank. And please let us know in the comment section if you have faced any issues while making it and also how you are going to use it in real life.

    Thanks for reading this article. All the best for your projects.

     

    Regulated Power Supply Using LM317

    Hello geeks, welcome to our new project. We are going to make an important project which will be very useful for us in our daily life which is a variable DC power supply. As engineers who work with electronics need different voltage ranges of DC power supply for different electronic projects and components. It becomes very clumsy and hard to manage different power supplies because of wires which are connected to it and each power supply consumes an extra power socket as well.

    So in this project, we will overcome this issue and learn to make an adjustable DC power supply, in which we will get a wide range of voltages.

    Software to install

    We will make this project in the simulation, as it is a good practice to make any project in the simulation first so that if we do any mistakes or errors in the circuit, which can be corrected without making any physical damage to actual components.

    To make this project we will be using the Proteus simulation tool. A brief about the Proteus, it is a simulation software for electronics, here we can make different types of electronic circuits and run the simulation and it will give us the real-time working model of our circuit. Also, we can easily debug in case of a wrong connection.

    It has a very large database of pre-installed components which has basically all types of different electronic components and in case, if it is not pre-installed, then we can install a library for those.

    Components Required

    • One Step down transformer
    • Five 1N4007 Diodes
    • One 4700 microFarad Polarised capacitor
    • One 100 microFarad Polarised capacitor
    • Three 0.1 microFarad non-polar capacitors
    • One 5 kOhms potentiometer
    • One 220 Ohms resistor
    • One LM317 IC

    Components details

    1. LM317

    • It is a voltage regulator IC which has a wide range of applications in various voltage limiting circuits.
    • It has three terminals as Vin, Vout, Adjust.
    • Using these three pins only we can regulate the output voltage.
    • As the name suggests, the Vin pin is used for the input power supply, the Vout pin is used to take the output voltage, and Adjust pin is used to control the output voltage.
    • It is a very easy-to-use IC, it requires only two resistors for the circuit and it will be ready to use.
    • It uses one resistor for the RC filter and one as a potentiometer to adjust the output voltage.
    • As per the datasheet, it has a formula for calculating output voltage, and using that we can adjust our resistor value as per our requirement of output voltage.
     
    • For more details about this IC prefer the following datasheet:

    2. Step down Transformer

    • Step down transformer is used to convert the high input voltage to low voltage.
    • It takes high voltage and low current as an input and it will give low voltage and high current as an output.
    • Here we will not go in-depth about the working of transformers but in brief, it has two windings as primary and secondary.
    • It is the exact opposite of the Step-up transformer as per the use case and windings.
    • In this type of transformer, there are more turns on the primary side winding and lesser turns on the secondary side winding.
    • It is mostly used in power supplies.

    3. Diodes

    • Diodes are two-terminal simple electronics components.
    • It works as a valve which allows the flow of current in only one direction and limits the flow of current in another direction.
    • They are used mostly in every electronic device such as in power supply or as regulators or used in construction ICs for logic gates.
    • It has two terminals as Anode and Cathode and current is allowed to flow from Anode to Cathode side only.
    • As per the construction, it has two sides P side and N side.
    • The P side terminal is also known as Anode and the N side terminal is known as Cathode.
    • A simple PN type diode is made using the P-type and N-type semiconductors.
    • In N-type semiconductors, free electrons are in majority, and in P-type semiconductors, holes are in majority.
    • There are various types of diodes available but as per our use case, we will use a simple PN junction type diode.
    • We are using the diodes as rectifiers in this project.

    4. Capacitors

    • Capacitors are electronic components that have the ability to store energy.
    • It has two terminals that are connected with two parallel conductor plates and they are separated from each other with an insulating material called dielectric material.
    • When we apply voltages across the terminals then due to generated electric field, it stores energy in the form of electric charges.
    • We have used capacitors in this project for filtering purposes.
    • There are various types of capacitors as per the use case in this project we have used the non-polarized and polarized capacitors.

    5. Potentiometer

    • It is a passive electronic component using which we can vary the output voltage by changing the resistance.
    • Basically, it is a variable resistor in which we change the resistance by moving a nob.
    • It has three terminals as Vcc, Ground, and Vout.
    • There are two types of potentiometers. First is the Rotary potentiometer and the second is the Linear potentiometer.
    • In this project, we have used a rotary potentiometer.
    • The main application of a potentiometer is a voltage divider. And using this characteristic, it is used in various types of applications such as speed controlling of motors, volume control in audio systems, etc.

    Project Overview

    In this project, we will use the following components-

    • LM317 - We will be using this IC as the main controller of our project, using this we will regulate the voltage of the power supply.
    • Diodes - These are very important components for any DC power supply as they will change the AC supply to DC supply.
    • Step down Transformer - This will be used as an isolator and it will lower the input voltage.
    • Capacitors - These are used for smoothening the pulses and making the noise-free power supply.
    • Potentiometer - It is used as a regulator to set the output DC voltage.

    Now we know the basic role of each component, so let's talk about how actually our power supply will work. In brief, the flow of our power supply will be as mentioned further.

    We connect it with AC power then we will lower down the AC supply to 12-24 AC because most of the electronic component has this working voltage range, thereafter we will change the AC to DC and do the smoothening of that DC supply, and then we will regulate that using a potentiometer and LM317 IC.

    • To step down the AC voltage we have used the Step-down transformer and it will also isolate the AC circuit with the DC circuit although there are ways to step down the power without using the transformer also.
    • After that, using the diodes we will make a full-wave bridge rectifier. It will change the AC power to DC but still, it will have some ripple from the AC supply.
    • To smoothen the ripples from the AC supply we will use the RC filters, where we will connect some capacitors.
    • Now we will have the smooth DC supply that we will use as input power for LM317 IC and a potentiometer will be connected to it.
    • Using that potentiometer, we will change the output voltage.

    Circuit Diagram and Working

    Now we know all the components which we will use in this project and their use cases also. Let's start connecting them.

    • Start the new project in the Proteus software and import all the required components to the workplace.
    • Now, we have all the listed components in the workplace.
    • First, connect the AC power supply with the Step-down transformer primary winding.
    • On the secondary winding of the transformer, we will connect the full-wave bridge rectifier which we will make using the diodes. They are simple 1N4007 diodes.
    • First, we will make two pairs of diodes by connecting two with each other.
    • In the first pair, we will connect the Anode of two diodes with each other and leave the other two terminals free.
    • Then in the second pair, we will connect the Cathode of two diodes with each other and leave the other two terminals.
    • Now we have two free terminals in each pair, and we will connect them with each pair.
    • If you are working with real components, just remember there will be a grey color stripe on the diode so that side will be Cathode and another side will be Anode.
    • In simple words just take two diodes, connect the grey strip side of them with each other, then take another two diodes and connect the black side with each other, and after that connect them with each other.
    • It is very important to connect the diodes very carefully otherwise our power supply will not work.
    • And in case of wrong connections, it will flow the AC current in our circuit and that would be very dangerous.
    • Now we have completed our full-wave bridge rectifier so now connect the input side of that with the secondary side of the step-down transformer.
    • And connect two capacitors parallel to the output side of the rectifier. That is used for smoothening the output power.
    • One 4700 microFarad capacitor and a 0.1 microFarad capacitor.
    • While connecting the polar capacitor keep the terminals in mind.
    • Connect the positive terminal of the capacitor with the positive side of the rectifier and the negative side with the negative side of the rectifier.
    • In the polar capacitor, the longer terminal is positive and the shorter side is negative.
    • Now let's connect the LM317 IC with the circuit.
    • As we know LM317 has three pins so connect the Vin pin of IC with the positive terminal output of the rectifier.
    • Now connect the Adj pin of IC with the potentiometer and Vout of IC will be the output of the power supply.
    • We will use some more resistors and capacitors for filtering purposes.
    • Connect two capacitors parallel with the output of LM317 and one RC filter also with it.
    • At last, connect a diode from the output of LM317 with the input side of LM317 that will prevent the flow of reverse voltage. It is for simple protection.
    • Now we have completed the connection of our circuit. For debug purposes, connect a voltmeter at the end so that it will be easy to check the working of the power supply and we can monitor the change in the output voltage by changing the value using the potentiometer.

    Results and Working

    • Now run this project.
    • At first, AC high voltage will be converted to low voltage AC.
    • As we know AC power is a sine wave and DC power is a straight line. It does not travel as a sine wave.
    • That will be converted by the full-wave bridge rectifier. We know that diodes allow the flow of current only in the forward bias. This means only half of the cycle of the sine wave will pass through it, that is when the sine wave is in a positive direction.
    • So to overcome this problem, we have used the diodes as full-wave bridge rectifiers.
    • When the AC sine wave will be in the positive half cycle, the diodes D2 and D3 will be in forward bias, thus they will let the current flow. But D4 and D5 will be in reversed bias so they will not allow the current to flow.
    • And when the AC sine wave will be in the negative half cycle, the diodes D2 and D3 will be in reversed bias, and diodes D4 and D5 will be in forward bias and that is how current will flow here. Thus, we will get the current in a full sine wave.
    • So the output of the full-wave bridge rectifier will be like the following image:
    • But still, this wave is not a DC current, so to make it a smooth DC current we have used the capacitors.
    • When the wave goes upward, at that time, the capacitors store the charge but when the wave goes downward, then the capacitors start discharging, and while discharging they maintain the output voltage and let the current flow.
    • But this will make some ripples and to neutralize that, we have used another capacitor that will do the same charging-discharging process and after that, we will have a straight line of pure DC power.
    • Now DC power will go into the LM317 regulator IC. Thereafter when we change the value from the potentiometer, we can see the output voltage will change on the voltmeter which is connected to the output side.
    • We can see in the following image when the value of the potentiometer is 4% then the output voltage is 2.40 volts
    • Let’s change the value of the potentiometer.
    • After changing the value of the potentiometer to 52%, we can see that output voltage is also changed to 14 volts.
    • As we can see that output voltage changes by changing the value of the potentiometer which means our regulated power supply is working well.

    Conclusion

    I hope we have explained all the points related to this project. And I hope this will be a very useful project for your daily use as a power supply.

    Please let us know if you face any issues while making this project in the comment section below.

    We will be happy to know if you will make this project and how you are going to use it in your daily life.

    Thanks for reading this article and All the best for this project, see you in the next one.

    Motion Detection with ESP32 & PIR Sensor

    Hello readers, we hope you all are doing great. Welcome to the 4th lecture of Section 5(ESP32 Sensor) in the ESP32 Programming Series. So far, we have discussed the ESP32 built-in sensors in this section. Today, we are going to interface an external embedded sensor(i.e. PIR Sensor) with the ESP32 Microcontroller board. At the start, we will discuss the basics of a PIR Sensor(HC-SR501) i.e. its pinout and working. After that, we will design a simple project to detect the motion with a PIR sensor and ESP32. Finally, we will display the motion detection results on the ESP32 WebServer.

    We will use ESP32 interrupts to detect the motion. Interrupts are used when a microcontroller needs to continuously monitor an event while executing other tasks at the same time. We have already posted a tutorial on ESP32 Interrupts, which includes both software and hardware interrupts. In this tutorial, we are implementing the hardware interrupt(Hardware interrupts are the external interrupts that are caused by an external event). In our project, the hardware interrupt will be generated by the PIR sensor.

    PIR motion sensor is mostly used in home automation & security projects, used to enable the system to respond automatically over human presence. Appliances connected to ESP32 will respond automatically(as per the instructions provided) whenever an interrupt is triggered by the PIR motion sensor. Let's first have a look at the working of PIR Sensor:

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

    What is a PIR Motion Sensor?

    In today's project, we will use the HC-SR501 PIR Sensor to detect the motion. PIR stands for Passive Infrared sensors. It uses a pair of pyroelectric sensors to detect heat energy in the surrounding environment. Both the sensors sit beside each other, and when a motion is detected or the signal differential between the two sensors changes the PIR motion sensor will return a LOW result (logic zero volts). It means that you must wait for the pin to go low in the code. When the pin goes low, the desired function can be called.

    PIR Sensor Calibration

    PIR Sensor has two variable resistors on its back side, used to adjust the Sensitivity and Detection Range, explained below:

    • Low sensitivity ignores the small motions i.e. a moving leaf or a small mouse. The sensitivity can be adjusted based on the installation location and project requirements.
    • The second resistor is used to specify how long the detection output should be active. It can be set to turn on for as little as a few seconds or as long as a few minutes.

    PIR Sensor Applications

    Thermal sensing applications, such as security and motion detection, make use of PIR sensors. They're frequently used in security alarms, motion detection alarms, and automatic lighting applications.

    Now let's interface the PIR Sensor with ESP32:

    Interfacing PIR Sensor with ESP32

    As I mentioned earlier, in today's project, we will design a motion detection project with ESP32 and PIR Sensor. In the first example, we will turn "ON" the LED on motion detection, while in the second project, we will display the results in the ESP32 WebServer.

    Here's the list of the components for today's project:

    Components Required

    • ESP32 Development Board
    • PIR motion sensor (HC-SR501)
    • LED
    • 1k Ohm resistor
    • Jumper Wires
    • Breadboard

    Circuit Diagram

    Here's the circuit diagram for motion detection with ESP32 and PIR Sensor:

    Now let's design the programming code for motion detection:

    ESP32 Motion Detection Code

    We are using Arduino IDE to compile and upload code into the ESP32 module. You need to first Install ESP32 in Arduino IDE to get started. Here's the code for motion detection:

    //----Set GPIOs for LED and PIR Motion Sensor
    const int led = 23;
    const int PIRSensor = 4;
    
    // -----Timer: Auxiliary variables
    #define timeSeconds 10
    unsigned long now = millis();
    unsigned long lastTrigger = 0;
    boolean startTimer = false;
    
    //---Checks if motion was detected, sets LED HIGH and starts a timer
    void IRAM_ATTR detectsMovement()
    {
        Serial.println( " MOTION DETECTED " );
        Serial.println("Turning ON the LED");
        digitalWrite(led, HIGH);
        startTimer = true;
        lastTrigger = millis();
    }
    
    void setup()
    {
        Serial.begin( 115200 ); // Serial port for debugging purposes
        pinMode( PIRSensor, INPUT_PULLUP ); // PIR Motion Sensor mode INPUT_PULLUP
        pinMode( led, OUTPUT );
        digitalWrite( led, LOW );
        attachInterrupt( digitalPinToInterrupt( PIRSensor ), detectsMovement, FALLING ); // Set PIRSensor pin as interrupt, assign interrupt function and set RISING mode
    }
    
    void loop()
    {
        now = millis();
        if( startTimer && (now - lastTrigger > ( timeSeconds*500)))
        {
            Serial.println(" Turning OFF the LED " );
            digitalWrite( led, LOW );
            startTimer = false;
        }
    }
    

    Variables Declaration

    • The first step is to set up the GPIO pins for the LED and motion sensor(PIR).
    • LED is connected to GPIO23 and PIR sensor to GPIO4, as shown in the below code:
    //----Set GPIOs for LED and PIR Motion Sensor
    const int led = 23;
    const int PIRSensor = 4;
    • Next, we need variables to set the timer to count the time, after the interrupt is detected.
    • The variable "now" defines the current time
    • The variable "lastTrigger" defines the time when the interrupt is detected.
    • The variable "startTimer" is used to start the time when an interrupt is detected.
    //-----Timer: Auxiliary variables
    #define timeSeconds 10
    unsigned long now = millis();
    unsigned long lastTrigger = 0;
    boolean startTimer = false;

    ESP32 Interrupt Function "IRAM_ATTR"

    • The Function with the attribute "IRAM_ATTR" is executed inside the internal RAM.
    • We are assigning this attribute to our interrupt function because RAM (random access memory) operates faster than flash memory.
    • After the execution of the interrupt code or ISR, the normal code will be executed inside the flash memory.
    • It is recommended that the interrupt service routine should have the minimum possible execution time because it halts or blocks the normal program execution.
    //---Checks if motion was detected, sets LED HIGH and starts a timer
    void IRAM_ATTR detectsMovement()
    {
        Serial.println( " MOTION DETECTED " );
        Serial.println("Turning ON the LED");
        digitalWrite(led, HIGH);
        startTimer = true;
        lastTrigger = millis();
    }

    Setup() Function

    • Inside the setup() function we are initializing the serial communication with a baud rate of 115200.
    • Set the mode of pin GPIO23 (LED) as output.
    • Set the initial state of the LED as LOW.
    • Assigned the digital pin(connected to the PIR Sensor) to hardware interrupt using the attachInterrupt function.
    • The detectMovement function is passed as an argument inside this function.
    void setup()
    {
        Serial.begin( 115200 ); // Serial port for debugging purposes
        pinMode( PIRSensor, INPUT_PULLUP ); // PIR Motion Sensor mode INPUT_PULLUP
        pinMode( led, OUTPUT );
        digitalWrite( led, LOW );
        attachInterrupt( digitalPinToInterrupt( PIRSensor ), detectsMovement, FALLING ); // Set PIRSensor pin as interrupt, assign interrupt function and set RISING mode
    }

    Loop() Function

    We have activated the interrupt in the Setup Function, so when the PIR Sensor detects the motion, it will automatically execute the interrupt function, which will turn the LED ON and start the timer.

    • In the loop function, we are comparing the current time with the last triggered time.
    • LED will turn off after a delay of 5sec (once an interrupt is detected).
    • The variable “now” will be updated with the current time in each iteration.
    void loop()
    {
        now = millis();
        if( startTimer && (now - lastTrigger > ( timeSeconds*500)))
        {
            Serial.println(" Turning OFF the LED " );
            digitalWrite( led, LOW );
            startTimer = false;
        }
    }

    Motion Detection Results/Testing

    • Select the right development board from Tools >> Boards >> DOIT ESP32 DevKit V1 in Arduino IDE.
    • Compile and upload the code into ESP32 using Arduino IDE.
    • Open the serial monitor with a 115200 baud rate as defined in the Arduino code.
    • Press the EN button on the ESP32 development board.

    This concludes the tutorial. I hope you find this tutorial helpful. Thanks for reading. See you soon with a new tutorial on ESP32. Take care !!!

    Christmas Tree using Arduino

    Hello Geeks, I hope you all are doing great and enjoying your festive seasons. This time, we have come up with a new project which will make your festival a bit brighter so here comes a Christmas tree.

    It is said that Christmas is the center of all the celebrations. Did you guys know the scientist who discovered the light bulb, Thomas Edison and his friends were the first to put up the light bulbs on the Christmas tree, and here we are going to keep that tradition forward? Well, it’s time to gear up for the next season of Christmas being tech-savvy. Hence we have decided to brighten up a Christmas tree with the usage of Arduino Uno and LEDs in real life.

    Where To Buy?
    No.ComponentsDistributorLink To Buy
    1LEDsAmazonBuy Now
    2Arduino UnoAmazonBuy Now

    Software to Install:

    To make our festival a little safer, we will first make our Christmas tree in the simulation and for that, we will use the Proteus simulation software. Making it in the simulation will give us a good understanding of how it is going to work, and how we are about to design the Christmas tree such as the placements of lights and lighting patterns.

    Proteus is a simulation tool for electronic projects. In this software, we can make approximately every type of electronic circuit and run the working simulation. It will show the real-time working simulation of the circuit and errors as well if any occurs.

    It has a large database of mostly all types of electronic components but still, for some, we have to install libraries. In this project, we are using Arduino UNO and it is not pre-installed so we have to download it first.

    Project Overview:

    Following components will be required to design our Christmas Tree

    • Arduino UNO - It works as the main controller in the project. We have used this to make different types of lighting patterns and using this, we will have a scope to make interesting lighting effects.
    • LEDs - We will need LEDs for our Christmas tree. We have used different colors of LEDs to make the matrix shape circuit for the Christmas tree.

    Components required:

    • Arduino UNO
    • Different colors of LEDs

    Components Details:

    Arduino UNO

    • Arduino UNO is an open-source development board that we will use in this project.
    • There are many types of Arduino development boards available but as per our requirement, we will be using Arduino UNO.
    • It uses the ATMega328P processor.
    • This microcontroller has a RISC-based architecture.
    • It has 32KB flash memory, 2KB of SRAM and 1 KB of EEPROM.
    • Talking about the communication peripherals, it has 1 SPI, 1 I2C and 1 UART on board.
    • It comes with 6 individual PWM channels and 6 channels of ADC.
    • There are 14 digital pins starting from D0-D13 and 6 analog pins starting from A0-A5 in this.
    • D10-D13 can be used for digital I/O and SPI communication pinouts.
    • A4 and A5 can be used for analog I/O and I2C communication pins.
    • To power the Arduino, we can use the USB or Vin pin of the Arduino UNO board.
    Note - It is recommended to disconnect any connection which is connected with the D0 and D1 pin of Arduino UNO before uploading the code otherwise it will cause issues in communication with the Arduino UNO and there can be an error for the same.

    LEDs

    • In this project, we have used different colors of LEDs for our Christmas tree.
    • LED stands for light-emitting diode.
    • It is one of the most efficient light sources compared to all other types of lights or bulbs.
    • They are used mostly in all types of electronics projects such as display, indicators or works as a light source.
    • Due to the long range of applications, LEDs come in a variety of shapes and colors.
    • There are two poles for connecting it, one is short and the other one is longer.
    • Talking about the connection, the longer side pole will be connected to positive voltage and the shorter side will be connected to the ground.
    • As LED is a type of diode, the current will flow in only one direction. In case, if we connect the wiring incorrectly, it will not work.
    • But still, if we have connected the LED wrong, no need to worry, just flip it over.

    Mostly it has not been damaged yet.

    • LEDs come in different voltage working ranges but here we have used 5v operating

    Circuit Diagram and Working:

    Now let's start with the circuit diagram of our project. The first step would be to import all the components to the workspace of Proteus software.

    We will be using one Arduino UNO for controlling the LEDs and six different colors of LEDs. Here we will make 6 rows and 6 columns of LEDs for our Christmas tree, so we will be using 6 Aqua color LEDs, 6 Green color LEDs, 6 Orange color LEDs, 6 White color LEDs, and 6 Yellow color LEDs.

    • After importing all the components to the workplace, it’s time to start connecting them.
    • We will use 6 pins of Arduino UNO for rows and 6 pins for columns. As we know, Arduino UNO has 14 digital pins but as suggested we should not connect any connections with D0 and D1 pins.
    • We will connect from D2 to D7 with the rows and D8 to D13 for columns.
    • While connecting the LEDs, we must be very careful in case, if we connect any wrong terminal or any wrong connection, our whole tree will not work because all of them are connected in series with each other and that is the drawback of series connection.
    • In case any connection is loose or wrong then all of the connected components will not work.
    • Keeping this in mind, when we will use the real components, make sure all the LEDs are working fine otherwise we will not get the desired output.
    • Don’t leave any loose connections or hanging wires.
    • It would be easy if we would connect it in steps therefore we will divide it into three steps.
    • First, connect all LEDs and make a 6x6 matrix. For connecting those we can use the simple twisted copper wires.
    • While connecting the LEDs, mind the terminals.
    • Now we will connect the column pins.
    • After connecting the pins, we will connect the row pins.
    • We have divided the connections in different pictures so that it would be easy to understand.
    • After completing all the connections, our circuit will look like as shown in the picture below.
    • Here, we have adjusted the wires, so that it will be in shape as the Christmas tree.
    • After completing the connections, there may be a doubt about the working of this circuit.
    • It is a little tricky, we have to make sure from the coding side that whenever we want to glow any LED, its ground terminal should be logic LOW and the positive terminal should be logic HIGH.

    Arduino Coding:

    After the connection of the circuit, let's start to code our Christmas tree:

    • For writing the code, we will be using the Arduino IDE.
    • In this application, we will not require any external library.
    • So our code will be divided into three parts: first declaration of variables, pin definition and setup and the last main application logic.

    Code declaration

    • First, declare two arrays for rows and columns.
    • In those arrays, we will store assigned pins for each row and column.
    • As we are using D8 to D13 for columns, that will be stored in the “column” array and D2 to D7 for rows, similarly, that will be stored in the “row” array.

    Void setup function

    • This is one of the most important functions as per the structure of the Arduino sketch.
    • As we are using the GPIO pins to control the LEDs, we will set the pin modes of LEDs to be in output mode.

    ? We have declared all the row and column pins in the output modes.

    Void loop function

    • In this function, we will write our main application code for our Christmas tree.
    • Here we will write the interesting patterns to glow the LEDs of the tree.
    • While making patterns, we only need to focus on two points, first, if we want to glow LEDs sequentially from rows, in this case, set all the pins of the column to logic HIGH state and if we want to glow the LEDs sequentially from columns then we need to set all the row to logic LOW state.
    • Keeping the above-mentioned points, we can glow any pattern on our tree.
    • For blinking the LEDs in a row-wise direction. We have to set all the column pins to HIGH state and then toggle the rows pin to HIGH-LOW.
    • For blinking the LEDs in a column-wise direction. We have to set all the row pins to LOW state and then toggle the column pins to HIGH-LOW.
    • To turn off all the LEDs, either set all the pins of columns and rows to logic HIGH or set all the pins of columns and rows to logic LOW.
    • To turn off the LEDs by setting all column and row pins to a HIGH state.
    • To turn off the LEDs by setting all column and row pins to LOW state.
    • We can use either of the above-mentioned logic depending upon the next pattern.
    • Using these simple logics, we can write various patterns.
    • Here in this code, we have written some interesting patterns that would be easy to understand while running the code.

    After completing the development side of the Christmas tree, it is time to test it.

    Results and Working:

    • As we have successfully completed the coding and the wiring part of our project, let's start the real fun of running it.
    • In the Proteus, to run any application code, it requires a hex file of the application code.
    • First of all, we need to generate the binary or hex file of our application code using the Arduino IDE.
    • To generate the hex file, we need to go to the toolbar and then click on the “Sketch” option. Thereafter click on the “Export compiled binary”.
    • After that, it will compile the code and a hex file will be generated.
    • Now add this hex file to the Proteus project.
    • To do so, click on the Arduino UNO module and go to the “Program File” option, then browse to the folder containing the hex file.
    • Now we are all ready to test our project.
    • Click on the “Play” button in the Proteus software.
    • As per our code, first, all the LEDs will blink column-wise, after every 100 milliseconds of delay.
    • Then all the LEDs will blink row-wise similarly after every 100 milliseconds of delay.
    • After that, all the LEDs will be off and it will start glowing in the column-wise pattern from both sides towards the center.
    • Thereafter, it will start glowing from the center towards the sides.
    • Each row will glow and after that, all the LEDs will be off, thereafter each will blink sequentially.
    • The working logic of this circuit is pretty simple. We just have to maintain the appropriate switching of the pins.
    • Using the same we can have different types of interesting patterns.

    Here is the working demo of our Christmas Tree

    I hope we have covered all the points related to this project and you have enjoyed reading it. We can use this with the real component and decorate the Christmas tree or we can use some cardboard and insert the LEDs on them in the same way.

    If you have any doubts regarding the project. And we will be glad to read about how you made your Christmas tree using this project and if you try any interesting new patterns with it, please let us know in the comment section.

    Merry Christmas.

    Servo Motor Control with ESP32 WebServer

    Hello readers, we hope you all are doing great. In this tutorial, we are going to demonstrate how to interface and control a servo motor using an ESP32 board. After that, we will demonstrate how to create a webserver to control the servo motor’s shaft position with the ESP32 board.

    Servo Motors are among the most important actuators in robotics, with applications ranging from RC planes to automated door locks.

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

    Hardware components required

    • A servo motor
    • ESP32 development board
    • Connecting wires
    • Breadboard

    Servo Motor

    There are several specific types of electric motor applications in which the motor must rotate only at a specific angle. For such applications, we need a special type of motor with such a special arrangement that causes the motor to rotate at a specific angle for a given electric signal (input). The servo motor comes into effect for this purpose.

    A servo motor is a linear or rotary actuator that enables accurate control of linear or angular position, acceleration, and velocity. It is made up of a motor and a sensor for position feedback. It also necessitates a fairly sophisticated controller, which is frequently a dedicated module designed specifically for use with servo motors.

    Fig. Servo Motor

    The primary reason to use a servo motor is that it offers angular precision, which means that it will only rotate as far as we want it to before stopping and waiting for the next signal to take action. The servo motor, unlike a standard electric motor, begins to turn as soon as we apply input power to it and continues to rotate until we turn off the power. We cannot restrict the rotational progress of an electric motor, but we can control its speed and turn it on and off. Small servo motors are included in numerous beginner Arduino launcher kits since they are simple to use in small electronic projects and applications.

    Interfacing Servo Motor with ESP32

     

    Fig. Interfacing Servo motor with ESP32

    When compared to an Arduino, interfacing a servo motor to the ESP32 is extremely difficult because it does not support analogWrite(). However, it employs a variety of frequencies and timers, allowing all digital pins to be used as PWM pins and to send signals much faster than any Arduino.

    Connections:

    Servo motor consists of three wires;

    Table 1 ESP32 and servo motor interfacing

    Controlling servo motor

    A servo motor is controlled by sending a PWM or pulse width modulated signal. A servo motor can only turn for a total of 180-degree movement (90 degrees in either direction).

    The PWM signal sent to the motor specifies the position of the shaft, and the rotor will turn to the desired position depending on the duration of the pulse sent through the control wire.

    Arduino IDE programming

    We are using Arduino IDE to compile and upload code into the ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial i.e., on the ESP32 programming series.

    • Installing Required Libraries
    • Download the library from the given link:

    https://github.com/RoboticsBrno/ServoESP32

    • Open the Arduino IDE.
    • Go to Sketch >> Include Library >> Add .ZIP library.
    • Select the zip file you have downloaded from the above link.

    Fig. Adding Library file

    Arduino IDE Code

    • We are using the example code that comes with the library file we have downloaded for the above link.
    • To access the example code, go to Files >> Examples >> Servo ESP32 and select the required example code.
    • In this tutorial, we are using a simple servo example code.

    #include <Servo.h>

    static const int servoPin = 4;

    Servo servo1;

    void setup()

    {

    Serial.begin( 115200 );

    servo1.attach( servoPin);

    }

    void loop() {

    for(int posDegrees = 0;

    posDegrees <= 180;

    posDegrees++)

    {

    servo1.write( posDegrees );

    Serial.println( posDegrees );

    delay( 20);

    }

    for(int posDegrees = 180;

    posDegrees >= 0;

    posDegrees--)

    {

    servo1.write( posDegrees);

    Serial.println( posDegrees);

    delay(20);

    }

    }

    Code Description

      • The first task is adding the required library files or header files.

    Fig. header file

    • Define the GPIO pin which you are going to use for controlling the servo motor.

    Fig. Defining Variables

    • Create an object Servo, which is called

    Setup()

    • Inside the setup() function, the first task is to initialize the serial monitor with a 115200 baud rate for debugging purposes.
    • Attach the GPIO pin you have assigned to the variable servoPin (in the global declaration) to the servo object.

    Fig. setup function

    Loop()

    • As we mentioned earlier, a servo motor can only rotate between 0 to 180 degrees. So in this code, we are changing the position of the servo motor from 0 degree to 180 degrees and then back to 0 degree from 180 degrees.
    • We have defined a variable postDegree to store the position or angle of the servo motor.
    • We are using the for() loop, which will change the position of servo motor from 0 to 180 degrees.

    Fig.

    • Another for() loop is used to change the position back to 0 degrees from 180 degrees.

    Testing

    • Select the right development board from Tools >> Boards >> DOIT ESP32 DevKit V1 in Arduino IDE.
    • Compile and upload the code into ESP32 using Arduino IDE.
    • Open the serial monitor with a 115200 baud rate as defined in the Arduino code.
    • Press the EN button from the ESP32 development board.
    • Now you should see the servo motor’s shaft rotating as per the instructions provided.
    • You can observe the variation on shaft’s angle on the serial monitor as well, as shown below:

    Fig. Serial monitor output

    Fig. ESP32 and servo motor

    Creating a web server to control servo motor with ESP32

    Let’s create a web server to control the position of the servo motor. We will create a web page containing a slider to control the angle/position of the servo motor’s shaft.

    We have also created a tutorial on creating a simple web server with ESP32.

    Arduino IDE Code

    #include <WiFi.h>

    #include <Servo.h>

    Servo servo1; // create servo object to control a servo

    // twelve servo objects can be created on most boards

    // GPIO the servo is attached to

    static const int servoPin = 13;

    // Replace with your network credentials

    const char* ssid = "SSID";

    const char* password = "PASSWORD";

    // Set web server port number to 80

    WiFiServer server(80);

    // Variable to store the HTTP request

    String header;

    String valueString = String(5);

    int angle_x = 0;

    int angle_y = 0;

    // 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);

    servo1.attach(servoPin); // attaches the servo on the servoPin to the servo object

    // Connect to Wi-Fi network with SSID and password

    Serial.print("Connecting to ");

    Serial.println(ssid);

    WiFi.begin(ssid, password);

    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();

    // Display the HTML web page

     

    client.println("<!DOCTYPE html><html>");

    client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");

    client.println("<link rel=\"icon\" href=\"data:,\">");

    // CSS to style the slider

    // Feel free to change the background-color and font-size attributes to fit your preferences

    client.println("<style>body { text-align: justify; font-family: \"Trebuchet MS\", Arial; margin-left:auto; margin-right:auto;}");

    client.println(".slider { width: 600px; }</style>");

    client.println("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>");

    // Styling Web Page

    client.println("</head><body><h1>Control Servo via ESP32</h1>");

    client.println("<p>Angle: <span id=\"servoPos\"></span></p>");

    client.println("<input type=\"range\" min=\"0\" max=\"180\" class=\"slider\" id=\"servoSlider\" onchange=\"servo(this.value)\" value=\""+valueString+"\"/>");

    client.println("<script>var slider = document.getElementById(\"servoSlider\");");

    client.println("var servoP = document.getElementById(\"servoPos\"); servoP.innerHTML = slider.value;");

    client.println("slider.oninput = function() { slider.value = this.value; servoP.innerHTML = this.value; }");

    client.println("$.ajaxSetup({timeout:2000}); function servo(pos) { ");

    client.println("$.get(\"/?value=\" + pos + \"&\"); {Connection: close};}</script>");

    client.println("</body></html>");

    //GET /?value=180& HTTP/1.1

    if(header.indexOf("GET /?value=")>=0) {

    angle_x = header.indexOf('=');

    angle_y = header.indexOf('&');

    valueString = header.substring(angle_x+1, angle_y);

    //Rotate the servo

    servo1.write(valueString.toInt());

    Serial.println(valueString);

    }

    // 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(" ");

    }

    }

    Code Description

    • Replace SSID and PASSWORD with your network credentials.

    Fig. Variables to store Network credentials

    • As we are creating a web server, we need to assign a port to it and normally we use port 80 for a local webserver.
    • So, in the below code, we have assigned port 80 to the web server and then initialized a few variables:

    Fig.

    • header variable is used to store the HTTP requests.
    • Variables angle_x and angle_y are used to store the position/angle of servo motor’s shaft.

    Fig.

    • Variables to store timer values for a delay of 2sec or 2000ms.

    Fig.

    Setup()

    • Inside the setup() function, servoPin is being attached to the servo1 object.

    Fig.

    • Wi-Fi.begin() is used to initialize the ESP32’s wi-fi module.
    • IP address of the device will be fetched once ESP32 is successfully connected to the wi-fi network.
    • begin() function is used to initialize the webserver mode in ESP32.

    Loop()

    • After the webserver has been initialized successfully, the ESP32 server will be continuously waiting for the client connection.

    Fig

    • Once the connection is established between the access point and the client device, the access point will wait for the data input.
    • A string type variable called currentLine has been defined to hold the incoming data from the client.
    • If there is a byte to be read from the client, then it will be stored inside the char type variable

    HTML to display a web page

    • The ESP32 will respond to your browser with HTML (hypertext markup language) code that will be used to construct the web page.
    • HTTP header always starts with a response code e.g.: HTTP/1.1 200 ok
    • An HTML page will be created on the client’s browser, from where the client device can control the position of the servo motor.

    Fig.

    • The next line, which signals that we are transmitting HTML, should always be the first thing we send.
    • Make the web page responsive in any web browser.
     

    Fig.

    • The next task is styling the webpage and the slider.
    • The maximum and minimum angles are 180 and 0 degrees respectively.
    • valueString variable is containing the current angle/position of the slider, fetched from the HTTP request.

    Fig.

    • Close the web connection and clear the header that was used to store the HTTP request header.
    • Print information about the closed web connection on the serial monitor.

    Fig. Close the connection

    Testing

    • Enter the Wi-Fi or network credentials in the code.
    • Compile and upload the code into ESP32 using Arduino IDE.
    • Make sure you have selected the right development board and com port before uploading the code.
    • Open the serial monitor with a 115200 baud rate as defined in the Arduino code.
    • Press the EN button from the ESP32 development board.

    Fig. Serial Monitor

    • Copy the IP address from the serial monitor.
    • Open the web browser.
    • Paste the IP address. A webpage to control the position/angle of servo motor will be displayed, as shown below:

    Fig. Web Page

    This concludes the tutorial. I hope you found this of some help and also to see you soon with a new tutorial on ESP32.

    Capacitance Measurement using Arduino

    Hello geeks, welcome to our new project. In this project, we are going to make a very useful and interesting electronics tool that we as engineers or tinkers need in everyday life. We use the capacitor in most of our projects for various purposes such as filters or power supplies. Most of the time, we do not have a provision to measure the capacitor value in our digital multimeter. So, this time we came up with the solution. Hence, we will make our own capacitance measurement tool using Arduino.

    Rather than investing in new electronic equipment, we will use an Arduino board and some basic components to measure the capacitance. To make this project, we should have some working knowledge about the capacitor. Here, we will not discuss the in-depth working of capacitors, but we will talk briefly so that it would be easy to understand the working principle of our project.

    The capacitor is an electronic component that basically stores the energy when applied to an electric field. It has two parallel terminals connected by two parallel conducting plates separated by a dielectric material. Dielectric materials are electrical insulators(resist to pass the current) that can be polarised by applying an electric field. When we connect a battery with the capacitor then due to potential difference, the electric field is created between two oppositely charged plates of the capacitor and this way the capacitor stores the energy.

    Where To Buy?
    No.ComponentsDistributorLink To Buy
    1CapacitorAmazonBuy Now
    2ResistorAmazonBuy Now
    3LCD 16x2AmazonBuy Now
    4Arduino UnoAmazonBuy Now

    Software to install

    To make this project, we will need some software to install. As we will make our project in the simulation, so for that we will install Proteus simulation software and for coding, we will use the Arduino IDE.

    A brief about Proteus, it is a tool used for simulation and design of electronic circuits. Here we can design different types of electronic circuits and run the simulation. Although Proteus has a very big database for electronic components, still we need to install some libraries which we will use in this project.

    • Arduino UNO - We have to install the library for Arduino UNO.
    • LCD module - We have to install a library for the LCD module.

    You can download this whole project for example Proteus Simulation and Arduino Code, by tapping the below button:

    Capacitance Measurement using Arduino

    Project overview

    In this project, we will use the following components-

    • Arduino UNO - We will use this as the main controller for this project. It will calculate the capacitance of the capacitor.
    • 16x2 LCD Module - We will use this to show the result of measured capacitance and some user-related messages.
    • Resistors and Capacitors - We will be using some resistors to make the RC circuit which is required for measuring the capacitance.

    Now let's talk about the working of this project. The capacitance of any capacitor is the amount of charge that is stored in that capacitor and its unit is Faraday (F). To measure the capacitance, we will use some basic properties of the capacitor.

    So when we connect a power supply with a resistor across the terminals of a capacitor, it will take a certain amount of time to fully charge. And when we connect any discharging resistor as a load across it, then it will take a certain amount of time to fully discharge. And this charging and discharging time will be proportional to the capacitance of the capacitor and the charging resistor in the RC circuit.

    We will use the time constant formula for the calculation of capacitance. The time constant of any capacitor is known as the time taken by the capacitor to charge 63 percent of applied voltage or the time taken by the capacitor to discharge to 33 percent of stored voltage.

    Here,

    T (Tau) = Time constant(Seconds)

    R = Resistance (Ohms)

    C= Capacitance (Farads)

    Using the above principle, we will charge the capacitor using a resistor to reach the charge of the capacitor to 63 percent of applied voltage and we will measure the time taken by the capacitor to reach that point. As we know the resistor’s value and time constant, using these two, we can calculate the capacitance:

    Components required

    • Arduino UNO
    • 16x2 LCD module
    • 10 kOhms Resistor
    • 220 Ohms Resistor
    • An unknown capacitor(Enter range here )

    Components details

    1. Arduino UNO

    • Arduino UNO is an open-source development board that will be used to measure capacitance.
    • It comes with 14 digital I/O pins and 6 analog I/O pins.
    • It has 1 UART, 1 SPI, and 1 I2C hardware which are multiplexed with GPIO pins.
    • Digital pins can be used for input and output for digital data. In this project, we have used digital pins for charging the capacitor.
    • Analog pins have 10 bits of ADC (Analog to Digital convertor) resolution ranging values from 0 - 1023.
    • Analog pins can be used for input and output purposes. In this project, we have used analog pins as input for measuring the discharge and charge voltage.

    Note-Whenever uploading the code on the Arduino UNO, disconnect any wire which is connected to Rx(D0) and Tx(D1) pins, otherwise, it will give an error while uploading the code.

    2. LCD Module

    • LCD stands for Liquid Crystal Display, and its display is made using liquid crystal technology.
    • For more knowledge of how LCD works, prefer this link Working of LCD display.
    • We have used a 16x2 LCD display in this project.
    • The LCD module works in two different data modes: 8-bit or 4-bit mode.
    • We have used 4-bit mode which means we can send 4-bit data in a single cycle to the LCD module.
    • We have used an LCD module to display the user-related information such as capacitance value and the welcome message.

    3. Resistors and Capacitors

    • Resistors, as the name suggests, is an electronic component that controls the flow of current in a circuit.
    • Current flowing in any circuit is inversely proportional to resistance.
    • They are used mostly in every type of electronic circuit for current limiting, voltage divider, and in some noise filters.
    • There are various types of resistors available depending upon the current rating, manufacturing materials, and use case.
    • Although we are making this project in simulation, if you want to make this project using the real components for that we will use the carbon composition through-hole resistors.
    • Capacitors are electronic components that have the ability to store energy.
    • When we connect any battery across the terminals of capacitors then it will start charging.
    • We can store a large amount of charge for a very short period of time in capacitors.

    Circuit diagram and Working

    Now, we have a list of all the required components. Let's start connecting them.

    • Make sure, we have the correct version of Proteus and have installed all the required libraries which we will be using in this project.
    • Now let’s start creating the new project in the Proteus.
    • Import the listed components to the workspace of Proteus.
    • Now we have imported all the components to the workspace.
    • First, connect the charging resistor of 10K ohms with the digital pin 8 of Arduino UNO and then connect the discharging resistor of 220 ohms with the digital pin 9 of the Arduino UNO.
    • We will use the D8 pin for charging the capacitor and the D9 pin for discharging the capacitor.
    • Now connect the capacitor which we want to measure in between these two resistors and connect another terminal of the capacitor with the ground.
    • Connect an analog pin of Arduino UNO with the discharging resistor terminal and that analog pin will be A0 on Arduino UNO.
    • After that, we are finished with our RC circuit.
    • Let’s connect the LCD module with the Arduino UNO, as we are using the LCD module in 4 bits mode so we need to connect only four data pins with Arduino UNO.
    • Connect D4 pin to D7 pins of the LCD module with D2 to D5 pins of the Arduino UNO.
    • While connecting them, keep in mind that they must be connected in the same order.
    • Connect the RS pin with the D6 and Enable pin with the D7 pin of Arduino UNO.
    • Connect the RW pin with the ground which enables the write mode in the LCD module.
    • Connect the 5v power supply with Vdd and Gnd pins of the LCD module.
    • Now we have connected all the components.
    • Before moving to the coding part, reverify your connections once.

    While working on the real components, make sure you have connected the backlight of the LCD module and set the contrast properly otherwise nothing will be visible on the LCD module.

    Arduino code of Capacitance measurement-

    Downloading and including libraries

    • This project will need the library for the LCD module.
    • Before going to write, we must download and include all the required libraries.
    • We can download the library for the LCD module using this link LCD module library.
    • To include the library, go to the Sketch >> Include Library >> Manage Libraries… Using this, we can add libraries directly by searching the window.
    • Or if you have downloaded the library using the link then you will have a zip file for the library. In this case, follow this path: Sketch >> Include Library >> Add .Zip Library
    • After downloading the library, we are all set to start our code.
    • First, include the LCD library header at the start, make an object for the same, and declare all the pins which are used for the LCD module.

    Variable declaration

    • Now we will declare all the variables and pins which we are going to use in this project.
    • Declare the charging pin, discharging pin, and an analog pin for measuring the charging voltage as 8,9 and A0 respectively.
    • Declare variables to store the start time, stop time, and a variable to store the duration.
    • Declare a function “measure()” which will read the analog values.
    • After the declaration, we will define a function “measure()”.
    • We have defined this at the end of the code.
    • This function will read the analog values from the pin and return the values for the same.
    • Here, we have declared and defined the function separately but we can define the function without declaring it, but it is not a good practice to do so and sometimes that will cause errors in the code also.

    Void setup()

    • After declaring all the required variables, we will start writing the “void setup()” function.
    • This is a built-in function in the structure of the Arduino sketch.
    • We can write any code without this function. As per the structure of the Arduino sketch, this function must be in the code.
    • In this function, we will write the pin mode and initialization of other peripherals which will be required in the code.
    • This function will only run once when the code starts.
    • So in this function, we will first begin the LCD module and print the instructions to use.
    • Then set the pin mode of pins and the initial state of the pins.

    Void loop()

    • This is also a built function of Arduino sketch.
    • As per the structure of the Arduino sketch, we can not delete this function from the code even though we don’t have anything to write in this.
    • This function executes after the “void setup()” function.
    • In this function, we will write our main code which we want to run continuously.
    • As the name suggests this will run in a loop.
    • Initially, when there is no capacitor connected then the analog value will be in the maximum range and that is 1010 to 1030.
    • So now, we will display the message that ‘place a capacitor’ and code will be in a while loop until we connect any capacitor to the circuit.
    • Now when we connect any capacitor, the above condition will be unsatisfied, then code will enter in a next infinite while and there we will write the process of charging and discharging of capacitor and time constant.
    • First, we will discharge the whole capacitor, for that we will run a while loop, and using the measure() function, we will measure the currently stored voltage in the capacitor.
    • And when the stored voltage reaches below or equal to the threshold, we will change the pin mode of pins to start charging the capacitor again and store the start time of charging.
    • Using the measure() function, monitor the charging voltage in the capacitor and when the stored charge reaches 63 percent which is 648 of 1023 then we will stop the charging and store the stop charging time also.
    • And display the charging percent on the LCD module.
    • Now calculate the total time taken by the capacitor to reach the 63 percent of charge and that will be the time constant of the capacitor.
    • Using the time constant formula, we can calculate the capacitance of the capacitor as we know the charging resistor connected to the capacitor.
    • As we know the charging resistor value is 10k ohms, using that when we divide the time taken by the resistor value, then we will get the capacitance.
    • And the calculated result will be displayed on the LCD module for 3 seconds, after that code will enter in an infinite while loop.
    • Now we have to reset the device to measure any new capacitor value.
    • Here, our coding part will be completed, it is time to test our code with the circuit and now we will move to the next section.

    Results and Working

    • As we are going to test our project in the Proteus simulation, we have to include the hex file of our code in the Arduino UNO module.
    • The first step is to generate the hex file of the code.
    • Click on the Arduino UNO module in the Proteus then browse to the location of the generated hex file.
    • After adding the code, we are ready to run the simulation and click on the Play button to start the simulation.
    • First of all when the code starts, on the LCD module, we will show the range of capacitance that can be measured using this device and the message to place the capacitor if it is not placed already.
    • When the capacitor is placed, then the discharging process will start to eliminate any pre-stored charge in the capacitor, thus we will get the more accurate value.
    • After 100 percent discharge, the charging process will start and it will go to 63 percent of the stored charge.
    • Thereafter, the code will calculate the capacitance using the time constant formula, and the result will be displayed on the LCD module with the message to reset the device to measure again.
    • After the compilation of the simulation, click on the stop button to stop the running code.

    I hope we have covered all the points related to this project such as circuit diagrams, codes, and working simulation. And I think this will be a very useful project for your daily tinker life. Please let us know if you face any difficulties while making this project in the comment section below.

    We will be happy to hear if you will make this project used in your projects.

    Thanks for reading this article. All the best and see you in the next project.

    Accessing ESP32 Dual Core

    We are familiar with multiple features of the ESP32 module. Like Wi-Fi capabilities, classic Bluetooth, Bluetooth low energy (BLE), inbuilt sensors etc.

    Hello readers, I hope you all are doing great. We have already mentioned in our previous tutorials that, ESP32 is also featured with a Dual-Core Processor. Which provides better performance and efficiency.

    In this tutorial, we will learn how to use ESP32’s dual cores. ESP32 has two (32-bit each) Tensilica Xtensa LX6 microprocessors namely, core0 and core1 which makes it a powerful dual-core microcontroller and hence stands apart from its predecessors.

    When we compile and upload a code using Arduino IDE, we do not have to worry about which core executes the code. It just runs.

    Fig. 1 ESP32 dual-core processor

    Features of Dual-Core processor

    • Power Efficiency: A single-core processor can rapidly hit 100% of its workload. On the other hand, a dual-core processor allows the efficient allocation of resources with a multitasking environment.
    • Increased Performance to Multithread Programs: Aside from being able to run multiple programs at the same time, dual-core processors can also collaborate to make a single program faster and more efficient. Multithreading allows programmers to send different instructions from the same program into two processing paths. On a single processor with hyper-threading, the program is still limited to the single core's maximum processing speed. However, on a dual-core, this effectively doubles the speed available to that program.
    • Two programs running simultaneously: Two cores allow two programs to run at the same time. The many complex calculations that a computer must perform to create the average browsing experience are difficult to quantify; however, single-core processors only create the illusion of multitasking through technologies such as hyper-threading.
    Where To Buy?
    No.ComponentsDistributorLink To Buy
    1ESP32AmazonBuy Now

    FreeRTOS in ESP32

    A FreeRTOS (real-time operating system) firmware is already available in the ESP32 module. FreeRTOS is helpful in improving the system performance and managing the resources of the module. FreeRTOS allows users to handle several tasks like measuring sensor readings, making a network request, controlling motor speed etc. all of them run simultaneously and independently.

    FreeRTOS offers multiple APIs for different applications. Those APIs can be used to create tasks and make them run on different cores. You need to create tasks to assign a particular part of code to a specific core. You can also prioritize that on which core the code will run. Priority value starts with level_0.

    Accessing ESP32’s both cores using Ardui1no IDE

    Whenever we run a code on Arduino IDE, it runs on core_1 by default.

    • How to check on which core the code is running?

    There is a function you can use to check on which core the code is running on.

    xPortGetCoreID()

    Run the following code in Arduino IDE:

    void setup()

    {

    Serial.begin(115200);

    Serial.print( " setup() is running on: Core_" );

    Serial.println( xPortGetCoreID() );

    delay(1000);

    }

    void loop()

    {

    Serial.print( " loop() is running on: Core_" );

    Serial.println( xPortGetCoreID() );

    delay(1000);

    }

    • Open the serial monitor with a 115200 baud rate.
    • Press the EN button from the ESP32 development board.

    Fig. 2 Serial Monitor

    From the results on the serial monitor, you can see that both setup() function and loop() function are running on core_1.

    Steps to be followed to create a task are:

    • Create a task handle to keep a track of the task created. For example, a task handle named task is created below:

    Fig. 3

    • Inside setup() function, create a task assigned to a specific core. xTaskCreatedPinnedToCore() function is used to create a task assigned to a specific core.

    This function takes seven arguments:

    1. Name of the function to implement the task
    2. Name of the task
    3. Stack size assigned to the task in words (where 1 word = 2 Bytes)
    4. Task Input parameter
    5. Priority of the task
    6. Task handler
    7. Core where the task should run

    Fig. 4

    • Create a function that contains the code for the task you have been created.

    For example, we have created a function named task_code(). Inside the task_code() function a for(;;) loop is used which will create an infinite loop. All the instructions to be given for a particular core to perform a particular task like led blinking, sensor readings etc. will be written inside this for(;;) loop.

    Fig. 5

    • How to delete the created task, during the code execution?

    You can use the function vTaskDelete() during the code execution to delete a task. This function takes the task handle (task) as an argument.

    • Code for creating and assigning the separate task to each core

    In this code we will use two LEDs to be processed by different core.

    TaskHandle_t task1;

    TaskHandle_t task2;

    // Assign GPIOs pins to LEDs

    const int led1 = LED_BUILTIN;

    const int led2 = 25;

    void setup() {

    Serial.begin(115200 );

    pinMode( led1, OUTPUT );

    pinMode( led2, OUTPUT );

    //create a task that will be executed in the Task1code() function, with priority 1 and executed on core 0

    xTaskCreatePinnedToCore(task_1code, // Task function.

    "Task1", // name of task.

    10000, // Stack size of task

    NULL, // parameter of the task

    1, // priority of the task

    &task1, // Task handle to keep track of created task

    1); // pin task to core 1

    delay(1000);

    //create a task that will be executed in the Task2code() function, with priority 1 and executed on core 1

    xTaskCreatePinnedToCore(task_2code, //Task function.

    "task2", //name of task.

    10000, //Stack size of task

    NULL, //parameter of the task

    1, //priority of the task

    &task2, //Task handle to keep track of created task

    0); //pin task to core 0

    delay(1000);

    }

    //task_1code: blinks an LED every 1000 ms

    void task_1code( void * pvParameters ){

    Serial.print( "task1 running on: core " );

    Serial.println( xPortGetCoreID() );

    for(;;)

    {

    digitalWrite( led1, HIGH);

    delay(1000);

    digitalWrite(led1, LOW);

    delay(1000);

    }

    }

    //task_2code: blinks an LED every 500 ms

    void task_2code( void * pvParameters )

    {

    Serial.print( "task2 running on: core " );

    Serial.println(xPortGetCoreID() );

    for(;;){

    digitalWrite(led2, HIGH );

    delay(500);

    digitalWrite(led2, LOW );

    delay(500);

    }

    }

    void loop()

    {

    Serial.print( " loop() is running on: Core " );

    Serial.println( xPortGetCoreID() );

    delay(1000);

    }

    Code Description

    • We have created two task handle to keep track of two different tasks created for each core. Task1 is for core_1 and task2 is for core_0.
    • Although we do not need to create a new task and a task handle for core_1 because the void loop() function be default run on core_1 but for better understanding we are creating a different task for each core.

    Fig. 6

    • Allocate GPIOs to the LEDs. Led1 is the inbuilt one that is connected with GPIO2 (internally) and another one is led2 to be connected with GPIO 25.

    Fig. 7

    Setup()

    • Initialize the serial monitor with a 115200 baud rate for debugging purposes.
    • Set the mode of LEDs as OUTPUT.

    Fig. 8 setup() function

    • Create a task (task1) using xTaskCreatePinnedToCore() This task will take seven parameters which include; the task function namely task_1code(), name of the task, stack size of the task, priority level, task handle (if created), core to which you want to assign the task.

    Fig. 9

    • Create a similar task for another core. We will create a different function for this task namely task_2code() and will pass task_2 as a task handle and the core selected is

    Fig. 10

    • The next step is to create functions to execute the above task for each core.
    • task_1code() function is passed as a parameter in
    • xPortGetCoreID() function is used to fetch the core number on which the current function is running on.
    • This function will make the inbuilt LED (GPIO2) or led1 blink with a delay of 1 second or 1000msec.
    • This for(;;) loop will make led1 blink continuously which is similar to the instructions executed inside loop() function.
    • print() function is used to print the results on the serial monitor for debugging purposes.

    Fig. 11

    • task_2code() function is called for task2.
    • This code will be executed in core0.
    • Led2 (GPIO25) will blink continuously with a delay of 0.5sec.

    Fig. 12

    • Inside the loop function we called the xPortGetCoreID() function to get the core number which is responsible to execute the instructions written inside loop() function

    Fig. 13 loop function

    Testing

    Components required:

    • ESP32 development board
    • Breadboard
    • 2*Jumper wires
    • 1*LED
    • 1*resistor(330 ohms)

    Steps for testing:

    • Connect the LED with ESP32 as shown below:

    Fig. 14 connecting LED with ESP32

    • Upload the code into the ESP32 development board.
    • Open the serial monitor with a 115200 baud rate.
    • Press the EN from the ESP32 development board.
    • Results observed from the serial monitor are shown below:

    Fig. 15 Results on the serial monitor

    • On the serial monitor, we can see that task1 functions are processed by core 1 and task2 is processed by core 0.
    • We have already mentioned that core1 is the default processing core so instructions inside the loop() function are processed by core1.

    This concludes the tutorial. We hope you found this helpful and also hope to see you soon with a new tutorial on ESP32.

    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