Automatic Plant Watering System using Arduino

Hello friends, I hope you all are doing great. In today's tutorial, we are going to design a Proteus Simulation for Automatic Plant Watering System using Arduino. We have designed this project for engineering students as it's a common semester project, especially in electrical, electronics and mechatronics engineering.

The two most significant hazards to the agriculture industry are the need for extensive labor and a scarcity of water. According to the World Wildlife Fund (WWF) organization, water shortages might affect two-thirds of the world's population by 2025, putting both the ecosystem and human health at risk. The use of automatic plant watering systems eliminates both of these problems by watering plants at specified times and amounts while monitoring their hydration levels through measuring moisture in the soil surrounding the plants. Automatic plant watering systems can be used in homemade gardens and can also be deployed in fields for large-scale use. Whenever designing an automatic watering system, it is important to keep in mind that the system should be expandable, allowing for the simple integration of new devices in order to broaden the applicability of the system.

Where To Buy?
No.ComponentsDistributorLink To Buy
1BuzzerAmazonBuy Now
2LEDsAmazonBuy Now
3DS1307AmazonBuy Now
4LCD 20x4AmazonBuy Now
5Arduino UnoAmazonBuy Now

Software to Install

We are not designing this project using real components, instead, we are going to design its Proteus simulation. So, first of all, you should Install Proteus Software itself. Proteus software has a big database of electronics components but it doesn't have modules in it. So, we need to install Proteus Libraries of a few components, so that we could simulate them. So, these are the PRoteus libraries which you should install first, before working on this project: You can download this complete project i.e. Proteus Simulation & Arduino Code, by clicking the below button: Download Complete Project Note: You should also have a look at these other Proteus Libraries:

Project Overview:

Three main components of an autonomous watering system are:

  • Water Level Sensor: monitors the water reservoir level.
  • Moisture Sensor: monitors the soil moisture level.
  • RTC module: responsible for supplying water to the plant at predetermined intervals or at a predetermined time.
  • Arduino UNO: serves as a hub for connecting and controlling all these components.

It is necessary to integrate the water level sensor with the microcontroller before it can be installed within the water reservoir. The location of the water level sensor within the reservoir is variable and is determined by the user and the application for which it is being utilized. The Arduino receives continuous data from the water level sensor and warns the user when the water goes below a certain level, either by an alarm or a buzzer, as appropriate.

The soil moisture sensor operates in a manner similar to that of the water level sensor. The tip of the sensor is inserted into the soil near the plant, and the sensor is activated. In the case of a moisture sensor, the closeness of the sensor to the plant is also variable, and the user may adjust it depending on the features of the plant for which it is being used. In vast agricultural fields, a single sensor may be used for numerous plants if they are closely spaced and their hydration levels can be determined by measuring the soil moisture at one location that overlaps with another spot on the soil surface.

The RTC module operates on the same concept of time monitoring in the background as other electronic devices such as computers and smartphones; even when these devices appear to be turned off, they continue to keep track of the current time. The RTC module, on the other hand, is capable of exchanging time information with the Arduino board. On a specific day of the week, at a specific time of day, the Arduino is pre-programmed to turn on the water pump and turn off the water pump after a specified length of time.

Components Needed:

  1. Arduino UNO
  2. Water Level Sensor
  3. Moisture Sensor
  4. RTC Module (DS1307)
  5. LCD
  6. 4 LEDs
  7. Buzzer
  8. Relay
  9. Water Pump
  10. PCF8574

Component Details:

Arduino UNO:

  • Arduino UNO is a programmable microcontroller board.
  • It contains Atmel's ATMega328 as is based on that microcontroller.
  • The Arduino board also contains an in-built voltage regulator to protect it from burning out and supports serial communication to help programmers.
  • The Arduino board is culturally programmed through the Arduino App designed by the board's developers and the programming is done in C language.
  • The Arduino App compiles code and interfaces the firmware into the Arduino hardware.
  • Arduino UNO has 14 digital I/O pins out of which 6 are PWM pins as well.
  • Arduino also takes analog inputs and has 6 analog input pins.

Figure # 1: Arduino UNO

Soil Moisture Sensor:

  • The soil moisture sensor is a resistive sensor that consists of two electrodes with a small charge and the resistance in those electrodes is measured and then the resistance in between the soil is used to find the moisture levels.
  • A soil moisture sensor normally comes equipped with an amplifier such as LM393. It has a VCC, GND and analog output pin.

Figure # 2: Soil Moisture Sensor

Water Level Sensor:

  • The water level sensor is a module that helps calculate the amount of liquid in a container.
  • When a liquid is present in the tank, the Submersible level sensor detects the hydrostatic pressure generated by the liquid.
  • Since hydrostatic pressure is a measure of two variables, the first of which is the density of the fluid and the second of which is the height of the fluid, it is a useful tool.

