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.

    Sending Sensor Readings to Google Sheet Through IFTTT using ESP32

    Hello readers, I hope you all are doing great. In our previous tutorial, we learnt how to make HTTP POST from ESP32 to the IFTTT server.

    In this tutorial, we will learn about another application of the ESP32 module in the field of IoT (Internet of Things). We can publish multiple sensor readings from ESP32 to Google sheets via the IFTTT web service.

    IFTTT is used as a third-party web service to integrate Google sheets with ESP32.

    Fig. 1

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

    Creating an IFTTT Account for Integrating ESP32 with Google Sheets

    We are going to create an applet (on the IFTTT server) that is responsible to integrate the Webhooks and Google Sheets services.

    While operating with the IFTTT server there are some services/utilities that we are going to deal with like Applets and Webhooks. Before getting started with the project, let’s first introduce you to those terms:

    Applet

    An Applet is a small application or a utility program, which is used for one or a few simple functions. It connects two or more devices or apps together. An applet provides integration between two devices or services to enable some functionality that those devices or services cannot do alone or on their own. An applet consists of actions and triggers.

    Fig. 2

    Webhooks

    • Webhooks are hypertext transfer protocol (HTTP) callbacks that are defined by the user. They are data and executable commands sent from one app to another over HTTP rather than through the computer's command line. Essentially, it is a method for apps to send automated messages or information to other apps.
    • When an event occurs on the "trigger" application, the app serializes the data and sends it to a webhook URL from the "action" application (the app that processes the data from the "trigger" application). After that, the active application can send a callback message.

    Getting Started with IFTTT:

    1. Enter the following link in the web browser: https://ifttt.com
    2. Login with your Gmail or Facebook accounts for free.
    3. Click on Create icon (top left menu) to create an

    Fig. 3: Creating an Applet

    1. Click on the ”if This” icon.

    Fig. 4: “If This”

    1. Select a service. Search for the Webhooks service and select the respective icon.

    Fig. 5: Search and Select Webhooks

    1. Click on the Receive a web request option to select a trigger option. The trigger will fire every time the maker service receives a web request to notify it of an event.

    Fig. 6: Receive a Web Request

    1. Assign a name to the trigger event and click on Create trigger We have assigned ESP32_GoogleSheets.

    Fig. 7: Create Trigger

    1. Next, click on the “Then That”

    Fig. 8:  Then That

    1. To select the service, search for the Google Sheets service and click on the respective icon.

    Fig. 9:  Google Sheets

     
    1. The next step is selecting an action, click on Add row to the spreadsheet

    Fig. 10: Select an Action

    1. Click on the connect button to connect with the Google Sheet service, if you haven’t connected to it yet.

    Fig. 11: Connect to Google Sheets Service

    1. A new window will pop up, where you need to log in with your Gmail account.
    2. Enter your Gmail account address and password.
    3. Click on Allow icon, (as shown below) to allow the IFTTT web service to access files from your Google drive. So that IFTTT can create new folders or update details in the existing Google drive folders with new sensor readings.

    Fig. 12: Allow IFTTT Service to Access Files of your Google Drive

    1. Finally, complete the action field by assigning the name to the spreadsheet and path the folder in Google drive. Leave the Formatted row as it is (default).
    2. A folder named IFTTT will be created by default if you leave the above fields empty.

    Fig. 13: Complete Action Fields

    1. Click on the finish

    Fig. 14: Applet Successfully Created

    Testing the Applet

    Before interfacing the IFTTT service (applet) with ESP32, let us test the applet whether it is created successfully or not.

    1. Open the following link: https://ifttt.com/maker_webhooks
    2. Click on the Documentation

    Fig. 15

    • A new window will open containing your key (API).
    • Enter the details in To trigger an Event and click on Test it.

    Fig. 16: Test your Applet

    • Open your Google drive.
    • You should see a folder (named IFTTT ) in your Google drive.
    • Open the folder to see the values received from the IFTTT server.

    Fig. 17:  IFTTT Folder in Google Drive

     

    Components Required:

    • ESP32 development board.
    • USB cable to connect to ESP32 development board with the computer.

    No external components are required as we are using the ESP32’s inbuilt sensors to take the readings.

     

    Arduino IDE code

    Let’s have an overview of the project before writing the Arduino code:

    • To access the internet, the ESP connects to the local Wi-Fi network.
    • Then, the Hall sensor will take the readings;
    • Your ESP32 will communicate with the IFTTT Webhooks service that publishes the readings to a spreadsheet on Google Sheets that is saved in your Google Drive’s folder.
    • After publishing the readings, the ESP goes into deep sleep mode for 15 minutes;
    • After 15 minutes the ESP wakes up;
    • After waking up, the ESP connects to Wi-Fi, and the process repeats.
    • We are using Arduino IDE to compile and upload into the ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial i.e., on ESP32 programming series.

    #include <WiFi.h>

    // Replace with your SSID and Password

    const char* ssid = "SSID";

    const char* password = "Password";

    // Replace with your unique IFTTT URL resource

    const char* serverName = "https://maker.ifttt.com/trigger/replace_this_with_eventName/with/key/replace_this_with_your_unique_key ";

    // Maker Webhooks IFTTT

    const char* server="maker.ifttt.com";

    //----Timer for sleep

    uint64_t uS_TO_S_FACTOR = 1000000; // Conversion factor for micro seconds to seconds

    uint64_t TIME_TO_SLEEP = 900; //sleep for 15 minutes

     

    void setup()

    {

    Serial.begin(115200);

    delay(100);

    Serial.print("Connecting to: ");

    Serial.print(ssid);

    WiFi.begin(ssid, password);

    int timeout = 10 * 4; // 10 seconds

    while( WiFi.status() != WL_CONNECTED && ( timeout-- > 0) )

    {

    delay(200);

    Serial.print(".");

    }

    Serial.println(" ");

    if(WiFi.status() != WL_CONNECTED )

    {

    Serial.println(" Failed to connect, going back to sleep ");

    }

    Serial.print("WiFi connected in: ");

    Serial.print(millis());

    Serial.print(", IP address: ");

    Serial.println(WiFi.localIP());

    makeIFTTTRequest();

    // enable timer deep sleep

    esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);

    Serial.println("Going to sleep now");

    esp_deep_sleep_start(); // start deep sleep for 900 seconds (15 minutes)

    }

     

    void loop()

    {

    // sleeping so wont get here

    }

    void makeIFTTTRequest()

    {

    Serial.print("Connecting to ");

    Serial.print(server);

    WiFiClient client;

    int retries = 5;

    while(!!!client.connect(server, 80) && (retries-- > 0))

    {

    Serial.print(".");

    }

    Serial.println();

    if(!!!client.connected())

    {

    Serial.println(" Failed to connect... ");

    }

    Serial.print(" Request server: ");

    Serial.println( serverName );

    // Hall sensor values

    String jsonObject = String("{\"value1\":\"") +

    hallRead() +

    "\",\"value2\":\"" + hallRead()

    + "\",\"value3\":\"" +

    hallRead() + "\"}";

    client.println(String("POST ") + serverName + " HTTP/1.1");

    client.println(String("Host: ") + server);

    client.println("Connection: close\r\nContent-Type: application/json");

    client.print("Content-Length: ");

    client.println(jsonObject.length());

    client.println();

    client.println(jsonObject);

    int timeout = 5 * 10; // 5 seconds

    while(!!!client.available() && (timeout-- > 0)){

    delay(100);

    }

    if(!!!client.available()) {

    Serial.println("No response...");

    }

    while(client.available()){

    Serial.write(client.read());

    }

    Serial.println("\nclosing connection");

    client.stop();

    }

    Code Description

    • Add the required header files.
    • WiFi.h header file is used to enable the Wi-Fi module and its respective functions.

    Fig. 18:  Library Files

    • Enter the network credentials, SSID and Password.

    Fig. 19:  Network Credentials

    • Add the IFTT domain name, the event name (you have created) and the API key. The event name we have created is ESP32_test.

    Fig. 20

    • IFTTT Server URL.

    Fig. 21

    • Time_To_Sleep variable is used to set a timer (sleep time) of 15 minutes (900 sec). ESP32 processor will wake up from sleep mode after every 15 minutes to take the sensor readings and publish them to Google Sheets.
    • uS_To_S_Factor is used to store the conversion value for converting the timer unit from microseconds to seconds.

    Note: The ESP32 sleep time should not be very short. A very short sleep time can result in the exceeded limit of requests imposed by the IFTTT service.

    Fig. 22: Timer

     

    Setup()

      • Initialize the Serial monitor with a 115200 baud rate for debugging purposes.

    Fig. 23:  Serial Monitor

    • Enable ESP32’s Wi-Fi module using begin() function which is using SSID and password as arguments.
    • Wait until the ESP32 is not connected to the Wi-Fi network.
    • Fetch the IP address using WiFi.localIP() function.

    Fig. 24:  Wi-Fi

    • makeIFTTTRequest() function is used to connect ESP32 with the client server.

    Fig. 25

    • esp_sleep_enable_timer_wakeup() function is used to enable the timer for sleep mode.
    • The duration of sleep mode is passed as an argument inside the timer function.
    • Esp_deep_sleep_start() function is used to start the sleep mode.

    Fig. 26

    • The below code represents the process happening inside the makeIFTTTRequest()

    Fig. 27

    • ESP32 connects to IFTTT serve and then communicates with the server (IFTTT) through port 80.
    • ESP32 tries 5 times to connect to the server and if it couldn’t then it will enter the sleep mode.

    Fig. 28

    • jsonObject variable is used to store the sensor data to be shared to the Google Sheets via the IFTTT server.
    • We are using ESP32’s inbuilt Hall sensor to take the readings.
    • This variable will take three sensor values and ESP32 will communicate the readings to Google Sheets.

    Fig. 29

    • Connection with the server will be closed once the data is shared successfully and ESP32 will enter to sleep mode form next 15 minutes.

    Fig. 30

    Testing

    • Select the right development board in Tools >> Boards >> DOIT ESP32 DevKit V1 in Arduino IDE.
    • Compile and upload the code into ESP32 using Arduino IDE.
    • Make sure that you have entered the right Wi-Fi credentials, API key and event name 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.
    • Go to your Google drive.
    • You should see a folder (named IFTTT ) in your Google drive.
    • Another folder will be there inside the IFTTT folder (named as ESP32_hall sensor readings, in our case)
    • Open the folder to see the values received from the IFTTT server.
    • The spreadsheet will be updated after every 15 minutes. If you press the EN button before completing the sleep duration(15 minutes), the spreadsheet will be updated automatically with new sensor data, as shown below:

    Fig. 31: Hall Sensor Readings on Google Sheets

    Fig. 32: Serial Monitor

    This concludes the tutorial. I hope you found this of some help and also to see you soon with the 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