Figure # 3: Water Level Sensor

RTC Module:

  • RTC stands for real Time Clock and as the name suggests the module keeps track of time even when the external power supply is cut off.
  • It has a battery cell installed within it for that purpose, moreover, it is capable of communication with other devices such as Arduino too.

Figure # 4: RTC Module

Relay:

  • Relays are basically electrical or electromechanical switches that operate on the principle of magnetic field controlling the switching within the relay.
  • A relay has two modes of operation, normally open and normally closed.

Figure # 5: 12V Relay

PCF8574:

  • The PCF8574 is a silicon-based CMOS integrated circuit.
  • Using the two-line bidirectional bus enables general-purpose remote I/O extension for the majority of microcontroller families (I2C).
  • It is used in our project for I2C communication of LCD.

Figure # 6: PCF 8574

 

Proteus Simulation of Plant Watering System

Now, let's design the Proteus Simulation of Plant Watering System first and then will work on the Arduino Code.
  • First of all, make sure that Proteus is installed on your computer and download all the necessary libraries for Proteus beforehand.
  • For this project, you will need libraries for Arduino, LCD, RTC Module, Water Level Sensor and Soil Moisture Sensor. Make sure that you read how to use each library in Proteus as well.
  • Open a new project on Proteus, import all the components required and place them within the working area or the blue line of Proteus.
  • Select below components from Proteus Components' library:

Circuit Diagram and Working:

  • Now, place these components in your Proteus workspace, as shown in the below figure:
  • For the water level and moisture sensor, place a variable POT(potentiometer) at the test pin and place an RC filter at the output pins. (This is only for simulation purposes)
  • Start with the input side of Arduino and connect the soil moisture, water level output pins to the A1 and A0 pins of Arduino respectively.
  • To use the LCD for I2C communication, Place PCF8574 and connect with LCD.
  • Connect the SDA and SCL pins of PCF8574 and the SDA and SCL pins of the RTC module with the SDA and SCL pins of Arduino.
  • For the output side of Arduino, Connect the D7 to the relay controlling the pump.
  • Connect the buzzer at D2 and the LEDs to their respective Arduino pins as well.
  • Make sure appropriate power and ground are provided to each component. With that the making of the circuit on Proteus is complete.

Figure 7 shows the circuit diagram of the system. Proteus was used to simulate the circuit and Arduino App was used for the simulation of the Arduino code. The circuit was designed in a way that is easy to understand and further integrated easily. We will now go through a step-by-step guide on how the circuit was built.

Figure # 7: Proteus Circuit diagram

Arduino Code for Plant Watering System

A normal Arduino code has two main segments:

  • void setup
  • void loop
We will look at both of them separately here.

Declaration Code

  • The first step in setting up our code is defining libraries, download if you don’t have any libraries already integrated in the Arduino App.

Figure # 12: Arduino Code

  • The next step in the code is tone definition for buzzer and pin definition of variables being used in the project.

Figure # 13: Arduino Code

  • After pin definition, the variables used must be defined so that Arduino knows where to find them and how to identify them.

Figure # 14: Arduino Code

  • The next step is defining the system messages that will appear on the LCD.
  • It is not necessary to define those messages in the setup, they can be easily defined within the main code but it is an easier way to define those beforehand and call them whenever needed.
  • This is especially useful when a system message is used multiple times in the code.

Figure # 15: Arduino Code

  • Now we define the objects being used in the project.
  • The two objects being defined are the RTC module and LCD. In the syntax below we used 20x0 in the argument for the LCD, that is because there are no libraries for I2C LCDs and we had to turn a simple LCD into an I2C LCD by the means of PCF8574.

Figure # 16: Arduino Code

Void setup:

Now we start the programming of void setup.
  • At first is the initialization of various components, such as initializing the RTC module and setting the time and date of RTC with respect to our computer.
  • Wire initialization and library are used for I2C communication.

Figure # 17: Arduino Code

  • The next step is defining the digital pins of Arduino being used as input or output pins and displaying the initial message on our LCD.

Figure # 18: Arduino Code

 

Void Loop:

  • The first step in the loop is to read the date and time from the computer through the RTC and read the values from the sensor.
  • Since this part of the program runs in the loop, Arduino will keep reading and refreshing the sensor inputs every time the loop starts.

Figure # 19: Arduino Code

  • In the next segment of the code, we will check various conditions of the sensor values and RTC and actuate our outputs on the basis of these conditions.
  • At first, we check the water level of the container, if it is below the set level, Arduino will actuate the buzzer to alarm the user of low tank on LCD.

Figure # 20: Arduino Code

  • In the next step, we check the values of the moisture sensor and place the conditions in three categories, namely, moist soil, soggy soil and dry soil.
  • The Arduino will light up the respective LED whenever its condition is true. Red LED for dry soil, yellow LED for soggy soil and green LED for moist soil.
  • The LCD will also display respective messages for each of those conditions.
  • The following code is for the condition of dry soil.

Figure # 21: Arduino Code

  • The following code is for the condition of moist soil.

Figure # 22: Arduino Code

  • And finally the code for the condition of soggy soil.

Figure # 23: Arduino Code

  • In the next step of the code, we check the condition of time, whether it is time to water the plants or not and the condition of the water reservoir to see its level as well.

Figure # 24: Arduino Code

If you see the code closely, you may see the function of the right hour, which is called various times in the main code. The function code in itself is written at the bottom of the main code. This function is used for displaying the time and date on the LCD and also for fixing the date and time.

Results/Working

  1. Open Arduino and generate a hex file for that program.
  2. Put the hex file in the Arduino UNO board placed in Proteus.
  3. Run the simulation.

Figure # 8: Proteus circuit simulation when soil is soggy

Figure # 9: Proteus circuit simulation when soil is moist

Figure # 10: Proteus circuit simulation when soil is dry

Figure # 11: Proteus circuit simulation when soil is dry and it is time to water the plant

As you can see from figure 8 that our simulation is running according to the program set at Arduino. You can increase or decrease the values coming from the sensors through the Potentiometer. So, that was all for today. I hope you have enjoyed today's lecture. If you have any questions, please ask in the comments. Thanks for reading.

ESP32 Programming Series: Install ESP32 in Arduino IDE

Hello everyone, I hope you're all doing well. In the previous lecture(Chapter 0: ESP32 Pinout), we discussed the ESP32 features & specs in detail. Today, we are officially starting this ESP32 Programming Series. In this ESP32 Programming Series, we will start with basic concepts and will gradually move towards complex topics. I will try to keep this ESP32 series as simple as I can. But still, if you encounter any issues, please ask in the comments, will try to resolve the issues as soon as possible.

As ESP32 has numerous features & applications, so I have divided this series into different sections. I have named the 1st section "ESP32 IDEs". In this section, we will discuss different IDEs used to program ESP32 boards. In each Chapter of this section, we will install one of these ESP32 IDEs and will test a simple LED Blinking Code in it. We will set up the ESP32 Development Environment for Windows, Mac, and Linux users.

As I am sharing the 1st Chapter today, so first we will unbox the ESP32 board, set up the most commonly used ESP32 IDE i.e. Arduino IDE, and test a simple WiFi Scan Code on the ESP32.

Here's a video lecture for better understanding:

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

ESP32 IDEs

IDE is an abbreviation of Integrated Development Environment. IDE is a software package used to write & compile the code. As ESP32 is one of the most popular microcontroller boards, there are numerous third-party IDEs available to program it, and each IDE supports its own programming language. So, if you are a C# developer or an Arduino expert, you can quickly and easily get your hands dirty with ESP32. The below table shows the most commonly used ESP32 IDEs along with their supported programming language:

ESP32 IDEs
No.
ESP32 IDEs
Programming Language
1
Arduino IDE
Arduino C
2
Thonny IDE
MicroPython
3
Visual Studio Code
Arduino C
4
PlatformIO IDE
C++
5
ESP-IDF(official IDE by EspressIF)
C
6
nanoFramework
C#

In today's lecture, we will install the Arduino IDE and configure it for ESP32 Programming. So, let's get started:

Install ESP32 in Arduino IDE

First of all, we need to install the Arduino IDE itself. To program ESP32 with Arduino IDE, we need to install the ESP32 Boards in Arduino IDE. Before installing the ESP32 Boards, we first need to add a JSON File containing information about ESP32 Boards. JSON format is used to share information between two computers. So, this JSON file will add the information of ESP32 boards in the Arduino IDE. So, let me summarize these 3 steps in proper order:

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

Installing Arduino IDE

We need to first download & install the Arduino IDE.

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

Adding ESP32 JSON File in Arduino IDE

Steps to install ESP32 JSON File in Arduino IDE:

  • In the Arduino Preferences Window, you will find a textbox named "Additional boards Manager URL".
  • Add the ESP32 JSON File link(provided above) in it, as shown in the below figure:

  • If you have already added any third-party board URLs, then add a comma (,) between the JSON links OR click on the button and it will open up a new window, add URL in the new row, as shown below:

  • Click "OK" to close the Preference Window.
  • Once you close the Preference Window, Arduino IDE will extract the information of all ESP32 boards by downloading the ESP32 JSON file.

Now, we are ready to install the ESP32 Boards in Arduino IDE:

Installing ESP32 Boards in Arduino IDE

  • In the Arduino IDE, click on "Tools > Board > Board Manager", as shown in the below figure:

  • It will open up a Board Manager Window in Arduino IDE.
  • From this Board Manager, we can install the packages for third-party modules.
  • In the Board Manager, make a search for "ESP32" and you will get many third-party ESP32 packages.
  • Here, we need to install the "ESP32 by Espressif Systems" as it's the official package, I have highlighted it in the below image:

  • So, click on the Install button to install ESP32 boards in Arduino IDE.
  • Arduino IDE will take some time to install the ESP32 package.

  • Once installed, click on "Tools > Boards > esp32" and you will find a list of newly added ESP32 boards, as shown in the below figure:

  • From this list, we will select "ESP32 DEV KIT V1", it's the most commonly used ESP32 board.

  • In the COM Port, select the available COM Port, in our case, it's COM5:

In some cases, the Arduino IDE won't automatically detect the ESP32 COM Port, so here we need to install the COM Port driver for ESP32. Let's do it:

Installing ESP32 COM Port in Arduino IDE

If you don't find the ESP32 COM Port in the Port Section of Arduino IDE, then you need to install the COM Port Driver manually. So, follow the below steps:

  • Download the Windows COM Port Driver by clicking the below button and install it on your computer:

CP210x_Windows_Drivers

  • If you are using 32-bit Windows, then install the x86 version and if working on 64-bit Windows, then install the x64 version.

After installing this COM Port Driver, restart your Arduino IDE and it's recommended to restart your computer as well.

So, we have successfully installed the ESP32 Boards in the Arduino IDE. Now, let's upload a simple LED Blinking Code in the ESP32:

Code Upload to ESP32 from Arduino IDE

Now that the Arduino IDE is ready to handle the ESP32 Dev Kit module, you can write the code for the ESP32 module. We will just upload a simple WiFi Scan Code to verify that our ESP32 installation is correct.

  • Open Arduino IDE and navigate to "File > Examples > WiFi > WiFiScan".

  • Click on the Tools and verify that you have selected the correct ESP32 board and the COM Port.
  • Now, click the "Upload " button to upload the code to the ESP32 board.
  • If the code is uploaded successfully in the ESP32 board, you will get the confirmation message in the Output pane, as shown in the below figure:

Now open the Serial Terminal and you will start receiving the List of all available WiFi connections, as shown in the below figure:

That concludes today's discussion. We hope you found this post informative. In the next tutorial, we will install the ESP32 Boards in the Visual Studio Code. If you have any questions, please ask in the comments. Take care. Have a good day.

Smart Home Security System using Arduino

Security systems are widely suggested for homes as well as other locations. Everybody wants to take necessary steps to prevent infiltration at home, thus this security is necessary. Intruders nowadays may take advantage of almost any illegal activity and wreak havoc on a property's security. The security of one's home is a critical concern that everyone faces in the current day.

While there are certain devices on the market that may considerably help protect your house, some of them are excessively costly and need constant maintenance. Many devices regarding smart home security systems are available in the market but these are not user friendly according to the budget, the device we designed provides the user with a better interface with the help of LCD. We have used enough sensors that make sure the security protocol.

So in this way, we designed a reasonable security system that has the features of gas and flame detection with the help of MQ-2 Gas Sensor and flame sensor respectively and also have installed a Motion detector sensor known as PIR sensor to detect the intruder's motion. For a better user interface an LCD and Alarm are installed to alert the user. The whole system is programmed using Arduino UNO. A proteus circuit is designed for this project as shown below:

  • You can download the complete project i.e. Proteus Simulation and Arduino Code by clicking the below button:
Smart Home Security System using Arduino
Where To Buy?
No.ComponentsDistributorLink To Buy
1LCD 20x4AmazonBuy Now
2SIM900AmazonBuy Now
3Flame SensorsAmazonBuy Now
4MQ-2AmazonBuy Now
5PIR SensorAmazonBuy Now
6Arduino UnoAmazonBuy Now

Components Required

For the home security system, we have used 3 sensors which are briefly explained as follows:

Flame Sensor

  • The flame sensor is used to detect the fire, it has 3 pins (Ground, VCC, OUTPUT) with operational voltages ranging from 3.3V to 5V.
  • This sensor may be constructed using an electrical circuit and a receiver similar to that used for electromagnetic radiation.
  • This sensor employs the infrared flame flash technology, which enables it to operate through a layer of oil, dust, water vapor etc.
  • There are several wavelengths of flame sensors normally in the range of 700 to 1100 nm from the source.
  • Normally flame sensors have an operating temperature ranging from -25? ~ 85? with several features like adjustable sensitivity, fast response time and ease to use.
  • Proteus doesn't have a Flame Sensor in its database, so you need to download this Flame Sensor Library for Proteus.

PIR Sensor

  • PIR Sensor is used to detect the intruder’s motion.
  • There are mainly two kinds of infrared sensors one is active and the other is passive.
  • The active infrared sensor emits as well as absorbs the infrared radiations whereas the passive infrared sensor simply absorbs not emit.
  • When an object enters or escapes the sensor's range, a passive infrared sensor is employed to detect it.
  • For adjusting the sensitivity and delay time, there are two trim pots supplied. You may alter them to meet your requirements.
  • The sensor produces a HIGH output when it senses movement within its range; otherwise, it generates a LOW output.
  • PIR also has 3 pins like a Flame sensor.
  • It has operating voltages of range 5V - 20V with output voltage generation of 0V-3V when the object is detected in the sensing range that is 7 meters.
  • Proteus doesn't have a PIR Sensor in its database, so you need to download this PIR Sensor Library for Proteus.

MQ-2 Gas Sensor

  • MQ2 gas sensors detect the presence of gases such as LPG, methane, ethanol and carbon monoxide in the air ranging up to 10000 ppm using electricity.
  • It is also known as chemiresistor for the MQ2 gas sensor.
  • The resistance of the sensing material changes depending on the amount of gas present.
  • When it comes to detecting gas, sensors use variations in resistance value that generates the output voltage.
  • When a sensor material is heated to a high temperature in the air, oxygen is adsorbed on the surface.
  • Because current can flow via the sensor, its analog voltage values may now be read.
  • The voltage values reported here may be used to compute the concentration of a gas. When the gas concentration is high, the voltage values are greater.
  • Proteus doesn't have a Gass Sensor in its database, so you need to download this Gas Sensor Library for Proteus.
 

Arduino UNO

  • Atmel's ATMega328 is used in the Arduino Uno, an open-source single-board microcontroller.
  • Either an external power source or a 5V USB connection may be used to power the device.
  • In all, there are 14 digital input/output pins on the board, with 6 of them serving as PWM outputs.
  • On the board, you'll find a reset button and six analog input pins. The Arduino software is used to program the board, which is written in C language.
  • When it came to controlling the home security system, the Arduino Uno's capabilities were found to be sufficient.
  • Arduino Boards are not present in Proteus, so we need to use this Arduino Library for Proteus.

Circuit Designing

  • This whole project is designed to provide a security system for the home in which multiple safety sensors can be installed with a Buzzer and LCD for a better user interface.
  • We won't design this project in real, instead, we are going to design its Proteus simulation.
  • If you are working on an electronics/embedded project, then it's always a best practice to design its simulation first.
  • In simulations, it's easy to debug your code and thus you can program quickly.
  • Once you are satisfied with your project's working, you can move forward to hardware designing.

So, let's design our Proteus Simulation for Smart Home Security System:

Proteus Simulation

  • These are the components, which we are going to use for designing our Proteus Simulation:
  • So, select these components from Proteus Components Library and place them in your workspace, as shown in the below figure:
  • Next, we need to connect these components' pins to complete our circuit, as shown in the below figure:
  • As you can see in the above simulation, we have used three sensors in total, which we have discussed above.

So, now we are going to design the Arduino Code for this simulation:

Arduino Programming Code

We have designed the circuit in our Proteus Simulation and next, we need to design its Arduino Code, in order to make it work.

LCD Initialization Code

  • First of all, we are going to interface LCD with Arduino UNO and will display the Project's name on the screen.
  • The code is shown in the below figure:
  • As you can see in the above figure, we have first initialized the variables.
  • Arduino board is programmed using Arduino IDE software which has mainly 2 sections void setup and void loop.
  • Before void setup, we have to declare the pins of sensors and actuators that we are using in our project.
  • Depending on the nature of sensors (analog or digital) the pins of sensors are connected to Arduino UNO accordingly.
  • #define is used to declare the pins of Gas, PIR, FIRE and BUZZER.
  • Initially, all the sensors have zero value that is stored by an integer variable.
  • In the void setup section, input and output sensors are defined.
  • GAS, PIR, and FIRE sensors are employed as input sensors to detect and activate the BUZZER, which is an output component.
  • LCD 20×4 is used and lcd.begin is used to initiate the LCD.
  • lcd.setCursor is used to cursor position on LCD and the name of the project is displayed on LCD Screen using lcd.print command.
  • Now, let's run our simulation to check the results, shown in the figure below:

Sensors Interfacing with Arduino

  • In Arduino IDE code execution, void setup runs once while the void loop executes again and again.
  • analogRead and digitalRead commands are used to read the value of analog and digital sensors respectively, while analogWrite and digitalWrite commands are used for sending commands or data.
  • As shown in the above figure, first, we have read the sensors' data and if all sensors are in LOW state, then have displayed the message "You are safe".
  • Let's run the code to check the output:
  • As you can see in the above figure, all sensors are at a LOW state and thus LCD is displaying the safe message.
  • Next, we have added the if loop for the case where all sensors are giving HIGH value:
  • The rest of the code has similar if loops for various conditions of sensors.
  • You can download the complete code and Proteus Simulation from the link, given at the start of this tutorial.
  • Now, let's run our final simulation and test the sensors and if everything goes fine, you will get results as shown in the below figure:

Future Recommendations

It deters the crime and notifies the user about the gas or fire problem. Home security systems are mostly utilized for safety reasons in residences, businesses, and educational facilities. Another option is to use a mobile device or the internet to send data to a remote location. Other modules, such as a wind sensor or a fire sensor, might be added to the system in the future. Voice alarm modules may also alert you to an intruder or a gas leak if you use them. We can increase the number of sensors to make it better. We can use the latest technology of the Internet of Things that makes our system wireless. A growing number of devices and goods are being connected to the Internet, which is referred to as the Internet of Things by the phrase. We can use the Internet of Things to produce a low-cost security system for residential and industrial applications that is especially useful for home security. When the door is opened or an unauthorized entry is detected, the system will send an alert to the owner. The user may take action after getting the notification. ESP8266 Wi-Fi module will connect to and interact with the Internet, while an Arduino Uno microcontroller keeps track of the system's status, as well as a magnetic Reed sensor for sounding the alarm. The principal advantages of this system are ease of installation, low costs, and low maintenance requirements.

So, that was all for today. I hope you have enjoyed today's project. If you have any questions, ask in the comments. Thanks for reading. Take care !!! :)

Smart Irrigation System using Arduino UNO

Hello everyone, we are back with a new project and we hope you all are doing well. In this article, we will discuss a project named Smart Irrigation System using Arduino UNO. We will use different sensors to measure the environmental and crop parameters which are responsible for good production. We will also make the water pump system automatic which will open the water valve automatically according to the soil moisture of the crop.

We will discuss all points and concepts briefly in this article and also provide a Proteus Simulation to observe how it will work in the real world. Complete fully explained code and simulation are also provided below as you go ahead in this article. You can download it from there.

Smart Irrigation System using Arduino UNO

Let’s start with an Introduction:

Where To Buy?
No.ComponentsDistributorLink To Buy
1LCD 20x4AmazonBuy Now
2LDR SensorAmazonBuy Now
3MQ-135AmazonBuy Now
4Arduino UnoAmazonBuy Now

Introduction 

In the late decades, there has been a quick advancement in Smart Agricultural Systems. Show that agriculture has great importance worldwide. Indeed, in India for example, about 70 % of the people rely upon the vital sector of agriculture. In the past, irrigation systems used to be dependent on the mills to irrigate the farm by conventional methods without knowing the appropriate quantities of these crops.

These old systems are a major cause of the waste of large quantities of water and thus destroy some crops because of the lack of adequate quantities of water. However, with the recent technological developments, there have been innovative systems for irrigation without the farmer interfering in the irrigation process. We will discuss it in brief below.

We will do a simulation on Proteus 8 Professional Software.

Working

The working of this project is like, we will use a Soil Moisture sensor for measuring the moisture of Soil according to which water valves are controlled. When the moisture level gets below a threshold value, valves will open with the help of a relay or solenoid till the soil is well moisturized.

  • The BMP180 sensor will measure the Atmospheric Pressure.
  • The DHT11 sensor will measure the temperature and humidity of the climate.
  • The MQ135 sensor will measure the Air Quality Index of the environment.
  • LDR will measure the sunlight intensity.
  • We will use a 20x4 LCD Screen for displaying the data gathered from the sensors.
  • And the main thing, we will use an Arduino UNO microcontroller as the brain of the project.

In a used case, when the moisture level gets below a threshold value, valves will open with the help of a relay or solenoid for a required time interval.

Block Diagram

  • Here's the Block Diagram of Smart Irrigation System:

Components Required

Here's the list of components used in this project:
  • Arduino UNO
  • BMP180 Sensor
  • DHT11 Sensor
  • LDR Sensor
  • MQ135 Gas Sensor
  • Soil Moisture Sensor
  • 20x4 LCD Display
  • PCF8574 remote 8-bit I/O expander for the I2C bus
  • Breadboard.
  • Jumper wires (Male to Male, Male to Female, Female to Male.)

Since we are designing a prototype of this project, we will use jumper wires instead of soldering.

  • Power Supply

You can use a Battery, Adapter or any DC source of 5-8v(recommendable).

Circuit Diagram

Since we are making a prototype of this project, we will make connections on the breadboard and avoid soldering the components. We will use male to male, male to female and female to female jumper wires. 

Pins Connections

These are the pin connections of all components.
Pin Connections of Smart Irrigation System
No. Sensor Pinout
1 Soil Moisture Sensor Data - A0 (Arduino)
2 LDR Sensor LDR-Resistor Junction - A2 (Arduino)
3 MQ135 Gas Sensor Out - A1 (Arduino)
4 DHT11 Sensor Data - D2 (Arduino)
5 BMP180 Pressure Sensor SDA-SDA (Arduino) SCL - SCL (Arduino)
 

Arduino Libraries Required

You need to install these third-party Arduino Libraries, in order to interface sensors:

  1. Adafruit_BMP085.h
  2. DHT.h
  3. LiquidCrystal_I2C.h

We have added comments in the code for better understanding so it can be understood easily.

Note - Change the Address of the LCD Screen while you run the code in Proteus, change it to 0x20 instead of 0x27 or anyone else. In the real experiment, we can alter the address of the LCD by changing the configurations of A0, A1 and A2 pins of the PCF8574 module.

Proteus Libraries Required

We will show you a demo of this project as a simulation. We are using Proteus 8 Professional Software for the simulation.

Proteus Simulation Connections

  • This potentiometer defines the soil water content in the proteus simulation.
  • When the resistance is maximum at the test pin, the circuit shows zero volts across the voltmeter, which means the sensor is either in the dry ground or taken out of the ground, i.e. giving zero moisture value of the water content.
  • And when resistance is zero, the circuit will show the maximum voltage across the voltmeter which indicates the sensor is inserted in a wet ground i.e. water contents in the soil are too high.
  • This is important. We have attached the output pin with an LC filter. This filter is not required in real hardware implementation.
  • We are using it in Proteus Simulation only as Proteus gives the peak-to-peak value and we have to convert that PP value into Vrms.
  • If you are working on a real sensor then you don’t need to add this LC circuit.
  • Similarly for Gas sensor, as we increase the potentiometer, in simulation it means good air quality.

Steps for Simulation

These are the steps for simulation. Follow them to create a fully working simulation.
  • Download the Zip Files given at the start of this tutorial.
  • Extract them in the LIBRARY folder. You will find it inside the Labcenter Electronics Folder.
  • Go to Arduino IDE and open the code, go to Tools and select the board Arduino UNO.
  • Go to Sketch and Click on Export Compiled Binary. It will create a compiled .hex file of the code which will be used as the main program in the simulation ahead.
  • Open Proteus software and add components by searching like Arduino, DHT11, BMP180, 20x4 LCD, etc.
You can see the components listed here.

Note - We used a simple LED instead of the valve because the valve component is not available in the Software, simply replace the LED with a valve in a real project. Make connections according to the circuit diagram and add virtual terminals to Serial pins to see the readings and Data.

  • Paste the Program File here for all the sensors.
  • Paste the Compiled Binary File as a Program file of Arduino UNO.
  • Run the simulation and you can see the readings by opening the virtual terminal.

Observations and Results

 
  1. In this simulation and project, you can see the sensor's information first in the terminal.
  2. After that, we are getting well organized and easily understood data on the terminal by every sensor according to code.
  3. According to the code, when the value of the soil moisture sensor gets less than a threshold value, the LED gets on.

This means when the soil gets dry the valve will open and water will be provided to the crops.

pH Sensor Library for Proteus

Hi guys, I hope you are good and doing well in your life. In this article, I am going to tell you about a new pH Sensor Library for Proteus. I hope you all will enjoy it and find it useful. We are all well aware of pH Sensors which are used for the detection of pH of different fluids. By knowing the pH of a liquid we can tell whether the liquid is acidic or basic. You can’t find a pH sensor in Proteus software, so we designed a pH sensor for simulation purposes. You can interface this pH Sensor with any Microcontroller, for example: Arduino, PIC Microcontroller, 8051 Microcontroller etc.

In this pH Sensor Library, I have added four different pH Sensors, which are used for the detection of the pH of any fluid. Since we can’t place real liquid and measure pH in this software, I have attached a test pin in the pH meter where you have to connect a potentiometer. The potentiometer will produce a reading from 0 to 1023, which will be mapped from 0 to 14 in the program code. We can predict the nature of the liquid. We will have a look at how to use these sensors below. So, here’s the list of all four pH sensors, I have added to this pH sensor  library:

  • PH METER
  • PH METER 2
  • PH METER 3
  • PH METER 4

So, let’s start with downloading and installing the pH Sensor Library for Proteus.

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

What is a pH Sensor?

  • A pH sensor is a device that is used to measure the pH value of a liquid. pH can be defined as the concentration of H+ ions in a liquid. We can find whether the fluid is acidic, basic or neutral by knowing the pH of the liquid.
  • Real pH sensors are shown below:

pH sensor Library for Proteus

  • First, download the zip file of Proteus Library for pH Sensor.
  • Click the link below to download the library zip file of pH Meter:
pH Sensor Library for Proteus
  • After downloading the zip file, extract its files and open the folder named “Proteus Library Files“.
  • In this folder, you will find three files, named:
    • pHMeterLibraryTEP.IDX
    • pHMeterLibraryTEP.LIB
    • pHMeterLibraryTEP.HEX
  • We have to place these files in the ‘LIBRARY’ folder of Proteus software.
  • Now, open Proteus. if you are already working on it you have to restart it.
  • In the components search box, search for “PH METER” and you will get four results, as shown in the below figure:
  • Let’s place these four pH Meter models in our Proteus workspace:

Adding Hex File to the Sensor

  • Now we need to paste the hex file of the pH METER in the properties section of the sensor. Double click on the sensor to open the properties window.
  • Go to the program file section, browse to the hex file, which we have downloaded above and placed it in the ‘LIBRARY’ folder of Proteus software:
  • After adding the hex file, click the Ok button.
  • Now all is ready, let’s create a circuit to check it's working.

pH Sensor Proteus Simulation

  • The pH sensor is now ready to simulate in Proteus, so let’s design a simple circuit to understand its working:
  • As you can see, I have placed an LC filter on the analog output of the pH sensor, it's because proteus gives us a peak to peak voltage value and we need to convert it to Vrms.
  • While performing the real experiment, you don’t need to do the above stuff.
  • Now, let’s run the Proteus simulation. You will see such a screen if everything will work fine.

Interfacing of pH sensor with Arduino UNO

  • Add Arduino UNO  and pH sensor to the components list and place them in the workspace.
  • Placed an LC filter on the analog output of the pH sensor, as mentioned above.
  • Connect it to the A0 pin of Arduino. Add a virtual terminal also to see the readings generated.
  • Paste the hex file of the program at the program file section of the Arduino.
  • Now run the simulation, if everything's fine you will get results as shown in the below figure:
  • You can watch the complete working simulation in the below video:

So, that was all for today. I hope you have enjoyed today's lecture. Thanks for reading !!!

WiFi Temperature Monitor with ESP8266 and DS18B20

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

The project will be built as follows:

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

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

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

Materials

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

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

DS18B20

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

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

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

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

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

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

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

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

OneWire

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

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

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

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

Circuit

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

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

Finding the DS18B20 address

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

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

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

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

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

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

 

Sensor reading by Serial Monitor

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

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

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

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

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

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

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

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

Creating the monitoring page

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

We will build the following screen:

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

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

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

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

Complete Code

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

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

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

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

For the server, we have three routes:

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

Conclusion

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

ESP8266 – Serial Communication

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

Applications

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

1. Communicating with computers

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

2. Communicating with microcontrollers

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

3. Communicating with industrial machines

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

Main Functions

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

Serial.begin()

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

Serial.available()

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

Serial.read()

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

Serail.readString()

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

Serial.print() and Serial.println()

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

Serial Monitor

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

Controlling and monitoring an LED

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

ESP8266 – Knowing the NodeMCU GPIOs or Pinout

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

Introduction

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

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

Overview and Electrical Data

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

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

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

Power Source

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

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

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

The pins involved in the power are:

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

Some important considerations to keep in mind:

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

Serial – USB Adapter

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

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

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

Digital Pins (GPIO)

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

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

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

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

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

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

Analog Pinout

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

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

Main functions for GPIO in the Arduino IDE

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

pinMode(pin, mode)

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

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

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

pinMode(4, OUTPUT)

digitalWrite(pin, value)

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

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

digitalWrite(4, HIGH);

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

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

digitalRead(pin)

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

value = digitalRead(4)

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

analogRead(pin)

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

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

value = digitalRead(A0)

Constants

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

Differences in other modules

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

ESP8266 Operational WiFi Modes

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

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

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

ESP8266 Operational Modes

The ESP8266 WiFi module can operate in 2 different modes:

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

STA Mode

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

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

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

begin() function

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

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

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

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

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

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

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

Config() function

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

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

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

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

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

Access Point Mode (AP)

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

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

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

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

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

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

softAP() function

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

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

Let's take one for each parameter:

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

softAPConfig() Function

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

Where the parameters represent:

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

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

STA + AP Mode

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

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

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

Create Webserver with ESP8266 using SPIFFS

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

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

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

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

What is SPIFFS?

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

Create Webserver with ESP8266 using SPIFFS

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

Our page will have 3 main objects:

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

Files on Webserver

And to build this page we will use 4 files:

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

Understanding ESP8266 Webserver Code

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

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

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

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

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

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

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

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

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

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

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

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

Results

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

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

Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir