Sending Email with ESP32 using SMTP Protocol

Hello readers, I hope you all are doing great. In this tutorial, we will learn how to send an email using ESP32 module. We will also learn to send text files, images or some sensor readings using the SMTP server using the ESP32 module.

In IoT (Internet of things), there are various applications where we need to send emails carrying information like sending some sensor readings, altering emails, images, text files and much more.

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

What is SMTP?

SMTP or simple mail transfer protocol is an internet standard for sending and receiving electronic mail (or email) where an SMTP server receives emails from the email client.

SMTP is also used for setting communication between servers.

Various email providers like Gmail, Hotmail, Yahoo, etc. have unique SMTP addresses and port numbers.

How does SMTP work?

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

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

When a client wants to send emails, a TCP connection will be open for the SMTP server and emails will be sent across the connection.

SMTP commands:

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

SMTP parameters for different email providers

SMTP parameters for Gmail

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

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

SMTP parameters for Yahoo

  • SMTP server: smtp.mail.yahoo.com
  • SMTP Port: 465 (with SSL)
  • Another Port number: 587 (with TLS)
  • SMTP sender’s address: email address
  • SMTP sender’s password: password

SMTP parameters for Hotmail

  • SMTP server: smtp-mail.outlook.com
  • SMTP port: 587
  • SMTP sender’s address: Hotmail email address
  • SMTP sender’s password: Hotmail password
  • SMTP TLS/SSL required : YES

SMTP parameters for Outlook

  • SMTP server: smtp-mail.office.com
  • SMTP server port for incoming mail: 993
  • SMTP server port for outgoing mail: 587
  • SMTP sender’s address: Outlook email address
  • SMTP sender’s password: Outlook password
  • SMTP TLS/SSL required : YES

Sending emails over SMTP using ESP32 in Arduino IDE

  • In this tutorial, we will demonstrate sending raw text messages and HTML messages, images, text files, etc. to the client over the SMTP server.

Components required to send and receive emails using ESP32 over SMTP server are:

  • Recipient’s email address.
  • Sender’s email address.
  • Content to be shared over SMTP server.
  • ESP mail client library.
  • ESP32 module.

ESP mail client Library

To send emails with ESP32 we need to install this ESP Mail Client library. This library, make ESP32 able to send emails over an SMTP server.

Step to install ESP Mail Client Library:

  • To download the ESP Mail Client Library click on the link given below: https://github.com/mobizt/ESP-Mail-Client
  • Open the Arduino IDE.
  • Go to Sketch >> Include Library >> Add .ZIP Library.
  • Select the downloaded ZIP file. Click on

Your Arduino IDE is ready to send email using ESP32.

Create a new Gmail account (Sender)

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

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

In this tutorial, we are using a Gmail account.

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

 

Access to Less Secure apps

To get access to this new Gmail account, you need to enable Allow less secure apps and this will make you able to send emails. The link is: https://myaccount.google.com/lesssecureapps?pli=1

Arduino IDE Code, for sharing raw text and HTML text with ESP32 and SMTP server:
  • As we mentioned earlier, we are using Arduino IDE as a compiler and upload into the ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial Introduction to ESP32 Programming Series.
  • We have already discussed installing the ESP Mail Client Library to make ESP32 able to send emails over the SMTP server.
  • This library includes multiple examples on SMTP like sending text messages, images, HTML code, text files etc. We have attached an image below for your reference.
  • You can use those examples to send emails.

Fig SMTP example code

  • Note: You can not use the exact code. Hence, you need to make some changes like replacing SSID and password with your network credentials, email address of sender and receiver, SMTP setting parameters for respective email service providers etc, which need to be done before uploading the code. We will also describe these things during code description.

#include <WiFi.h>

#include <ESP_Mail_Client.h>

#define WIFI_SSID "SSID"

#define WIFI_PASSWORD "PASSWORD"

#define SMTP_HOST "smtp.gmail.com"

#define SMTP_PORT 465

/* The sign in credentials */

#define AUTHOR_EMAIL "email address"

#define AUTHOR_PASSWORD "email password"

/* Recipient's email*/

#define RECIPIENT_EMAIL "email address_Rx"

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

SMTPSession smtp;

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

void smtpCallback(SMTP_Status status);

void setup(){ Serial.begin(115200);

Serial.println();

Serial.print("Connecting to AP");

WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

while (WiFi.status() != WL_CONNECTED){

Serial.print(".");

delay(200);

}

Serial.println("");

Serial.println("WiFi connected.");

Serial.println("IP address: ");

Serial.println(WiFi.localIP());

Serial.println();

/** Enable the debug via Serial port

none debug or 0 basic debug or 1

*/

smtp.debug(1);

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

smtp.callback(smtpCallback);

/* Declare the session config data */

ESP_Mail_Session session;

/* Set the session config */

session.server.host_name = SMTP_HOST; session.server.port = SMTP_PORT; session.login.email = AUTHOR_EMAIL; session.login.password = AUTHOR_PASSWORD;

session.login.user_domain = "";

/* Declare the message class */

SMTP_Message message; message.sender.name = "ESP32"; message.sender.email = AUTHOR_EMAIL; message.subject = "ESP32 Test Email";

message.addRecipient("Sara", RECIPIENT_EMAIL);

/*Send HTML message*/

String htmlMsg = "<div style=\"color:#2f4468;\"><h1>Hello CLient!</h1><p>- Sent from ESP board</p></div>"; message.html.content = htmlMsg.c_str(); message.html.content = htmlMsg.c_str(); message.text.charSet = "us-ascii";

message.html.transfer_encoding = Content_Transfer_Encoding::enc_7bit;

//Send raw text message

/* String textMsg = "Hello Client! - you have a message from ESP32 board"; message.text.content = textMsg.c_str(); message.text.charSet = "us-ascii";

message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;*/

message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;

message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;

/* Set the custom message header */

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

/* Connect to server with the session config */ if (!smtp.connect(&session))

return;

/* Start sending Email and close the session */ if (!MailClient.sendMail(&smtp, &message))

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

}

void loop(){

}

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

void smtpCallback(SMTP_Status status){

/* Print the current status */

Serial.println(status.info());

/* Print the sending result */ if (status.success()){

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

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

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

Serial.println("----------------\n"); struct tm dt;

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

/* Get the result item */

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

time_t ts = (time_t)result.timestamp; localtime_r(&ts, &dt);

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

ESP_MAIL_PRINTF("Status: %s\n", result.completed ? "success" : "failed"); ESP_MAIL_PRINTF("Date/Time: %d/%d/%d %d:%d:%d\n", dt.tm_year + 1900,

dt.tm_mon + 1, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec); ESP_MAIL_PRINTF("Recipient: %s\n", result.recipients); ESP_MAIL_PRINTF("Subject: %s\n", result.subject);

}

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

}

}

Code Description

  • The first task is adding the required header files or libraries.
  • Wifi.h is used to enable the Wi-Fi module and hence wireless network connectivity.
  • Another library is ESP_Mail_Client.h to enable email service over SMTP (simple mail transfer protocol).
  • Enter the network credentials in place of SSID and PASSWORD.
  • Insert SMTP parameter of the respective email service provider.
  • The parameters used below are for Gmail.
  • Enter the sender’s email address and password details.
  • Insert recipient’s email address.
  • SMTPSession object is used for sending emails.
  • This smtpCallback() function is used to get the email sending status.
  • This function also includes printing the results like success and failure of email sent.

Setup()

  • Initialize the serial monitor at a 115200 baud rate for debugging purposes.
  • WiFi.begin() function is used to initialize the Wi-Fi module with Wi-Fi credentials used as arguments.
  • The While loop will continuously run until the ESP32 is connected to the Wi-Fi network.

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

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

  • Next step is setting the message header.
  • Message header will be set inside the setup() function which includes, sender’s name, subject, sender’s email address, receiver’s email address and name.

Sending raw text message

Write the message content (raw text) in the textMsg variable which you want to share over email.

Sending HTML text

To send HTML text write the respective content in the htmlMsg variable.

  • Connect to server with session configuration using smtp.connect() function.
  • Next thing to do is, send an email to the client for that MailClient.sendMail() function is used and if mail transmission is failed then that will be printed on the serial monitor along with the reason.
  • Loop() function will remain empty.

Testing

  • Upload the Arduino IDE code in the ESP32 module.
  • Make sure the Wi-Fi network is ON to which your ESP32’s Wi-Fi module is supposed to connect.
  • Open Serial monitor with 115200 baud rate.
  • Also, make sure that you have turned ON the permission for less secure apps.

Otherwise, you won’t be able to send emails and an error will be printed on the serial monitor.

  • Press the EN button from the ESP32 development board.

  • Check receiver email inbox.

Arduino IDE code, for sending images and text files using ESP32 and SMTP server:

In this example code, we will demonstrate how to share text files and images through emails using ESP32 over the SMTP server.

But, before sharing attachments (text files or images) you need to save those files on the ESP32 filesystem (SPIFFS).

Uploading files to ESP32 Filesystem (SPIFFS)

SPIFFS stands for Serial Peripheral Interface Flash File System, which is built into the ESP32 module. This is a lightweight filesystem designed for microcontrollers with flash chips connected via SPI bus, such as the ESP32 flash memory. In this flash memory, we can write, delete, read, and close files.

  • Text files and images will be saved on ESP32 filesystem (SPIFFS) using ESP32 filesystem uploader plugin for Arduino IDE.

Installing Arduino ESP32 Filesystem Uploader:

Fig.

  • Restart the Arduino IDE.

Check if the plugin is successfully uploaded or not:

  • Open Arduino IDE. Select ESP32 development board.
  • Go to
  • Check whether this ESP32 Sketch Data Upload option is available or not. If it is available that means plugin is uploaded successfully and it is ready to upload files.

Fig.

Finally, uploading files using SPIFFS or filesystem upload:

  • In Arduino IDE, create a new Arduino sketch.
  • Save the project.
  • Go to Sketch >> Show Sketch Folder. As shown in the image below:

Fig.

  • Create a new folder named as

Fig.

  • Inside that data folder add the respective text files or images you want to share over email as shown in the image below:

Fig.

  • If you are using the example code from ESP mail-client library then the images should be named as png and text files as text_file.text.
  • After saving files inside data folder, open the Arduino IDE then go to Tools >> ESP32 Sketch Data Upload to upload the SPIFFS Image.

Fig.

A message “SPIFFS Image Uploaded” will be displayed at the bottom of Arduino IDE, once the SPIFFS image is uploaded successfully.

Fig.

Arduino IDE Code

Code is already available in ESP Mail Client Library. As shown below:

Fig.

  • You can not use the exact code.
  • Some changes like Wi-Fi credentials, email address of sender and receiver, SMTP setting parameters for respective email service providers etc, need to be done before uploading the code.

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

// The file systems for flash and sd memory can be changed in ESP_Mail_FS.h.

#include <Arduino.h>

#include <WiFi.h>

#include <ESP_Mail_Client.h>

#define WIFI_SSID "SSID"

#define WIFI_PASSWORD "PASSWORD"

// server address for Gmail account

#define SMTP_HOST "smtp.gmail.com"

/** The smtp port e.g.

25 or esp_mail_smtp_port_25 465 or esp_mail_smtp_port_465 587 or esp_mail_smtp_port_587

*/

#define SMTP_PORT 465

/* The log in credentials */

#define AUTHOR_EMAIL "Sender's email address"

#define AUTHOR_PASSWORD "password"

/* Recipient's email*/

#define RECIPIENT_EMAIL "receiver's email address"

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

SMTPSession smtp;

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

void smtpCallback(SMTP_Status status);

void setup(){

Serial.begin(115200);

Serial.println();

Serial.print("Connecting to AP");

WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

while (WiFi.status() != WL_CONNECTED){

Serial.print(".");

delay(200);

}

Serial.println("");

Serial.println("WiFi connected.");

Serial.println("IP address: ");

Serial.println(WiFi.localIP());

Serial.println();

if (!SPIFFS.begin(true)) {

Serial.println("An error has occurred while mounting SPIFFS");

}

else{

Serial.println("SPIFFS mounted successfully");

}

/** Enable the debug via Serial port

  • none debug or 0
  • basic debug or 1

*/

smtp.debug(1);

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

smtp.callback(smtpCallback);

/* Declare the session config data */

ESP_Mail_Session session;

/* Set the session config */ session.server.host_name = SMTP_HOST; session.server.port = SMTP_PORT; session.login.email = AUTHOR_EMAIL; session.login.password = AUTHOR_PASSWORD;

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

/* Declare the message class */

SMTP_Message message;

/* Enable the chunked data transfer with pipelining for large message if server supported

*/

message.enable.chunking = true;

/* Set the message headers */ message.sender.name = "ESP Mail";

message.sender.email = AUTHOR_EMAIL;

message.subject = "Test sending Email with attachments and inline images from SD card and Flash";

message.addRecipient("Sara", RECIPIENT_EMAIL);

/** Two alternative content versions are sending in this example e.g. plain text and html */

String htmlMsg = "This message contains attachments: image and text file."; message.html.content = htmlMsg.c_str(); message.html.charSet = "utf-8";

message.html.transfer_encoding = Content_Transfer_Encoding::enc_qp;

message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_normal; message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;

/* The attachment data item */

SMTP_Attachment att;

/** Set the attachment info e.g.

  • file name, MIME type, file path, file storage type,
  • transfer encoding and content encoding

*/

att.descr.filename = "image.png"; att.descr.mime = "image/png"; //binary data

att.file.path = "/image.png";

att.file.storage_type = esp_mail_file_storage_type_flash;

att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;

/* Add attachment to the message */

message.addAttachment(att);

message.resetAttachItem(att);

att.descr.filename = "text_file.txt"; att.descr.mime = "text/plain"; att.file.path = "/text_file.txt";

att.file.storage_type = esp_mail_file_storage_type_flash;

att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;

/* Add attachment to the message */

message.addAttachment(att);

/* Connect to server with the session config */ if (!smtp.connect(&session))

return;

/* Start sending the Email and close the session */ if (!MailClient.sendMail(&smtp, &message, true))

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

}

void loop()

{

}

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

void smtpCallback(SMTP_Status status){

/* Print the current status */

Serial.println(status.info());

/* Print the sending result */ if (status.success()){

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

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

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

Serial.println("----------------\n"); struct tm dt;

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

/* Get the result item */

SMTP_Result result = smtp.sendingResult.getItem(i); time_t ts = (time_t)result.timestamp;

localtime_r(&ts, &dt);

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

ESP_MAIL_PRINTF("Status: %s\n", result.completed ? "success" : "failed"); ESP_MAIL_PRINTF("Date/Time: %d/%d/%d %d:%d:%d\n", dt.tm_year + 1900,

dt.tm_mon + 1, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec);

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

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

}

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

}

}

Code Description:

Most part of the code is similar to the previous one (that is sending raw text and HTML text), including libraries, network credentials, enabling Wi-Fi and the serial monitor, setting the email parameters of the respective email service provided. So we not explaining the complete code but, we will explain the programming part which is different than the previous one.

Setup()

  • We are initializing the SPIFFS, inside the setup() function to sore files which are to be shared over the SMTP server.
  • begin() function is used to for initializing SPIFFS.

Fig.

  • If the server supports, enable chunked data transfer with pipelining for large messages.

Fig.

  • Next, you need to create data attachments.

Fig.

  • The next thing is sending the image, for that you need to add the attachment details: filename, path, mime type, type of storage, encoding technique.
 

Fig.

  • After adding the details of the image, add the attachment to the message.

Fig.

  • To send a text file you also need to add similar details: name of the file, path, storage type, mime type and encoding technique.

Fig.

  • Add this attachment too to the message.

Testing

  • Upload the code into the ESP32 board.
  • Make sure you have selected the correct ESP32 development board and COM port.
  • Also, make sure that you have turned on the access for less secure apps for the sender’s email account as discussed earlier. Otherwise, the ESP32 will face an authentication error.
  • Turn ON the Wi-Fi with which your device is supposed to connect with.
  • Once the device is connected with the access point, it will automatically send the attachment to the receiver's email account.

Fig.

Fig.

Fig. Email Received

This concludes the tutorial; I hope you found this helpful and also hope to see you again with a new tutorial on ESP32.

ESP32 Capacitive Touch Sensor in Arduino IDE

Hello readers, I hope you are all doing great. Welcome to the 2nd lecture of Section 5(ESP32 Sensors) in the ESP32 Programming Series. In the previous tutorial, we discussed the built-in ESP32 Hall Effect Sensor. In this tutorial, we will discuss another inbuilt sensor of the ESP32 i.e. Capacitive Touch Sensor.

ESP32 Board has 10 built-in capacitive touch pins, which generate an electrical signal when someone touches these pins. These ESP32 touch pins are normally used to wake up the board from deep sleep mode. These touch pins are also used to replace the normal mechanical buttons with touch pads, improving the presentation of the IoT projects.

Here's the video demonstration of the ESP32 Capacitive Touch Sensor:

Before going forward, let's first understand how this touch sensor works:

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

What is a Capacitive Touch Sensor?

Capacitance is determined by the geometry of the conductors and the dielectric materials used. Changing any of these factors will result in changing the capacitance.

C = Ad

As we know, the human body also carries a small electric charge. So, when a body approaches the metallic plates(of a capacitor), the mutual capacitance between the two metal plates decreases. This change in capacitance is used to detect the touch in these capacitive sensors.

Capacitive touch sensor in ESP32

  • ESP32 offers 10 Capacitive-sensitive GPIO pins, operating at a normally HIGH state.
  • So, at open state, these pins provide +5V at the output but when someone touches any of these pins, the respective pin voltage drops to 0.
  • These ESP32 Capacitive Touch Sensor Pins are labeled in the below figure:(for detailed pinout, please read ESP32 Pinout)

So, if someone touches any of these pins, ESP32 can easily detect it. The pin mapping of touch-sensitive pins in DOIT ESP32 DevKit V1 with GPIO pins is shown below:

ESP32 Capacitive Touch Pins
No. Parameter Name Parameter Value
1
Touch0 GPIO4
2
Touch1 GPIO0(not available in DOIT ESP32 Dev-kit V1 30-pin module but available in the 36-pin module)
3
Touch2 GPIO2
4
Touch3 GPIO15
5
Touch4 GPIO13
6
Touch5 GPIO12
7
Touch6 GPIO14
8
Touch7 GPIO27
9
Touch8 GPIO33
10
Touch9 GPIO32

Programming ESP32 Capacitive Sensor

We are using the Arduino IDE development environment for programming ESP32. If you are new to Arduino IDE, read out How to Install ESP32 in Arduino IDE. Let's use the builtin Touch Sensor example in Arduino IDE:

  • Open the Arduino IDE, go to File > Examples > ESP32 > Touch. An image from Arduino IDE is attached below for your reference:

In Arduino IDE there are two example codes available for the ESP32 touch sensor. We will discuss and implement both example codes in this tutorial. So, let's first open the TouchRead Code:

ESP32 TouchRead Example

Here's the code for the TouchRead Example:

// ESP32 Touch Test
void setup()
{
    Serial.begin(115200);
    delay(1000); // give me time to bring up serial monitor
    Serial.println("ESP32 Touch Test");
}

void loop()
{
    Serial.println(touchRead(T0)); // get value using T0
    delay(1000);
}

Code Description

  • This is a basic code to test/understand the touch sensor feature of ESP32.
  • In this code, we are using a touch-sensitive pin to read the variation in capacitance and print the respective readings on the serial monitor.

Setup() Function

Inside the setup() function, the serial monitor is initialized at a baud rate of 115200 to display the sensor readings. Finally, we printed the message(ESP32 Touch Test) on the Serial Monitor:

void setup()
{
    Serial.begin(115200);
    delay(1000); // give me time to bring up serial monitor
    Serial.println("ESP32 Touch Test");
}

Loop() Function

  • Inside the loop function, the touchRead(T0) function takes the T0 capacitive sensor pin as an argument and reads the output of T0(GPIO Pin4).
  • The observed output is continuously printed on the serial monitor with a delay of 1 sec.
void loop()
{
    Serial.println(touchRead(T0)); // get value using T0
    delay(1000);
}

Testing/Result

  • Upload the above code into the ESP32 development board and connect a jumper wire to the T0 capacitive sensor pin(GPIO4).
  • To open the serial monitor in Arduino IDE, go to Tools > Serial monitor or use the Ctrl+Shift+M shortcut key.
  • Select the 115200 baud rate on the serial monitor.
  • Now hold the metal end of the jumper wire connected to the GPIO4.
  • To check the results, open the serial plotter, go to Toole > Serial Plotter or use Ctrl+Shift+L shortcut keys.
  • As you can see in the above figure, the sensor's value drops to 0 when we touch the metallic part of the capacitive sensor pin.
  • When we are not touching the sensor pin, the normal sensor output is around 107.
  • Here's the Serial Monitor showing the touch results:

ESP32 Touch Interrupt Example

These capacitive touch sensor pins are mainly used to generate an external interrupt for waking up ESP32 from low power modes(deep sleep mode). Moreover, can also be used to control external peripherals like LED blinking or tuning on a DC motor, when a capacitive touch-interrupt is observed. So, let's have a look at How to Generate external interrupt by touching the ESP32 capacitive touch pins:

ESP32 Touch Interrupt Code

Here's the ESP32 Touch Interrupt Code:

const int CAPACITIVE_TOUCH_INPUT_PIN = T0; // GPIO pin 4
const int LED_OUTPUT_PIN = LED_BUILTIN;
const int TOUCH_THRESHOLD = 40; // turn on light if touchRead value < this threshold
volatile boolean _touchDetected = false;

void setup()
{
    Serial.begin(115200);
    pinMode(LED_OUTPUT_PIN, OUTPUT);
    pinMode(LED_OUTPUT_PIN, LOW);
    touchAttachInterrupt(CAPACITIVE_TOUCH_INPUT_PIN, touchDetected, TOUCH_THRESHOLD);
}

void touchDetected()
{
    _touchDetected = true;
}

void loop()
{
    if(_touchDetected)
    {
        Serial.println("Touch detected.");
        _touchDetected = false;

        Serial.println("blink the LED");
        digitalWrite(LED_OUTPUT_PIN, HIGH);
        delay(1000);
        digitalWrite(LED_OUTPUT_PIN, LOW);
        delay(1000);
    }
}

Let's understand the code by parts:

Variables Initialization

  • The first step is to select the GPIO or touch sensor input pin to trigger an interrupt. We are using T0 or GPIO4 as an interrupt pin.
  • Select the LED output pin which will react or blink on the occurrence of an interrupt.
  • In the code, we are using the threshold value of 40. When a body, containing an electric charge touches a touch-sensitive pin, the threshold value decreases below 40.
  • The default state of the touchDetect variable is set to false.
const int CAPACITIVE_TOUCH_INPUT_PIN = T0; // GPIO pin 4
const int LED_OUTPUT_PIN = LED_BUILTIN;
const int TOUCH_THRESHOLD = 40; // turn on light if touchRead value < this threshold
volatile boolean _touchDetected = false;

Setup() Function

  • In the Setup Function, we initialized the serial monitor with a baud rate of 115200 so that you can display the results on the serial monitor for debugging purposes.
  • Set the LED pin as output and set the default state to LOW.
  • Attach the interrupt with the capacitive touch pin T0 using touchAttachInterrupt(), it takes the T0 pin, touchDetected and threshold value as arguments.
void setup()
{
    Serial.begin(115200);
    pinMode(LED_OUTPUT_PIN, OUTPUT);
    pinMode(LED_OUTPUT_PIN, LOW);
    touchAttachInterrupt(CAPACITIVE_TOUCH_INPUT_PIN, touchDetected, TOUCH_THRESHOLD);
}
  • touchDetected() function will be called when an interrupt is triggered i.e. someone touches the T0 Pin.
  • This Function will change the state of the "_touchDetected" variable to true.
void touchDetected()
{
    _touchDetected = true;
}

Loop() Function

  • Inside the loop() function, we are using the ‘if’ statement which is continuously checking the state of variable "_touchDetected".
  • Once the variable state is changed to true, an interrupt is triggered and the output LED (inbuilt LED) will start blinking with a delay of 1 second.
  • The result will be printed on the serial monitor.
void loop()
{
    if(_touchDetected)
    {
        Serial.println("Touch detected.");
        _touchDetected = false;

        Serial.println("blink the LED");
        digitalWrite(LED_OUTPUT_PIN, HIGH);
        delay(1000);
        digitalWrite(LED_OUTPUT_PIN, LOW);
        delay(1000);
    }
}

Testing of ESP32 Touch Sensitive Pin

  • Open the serial monitor with a 115200 baud rate.
  • Connect a male-to-female jumper wire with T0 or GPIO 4 of ESP32.
  • Hold the metallic end of the jumper wire.
  • LED will blink with a delay of 1 sec.
  • See the results displayed on the serial monitor.

This concludes the tutorial; I hope you found this helpful and also hope to see you again with a new tutorial on ESP32.

Simple Arduino Calculator

Hello geeks, I hope you all are doing well and looking forward to making something new yet interesting. So, today we have come up with our new project which is a calculator using Arduino.

We all use calculators in our daily life, whether you are working in an office or counting money at the bank, you are buying your daily grocery or doing shopping online, you will find calculators in different forms everywhere. In fact, the computer was initially considered a giant calculator. So if it is that common, why do we not make our own calculator?

Before going into the details of the project, it is good to know some history of that, let’s know some facts about the calculator. So the first known device for calculation is Abacus. And the first digital calculator was made by Texas Instruments in 1967 before that all calculators were mostly mechanical and they did not need any electronic circuits. The first all-transistor calculator was made by IBM and it is claimed that the calculator performed all the four basic operations such as addition, subtraction, multiplication, and division.

Where To Buy?
No.ComponentsDistributorLink To Buy
1Keypad 4x4AmazonBuy Now
2LCD 16x2AmazonBuy Now
3Arduino Mega 2560AmazonBuy Now

Software to Install :

In this, we will be going to use the Proteus simulation tool and we will make our whole project using this software only. But no need to worry while using the actual components because if our project works perfectly with simulation, it will definitely work with actual hardware implementation. And the best part of the simulation is, here we will not damage any components by making any inappropriate connections.

If you don’t have an idea about Proteus, Proteus is a software for the simulation of electronic circuits and here we can use different types of microcontrollers and run our applications on them.

So for this project, we need to install this software. This software has a big database for all electronics components but still, it lacks some, therefore we have to install some libraries for modules which we are going to use in this project.

Project overview :

In this project, we will take input from the user using a keypad and perform the operation using Arduino UNO and display the result on an LCD display.

  • Arduino UNO - It is used for performing calculation-related operations, other user-related operations like interfacing with keypad module and LCD module.
  • 16x4 LCD module- It is used to display user-related messages such as input digits and selected arithmetical operations and calculated results.
  • 4x4 Keypad- It is used for user input. From this module, the user can enter the numerical values and arithmetic operations.

Our project will work the same as a normal digital calculator such that the user will enter two numerical values and select arithmetic operations which she/he wants to perform on the given values. Once the user clicks on the equal button, thereafter Arduino UNO will calculate the output and display the result on the LCD module.

Components required :

  1. Arduino UNO
  2. 16x2 LCD module
  3. 4x4 Keypad module

Components details:

  1. Arduino UNO

  • Arduino UNO is an open-source development board that we have used in this project.
  • It works on the ATMega328P microcontroller developed by Atmel.
  • It has an 8-bit RISC based processing core and up to 32 KB of flash memory
  • It has 14 digital input/output pins from D0 - D13 with a resolution of 8 bits, these pins can be used for taking any digital input or can be used as output pins for controlling peripherals.
  • In the 14 digital pins, there are 6 PWM pins.
  • It is suggested that you do not use the D0 and D1 pins of Arduino UNO for digital read or write purposes because they have an extra functionality of UART communication.
  • Arduino UNO has 6 analog input/output pins from A0-A5, which can be used to read analog values.
  • Analog pins have 10 bits of ADC (Analog to Digital convertor) resolution ranging values from 0 - 1023.
  • Arduino UNO has one hardware UART peripheral (D0, D1), one I2C peripheral, and one SPI peripheral.
  • We can use the power supply from 7 to 12 volts to power the Arduino UNO, but it is suggested to use a voltage supply of less than or equal to 9 volts but not below 5 volts.
  • We will use the Arduino IDE for writing and uploading the code on Arduino UNO. It is an open-source software developed by Arduino.
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.
  1. LCD Module

  • LCD stands for Liquid Crystal Display, and this display is made using liquid crystal technology.
  • For more knowledge of how LCD works, prefer this link Working of LCD display.
  • In this project, we have a 16x2 LCD display which means we can display a max of 32 ASCII characters on this at a time.
  • The LCD module has 16 pins but we will not use all the pins in this project.
  • The LCD module can be used in two different modes, the first is 4-bit mode and the second is 8-bit mode.
  • We will use the 4-bit mode in this project, therefore, we have to connect only 4 data pins of the LCD module.
  • The major difference between 8-bit mode and 4-bit mode is, an ASCII character is 8 bit long so when we use 8-bit mode, LCD will process the data in single instruction but in 4- bit mode, microcontroller will send 2 chunks of 4 bits and the LCD will process that in two instructions.
  • To read more about the difference between 8-bit mode and 4-bit mode refer to this link Different modes of the LCD module
  • There are two registers in the LCD module: The Data register and the Command register.
  • When the RS(Register Select) pin is set to logic high, the data register mode is selected, and when it is set to logic low, the command register mode is selected.
  • The RS pin will be set to logic high to display the data on the LCD.
  • The operating power supply will be 5 volts for the LCD module.
  1. 4x4 Keypad

  • It is a membrane-based push keypad.
  • We have used a 4x4 keyboard which means it has 4 rows and 4 columns.
  • It has 0-9 numbers and basic arithmetic operations like addition, subtraction, multiplication, and division.
  • It has four pins for each row and 4 pins for each column.
  • The switch between a column and a row trace is closed, when a button is pressed, which completes the circuit and allows current to pass between a column pin and a row pin.

Circuit diagram and working:

Now, let’s start designing our circuit diagram for the calculator.

  • Make sure we have the correct and updated version of the Proteus software.
  • And make sure we have all the required libraries for the modules which we will be using in this project.
  • Now click on the new project (Ctrl+N) to start a new project of the Arduino calculator.
  • Import all the required components in the workspace.

Now we have all the required components in the workplace as follows.

Let's start connecting them.

  • First, we will connect the LCD module with the Arduino UNO module.
  • As we are using the LCD module in the 4-bit mode, therefore, we will have 4 pins for data, 1 pin for enable pin, and 1 pin for register status pin.
  • For data pins, connect the D4, D5, D6, and D7 pins of the LCD module to the D2, D3, D4, and D5 pins of Arduino UNO respectively. And connect the RS pin with D0 and Enable with D1 pin.
  • To use the LCD module in write mode, the R/W pin must be connected to the ground.
  • Now connect the keypad with the Arduino UNO board. As it is a 4x4 keypad, it will use 8 pins of the Arduino UNO board.
  • For row lines, we will use D13, D12, D11, and D10 pins and for column lines, we will use D9, D8, D7, D6 pins respectively.

That is all for connection. Make sure all the connections are correct, especially for keypad’s row and column connections otherwise we will get the wrong values from the keypad input.

And while working on the actual components, power the backlight of the LCD module and set the appropriate contrast, else nothing will be visible even if that has been displayed.

Arduino code for calculator:

Downloading and including libraries

  • Before going to write application code, we need libraries for the 16x2 LCD module and 4x4 keypad module.
  • We can download the library for the LCD module using this link LCD module library.
  • And use this link Keypad module library for keypad module.
  • Most of the Arduino related libraries are available on the Arduino official website.
  • We can add libraries in the Arduino using zip file or the manage libraries option.
  • If you have downloaded the libraries from the link then we have to click the option of “Add Zip Library” otherwise click on the manage libraries option and search for the required library.
  • After adding all the required libraries, include them in our application code.

Code declaration

  • We will declare the pins in the code as per we have connected them in the circuit diagram.
  • So first create the object for the LCD module and enter the pins we have used for LCD module connections.
  • While entering the pins in the LCD module object parameters, maintain the sequence as follows:

In the above-mentioned image, the first argument for RS pin, second for Enable pin, and rest four for data pins.

  • Now declare the variables for the Keypad module. We will use a 2D char array for storing keypad values, 2 arrays for storing pins used for rows and columns. And declare a ‘mykeypad’ name object for keypad class.
  • After that, declare some general variables which we will use to store the values like user input, output of calculation and operation.
  • After declaring and initialising all the variables and objects, we will start writing in the “void setup()” function.

Void setup function

  • This is one of the most important functions of Arduino programming.
  • As per the structure of Arduino programming, we can not remove this function from our code.
  • It will execute only once when the controller starts the execution.
  • Here, we will declare the modes of pins which we are going to use and setup functions related to the LCD module.
  • Display the welcome message on boot up of our calculator.
  • Here, we will begin the LCD module and set the cursor at 0,0 position and print the welcome message “The Engineering Projects Presents Arduino Calculator”.
  • As this message is written in the setup function, it will run every time once when the controller reboots and after 5 second delay, the LCD display will be cleared.

Void loop function

  • This is the second most important function of Arduino coding.
  • As per the structure of Arduino code, it must be in the code otherwise it will raise errors.
  • We will write our main application code here which we want to run in a continuous loop.
  • First, we will get the pressed key from the user, using the “myKeypad.getKey()” function and store that value in the variable named ‘key’.
  • And if the ‘key’ variable is one of the numbers, we will store that in the first number variable “num1”. And display that on the LCD display.
  • Now there can be two conditions, first if the user wants to perform the operation on a single digit number, in that case enter the operation which the user wants to perform. Then ‘key’ will be equal to ‘+’, ‘-’, ‘/’, ‘*’.

And required operation will be stored in the ‘op’ variable and a flag will be set for taking the second number.

  • Now the loop runs and control reaches to where ‘key’ is equal to number but this time it will go in the else condition of ‘presentValue’ variable because this variable is set ‘true’ from the operation condition.
  • And in this condition, the value will be stored in the ’num2’ variable. And here we will set the flag ‘final’.
  • Now the user will click the equal button to get the result. And the control reaches that condition and performs the operation on the values entered by the user and the same is stored in the ‘op’ variable.
  • Hence, the answer will be displayed on the LCD display.
  • After that, to clear the display, click the ‘C’ button. It will clear the LCD display and reset all the variables to their initial value.
  • Above mentioned condition is the first condition but in the second condition, when the user will enter more than one digits, then we shift the LCD cursor as per the length of the number entered.
  • To handle that situation, we will get the length of the entered digits and shift the LCD display cursor accordingly.

That is all the code, we need to run an Arduino Calculator.

Results/Working

Now, we have completed the coding and circuit part, it is time to run the simulation in the Proteus.

  • The first step to start the simulation, to add the hex file of our application code in the Proteus simulation.
  • To add the hex file, click on the Arduino UNO module and a new window will pop up then click on the Program Files option. Afterwards, browse to the folder of application code.
  • Now it is ready to start the simulation, click on the ‘Play’ button.
  • When simulation starts, the LCD display will show the welcome message.
  • Let’s suppose, we want to add two numbers 7 and 5. So click the same on the keypad.
  • After entering the values, click on the “=” button, it will display the result.
  • This is the same way we can operate different calculations using this calculator.
  • After that, click on this button which will clear the LCD display.

I hope we have covered everything related to Arduino calculator i.e. Simulation, Code, Working etc. but still if you find anything confusing, ask in the comments.

Thanks for reading this project out. All the best for your projects!

Smart 4 Way Traffic Signal Control with Variable Delay

Hello guys! I hope you’re all in a good mood today because we are going to review the design of an interesting project today. We’ll be looking to design 4-way traffic lights in such a way that their delay is variable and is dependent upon the traffic density. This project is of intermediate difficulty level for people studying in undergrad engineering school with electronics, electrical and mechatronics as their major. It is also for the people learning Arduino and basic circuit design on their own or through some course. We have already designed a Simple 4-Way Traffic Light Control using Arduino and today we will make it smart by adding a variable delay.

Where To Buy?
No.ComponentsDistributorLink To Buy
1LEDsAmazonBuy Now
2ResistorAmazonBuy Now
3LCD 16x2AmazonBuy Now
4Arduino Mega 2560AmazonBuy Now

Variable 4 Way Traffic Light:

As you all already know the importance of traffic lights and their usage has solved a number of traffic problems, traffic is becoming denser on each road in the whole world by the hour. This leads us to consider traffic density at such roads as well. A number of different solutions have been developed in recent times to help with this problem such as roundabouts. This is done so to ensure the safety of vehicles on road and of people walking on pedestrian walks. With the world going towards automation and autonomous systems, this is the right time to switch traffic lights to an autonomous traffic light system too and make the system intelligent.

Software to Install:

We will be going through how to make an autonomous traffic system by using Arduino as a microcontroller. However, we’re not making an actual system rather we will be making a simulation of the said traffic system on a circuit simulating software Proteus. So make sure you already have the latest version of Proteus installed on your PCs and laptops. If not, you should first install the Proteus Software by following the embedded link. Proteus is open database software, meaning people can easily make their own circuit simulating libraries for the software and can easily integrate those libraries. This helps in making the software versatile and easy to use. You can easily add your own components or download libraries of components and place them within the software.

To start working with this project, you need to install and include the following libraries on your Proteus software:

  • Arduino Library for Proteus: This library includes all the microcontroller-based programming boards made by the company Arduino.cc. This allows you to program on the Arduino software and after that, you can see the implementation of this code in Proteus simulation.
  • LCD Library for Proteus: LCDs are displays that can be used to display text or values being used in a certain code. These LCDs come in two sizes, namely a 16x2 and 24x4. LCDs are controlled by the Arduino board.
  • Ultrasonic Sensor Library for Proteus: Since we are using an ultrasonic sensor as well in this project for which Proteus does not have a built-in component, you would need to download its library as well.

Project Overview:

This is a smart 4-way traffic light system. The pedestrian lights work such that whenever a certain traffic light is green its opposite pedestrian lights turn on. An addition of ultrasonic sensors have been made in the traffic light sequence. One ultrasonic sensor is placed at each traffic light. Each ultrasonic sensor controls the time of their respective green traffic light. When the ultrasonic sensor output is high, the traffic light opens for one second, when the ultrasonic sensor output is intermediate the traffic light opens for two seconds and when the ultrasonic sensor output is low the traffic lights open for 3 seconds.

The main components and their use in this project is given below:

  • Arduino Mega: We have used Arduino mega in this project and recommend using an Arduino mega as well. This is because there are about 40 digital pins required to perform communication between the microcontroller and only an Arduino Mega fulfills that requirement.
  • Traffic Light Module: Proteus provides an in-built module for simulating traffic lights and we will use this instead of using RGB lights to create a better effect.
  • Ultrasonic Module: This module is not built-in, but information to integrate this module with Proteus has been given above. This module has a test pin in order to simulate it and works just like real life.
  • LCD: Liquid crystal display will be used to show the time in which the traffic light remains on.

Components Needed:

  • Arduino Mega
  • Traffic Lights
  • Green and Red LEDs
  • Variable resistors
  • LCD
  • Ultrasonic Sensor

Component Details:

We will go through the details of some of the important components being used in this project.

Arduino Mega:

Arduino is an open-source programmable board that serves as a microcontroller and processes information based upon inputs and gives information to actuators in terms of output. Arduino Mega is based upon the chip ATmegaGA2560 and has 53 digital I/O pins.

Figure 1: Arduino Mega

LCD:

Liquid Crystal Displays used in electronics are of two basic sizes, 16x2 and 24x2. These represent the number of columns and rows of the LCD. Each pixel can store one character in it. It is also known as a character LCD. It comes equipped with a backlight. The intensity or glow of the backlight can be controlled by attaching a potentiometer at specified pins.

Figure 2: LCD display

Ultrasonic Sensor:

An ultrasonic sensor uses SONAR technology to identify objects. It is basically used to find the distance of objects from the sensor. The ultrasonic sensor works by sending out ultrasonic waves and when these waves or parts of waves hit an object, they are reflected backward and the time from their propagation to their return is then noted. This time is then converted into the distance because we already know the speed by which those waves are traveling.

Figure 3: Ultrasonic Sensor

Proteus Simulation of Variable Traffic Lights:

In order to simulate this project on Proteus software, we will first make the circuit diagram on Proteus. After that, we will write our code on Arduino IDE software and integrate it with the circuit made in Proteus.

Open Proteus and open a new project. Import the following components in your Proteus worksheet.

Figure 4: List of components

Place the component in your worksheet as illustrated in the figure below:

Figure 5: Placement of components

After placing the components, make the connections as follows:

  • Connect 0,1 and 2 digital pins of Arduino to red, yellow and green of traffic light 1 respectively.
  • Connect 3,4 and 5 digital pins of Arduino to red, yellow and green of traffic light 2 respectively.
  • Connect 6,7 and 8 digital pins of Arduino to red, yellow and green of traffic light 3 respectively.
  • Connect 9,10 and 11 digital pins of Arduino to red, yellow and green of traffic light 4 respectively.
  • Connect 12and 13 digital pins of Arduino to red and green LEDs of pedestrian light 1 respectively.
  • Connect 14 and 15 digital pins of Arduino to red and green LEDs of pedestrian light 2 respectively.
  • Connect 16 and 17 digital pins of Arduino to red and green LEDs of pedestrian light 3 respectively.
  • Connect 18 and 19 digital pins of Arduino to red and green LEDs of pedestrian light 4 respectively.
  • Ground the negative terminals of all LEDs.
  • Connect one end of a variable resistor to the Vss pin of LCD.
  • Connect the other end of the variable resistor to the input.
  • Connect the input pin of the variable resistor with the Vee pin of LCD.
  • Ground the RW pin of LCD.
  • Connect RS pin of LCD to 22 digital pin of Arduino.
  • Connect E pin of LCD to 23 digital pin of Arduino.
  • Connect D4, D5, D6 and D7 pin of LCD to 24, 25, 26 and 27 digital pins of LCD respectively.
  • Connect the test pin of ultrasonic sensors to their respective potentiometers.
  • Connect the trigger pin and echo pin of the ultrasonic sensor of traffic light 1 to 28 and 29 digital pins of Arduino respectively.
  • Connect the trigger pin and echo pin of the ultrasonic sensor of traffic light 2 to 30 and 31 digital pins of Arduino respectively.
  • Connect the trigger pin and echo pin of the ultrasonic sensor of traffic light 3 to 32 and 33 digital pins of Arduino respectively.
  • Connect the trigger pin and echo pin of the ultrasonic sensor of traffic light 4 to 34 and 35 digital pins of Arduino respectively.

With this, your circuit connections are complete and we will now move on to the firmware setup of this circuit.

Arduino Code:

We have divided the Arduino code in 3 segments:

  • Declaration Code
  • Void setup
  • Void loop

We will look at these sections separately now.

Declaration Code:

The first step in the code is the declaration of variables that we will utilize in our program. At first is the declaration of ultrasonic sensor pins and setting them up with their respective pins of Arduino board. The syntax of this code is as follows.

Figure 6: Ultrasonic declaration code

Now we will include the library of LCD into our Arduino program, you can download this library from within the software. After that we will declare the LCD by defining the LCD pins. The syntax for which is as follows:

Figure 7: LCD declaration

In the next step, we will declare traffic light variables and define their Arduino pins.

Figure 8: Traffic light variable declaration

Now, we will declare the variables of pedestrian LEDs and then allot them their Arduino pins being used in the circuit.

Figure 9: Declaration of pedestrian LEDs

Now, there are two variables being used for each ultrasonic sensor for the calculation of their distance and time duration. We will declare those variables now.

Figure 10: Declaration of variables being used for calculations

Void Setup:

Void setup is the part of Arduino program that only runs once, in this section the program that only needs to run once is put, such as declaring pins as output pins or input pins.

Only the echo pins of ultrasonic sensor are input pins while all other pins are going to be output pins for this project.

We will first set up ultrasonic pins as follows:

Figure 11: Defining Ultrasonic pins as I/O for the Arduino Board

Now we will declare traffic light pins as output pins. The syntax for this is given as follows:

Figure 12: Setup of Traffic light Pins as Output

Now we will setup our pedestrian LEDs.

Figure 13: Setup of Pedestrian LEDs as Output

Now we will initialize our LCD, this basically tells the microcontroller to start the LCD and give power to it. The syntax is given below.

Figure 14: Initializing LCD

Void Loop:

This part of Arduino Program runs in a loop and consists of the main code of the program in which all the calculations are being done.

In the first part of the program, we will set the trigger pin of the first ultrasonic sensor to low and high. This would generate a pulse and send out a wave. After that we will read a pulse input from the echo pin. This will give us the duration in which the wave was propagated and returned. After that we will calculate the distance from the duration of the wave.

Figure 15: Syntax of 1st Ultrasonic Sensor

This distance calculation is for our first traffic light. Now we will use the if loop to check our distance value.

Figure 16: If Loop for Signal 1

If the value falls between our set limit for the loop, the signal will turn green for three seconds. This will also be displayed on the LCD.

Figure 17: Arduino Code

After that in our if loop, the yellow lights 1 and 2 will turn on to indicate transition.

Figure 18: Arduino Code

Now we will use the if loop to check our distance value.

If the value falls between our set limit for the loop of intermediate traffic, the signal will turn green for two seconds. This will also be displayed on the LCD.

Figure 19: Arduino Code

After that in our if loop, the yellow lights 1 and 2 will turn on to indicate transition.

Figure 20: Arduino Code

Now we will use the if loop to check our distance value again.

If the value falls between our set limit for the loop of low traffic, the signal will turn green for one second. This will also be displayed on the LCD.

Figure 21: Arduino Code

After that in our if loop, the yellow lights 1 and 2 will turn on to indicate transition.

Figure 22: Arduino Code

Now we will set the trigger pin of the second ultrasonic sensor to low and high. This would generate a pulse and send out a wave. After that we will read a pulse input from the echo pin. This will give us the duration in which the wave was propagated and returned. After that we will calculate the distance from the duration of the wave.

Figure 23: Arduino Code

This distance calculation is for our Second traffic light. Now we will use the if loop to check our distance value.

Figure 24: Arduino Code

If the value falls between our set limit for the loop, the signal will turn green for three seconds. This will also be displayed on the LCD.

Figure 25: Arduino Code

After that in our if loop, the yellow lights 2 and 3 will turn on to indicate transition.

Figure 26: Arduino Code

Now we will use the if loop to check our distance value.

If the value falls between our set limit for the loop of intermediate traffic, the signal will turn green for two seconds. This will also be displayed on the LCD.

Figure 27: Arduino Code

After that in our if loop, the yellow lights 2 and 3 will turn on to indicate transition.

Figure 28: Arduino Code

Now we will use the if loop to check our distance value again.

If the value falls between our set limit for the loop of low traffic, the signal will turn green for one second. This will also be displayed on the LCD.

Figure 29: Arduino Code

After that in our if loop, the yellow lights 2 and 3 will turn on to indicate transition.

Figure 30: Arduino Code

Now we will set the trigger pin of the third ultrasonic sensor to low and high. This would generate a pulse and send out a wave. After that, we will read a pulse input from the echo pin. This will give us the duration in which the wave was propagated and returned. After that we will calculate the distance from the duration of the wave.

Figure 31: Arduino Code

This distance calculation is for our third traffic light. Now we will use the if loop to check our distance value.

Figure 32: Arduino Code

If the value falls between our set limit for the loop, the signal will turn green for three seconds. This will also be displayed on the LCD.

Figure 33: Arduino Code

After that in our if loop, the yellow lights 3 and 4 will turn on to indicate transition.

Figure 34: Arduino Code

Now we will use the if loop to check our distance value.

If the value falls between our set limit for the loop of intermediate traffic, the signal will turn green for two seconds. This will also be displayed on the LCD.

Figure 35: Arduino Code

After that in our if loop, the yellow lights 3 and 4 will turn on to indicate transition.

Figure 36: Arduino Code

Now we will use the if loop to check our distance value again.

If the value falls between our set limit for the loop of low traffic, the signal will turn green for one second. This will also be displayed on the LCD.

Figure 37: Arduino Code

After that in our if loop, the yellow lights 3 and 4 will turn on to indicate transition.

Figure 38: Arduino Code

Now we will set the trigger pin of the fourth ultrasonic sensor to low and high. This would generate a pulse and send out a wave. After that, we will read a pulse input from the echo pin. This will give us the duration in which the wave was propagated and returned. After that, we will calculate the distance from the duration of the wave.

Figure 39: Arduino Code

This distance calculation is for our fourth traffic light. Now we will use the if loop to check our distance value.

Figure 40: Arduino Code

If the value falls between our set limit for the loop, the signal will turn green for three seconds. This will also be displayed on the LCD.

Figure 41: Arduino Code

After that in our if loop, the yellow lights 4 and 1 will turn on to indicate transition.

Figure 42: Arduino Code

Now we will use the if loop to check our distance value.

If the value falls between our set limit for the loop of intermediate traffic, the signal will turn green for two seconds. This will also be displayed on the LCD.

Figure 43: Arduino Code

After that in our if loop, the yellow lights 4 and 1 will turn on to indicate transition.

Figure 44: Arduino Code

Now we will use the if loop to check our distance value again.

If the value falls between our set limit for the loop of low traffic, the signal will turn green for one second. This will also be displayed on the LCD.

Figure 45: Arduino Code

After that in our if loop, the yellow lights 4 and 1 will turn on to indicate transition.

Figure 46: Arduino Code

Results/Working:

At first, after writing the code, generate its hex file and put that hex file on the Arduino board on your Proteus software. After that, run the simulation. The results of the simulation are shown below thoroughly.

At first, when sensor one gives the output within 500 cm, the traffic light will turn on for one second only.

Figure 47: Simulation Results

However, if the sensor one value is between 500 and 900 cm, the traffic light 1 will be green for 2 seconds with the LCD displaying the remaining time.

Figure 48: Simulation Results

If the sensor values are above 900 cm, then the lights will be green for 3 seconds.

Figure 49: Simulation Results

When the sensor two gives the output within 500 cm, traffic light 2 will turn on for one second only.

Figure 50: Simulation Results

However, if the sensor two value is between 500 and 900 cm, the traffic light 2 will be green for 2 seconds with the LCD displaying the remaining time.

Figure 51: Simulation Results

If the sensor values are above 900 cm, then the lights will be green for 3 seconds.

Figure 52: Simulation Results

When sensor three gives the output within 500 cm, traffic light 3 will turn on for one second only.

Figure 53: Simulation Results

However, if the sensor three value is between 500 and 900 cm, the traffic light 3 will be green for 2 seconds with the LCD displaying the remaining time.

Figure 54: Simulation Results

If the sensor values are above 900 cm, then the lights will be green for 3 seconds.

Figure 55: Simulation Results

When sensor four gives the output within 500 cm, traffic light 4 will turn on for one second only.

Figure 56: Simulation Results

However, if the sensor four value is between 500 and 900 cm, the traffic light 4 will be green for 2 seconds with the LCD displaying the remaining time.

Figure 57: Simulation Results

If the sensor values are above 900 cm, then the lights will be green for 3 seconds.

Figure 58: Simulation Results

Phew! I know that this was an extremely long project, but that is a part of an engineer’s life. Multiple receptions and running recurring patterns smoothly requires skill and patience only an engineer can possess. I hope you guys made it through. Kudos to your nerves of steel. Thanks for reading.

ESP32 Hall Effect Sensor in Arduino IDE

Hello readers, I hope you all are doing great. Welcome to Section 5 of the ESP32 Programming Series. In this section, we are going to interface different Embedded Sensors with the ESP32 Microcontroller Board. ESP32 development board is featured with some inbuilt sensors(i.e. hall effect sensor, capacitive touch sensor) so, in the initial tutorials of this section, we will explore these built-in ESP32 sensors and in the later lectures, we will interface third-party sensors with the ESP32.

In today's lecture, we will discuss the working/operation of the ESP32 built-in Hall Effect Sensor. Hall Effect sensor is used to detect the variation in the magnetic field of its surroundings. So, let's first understand What's Hall Effect:

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

What is the Hall Effect?

The Hall Effect phenomenon was first discovered by Edwin Hall in 1879. When current passes through a conductor, the electrons move in a straight line and thus the voltage difference across the conductor's surface remains zero, as shown in the below figure:

However, when a magnet is placed near the current-carrying conductor in a way that the direction of the magnetic field is perpendicular to the flow of current, the electrons get diverted and don't follow a straight line, which results in generating a small potential difference across the conductor's surface, as shown in the below figure:

This small potential difference generated because of magnetic field presence is called Hall Voltage. This magnetic field influence over the current-carrying conductor is termed the Hall Effect.

Hall Effect Sensor

A Hall Effect Sensor is a non-contact type embedded sensor, used to detect the presence & intensity of a magnetic field in its surroundings. Different third-party Hall Effect Sensors available in the market are shown in the below figure:

  • A normal Hall Effect Sensor Pinout consists of 3 Pins i.e.
  1. Vcc: Normally +5V, few +3.3V are also available.
  2. GND: We need to provide Ground here.
  3. OUT: The Output Pin to give the sensor's response.
  • When a perpendicular magnetic field is placed near a Hall-effect sensor, it changes the status of its Output Pin.
  • The analog Hall Effect Sensors can also detect the strength of the magnetic field i.e. greater the magnetic field greater will be the sensor's output or voltage deviation.

Applications of Hall Effect sensor

  • In an Automotive system, Hall Sensors are used to detect speed, distance, position etc.
  • Used in Proximity sensing.
  • Used in Current sensing.
  • Used in Anti-lock braking system.
  • Used in Internal combustion engines to assist with ignition timing.
  • To switch an electric circuit ON and OFF.

Hall Effect Sensor in ESP32

In ESP32, the Hall effect sensor is located inside the ESP-WROOM-32 metallic cover. As the Hall Effect sensor is a non-contact type, it doesn't have to be in contact with the magnet. We just need to place the magnet above this metallic sheet and the ESP32 Hall Effect sensor will detect it.

Programming ESP32 Hall Effect Sensor using Arduino IDE

To understand the working of the Hall sensor with ESP32, let's test the builtin ESP32 example:

  • You can find the code through File> Examples> ESP32 > Hall Sensor, as shown in the below figure:

Arduino IDE code

Here's the code for this ESP32 Hall Sensor example:

int val = 0;

void setup()
{
   Serial.begin (9600);
}

void loop() 
{
   val = hallRead();
   Serial.print ("sensor value = ");
   Serial.println (val);//to graph

   delay(100);
}

Code Description

The code is quite simple, where the hallRead() function is called to read the hall sensor value, store it into a variable and then print it on the Serial monitor. Finally added a small delay to get the next value. Let me explain the code line by line for the beginners:

Variables Declaration

  • The first step will be the declaration of an integer-type variable to store the hall sensor value. The initial value assigned to the variable is zero.
int val = 0;

Setup() Function

  • Inside the setup function, the only task is to initialize the serial port at a 9600 baud rate for serial communication.
void setup()
{
   Serial.begin (9600);
}

Loop() Function

  • Inside the loop function, we called a function ‘hallRead()’ to read the sensor value and store those readings into the variable ‘val’.
  • Printed the sensor readings on the serial monitor or serial plotter using serial.println() function.
  • A delay of 0.3 sec is added at the end.
void loop() 
{
   val = hallRead();
   Serial.print ("sensor value = ");
   Serial.println (val);//to graph

   delay(100);
}

ESP32 Hall Effect Sensor - Testing

  • After successfully uploading the code into ESP32, open the serial plotter or serial monitor to monitor the results.
  • Place a magnet near the ESP32 board.
  • The sensor reading will increase/decrease depending on the magnet pole(i.e. North or South Pole) facing the Hall sensor.
  • Now click on Tools > Serial Plotter to visually analyze the sensor's output.
  • The Serial Plotter of our project is shown in the below figure:
  • As you can see in the above figure, the sensor is giving negative output when facing the North Pole of the magnet.
  • In the case of a South Pole, the sensor's output is positive.
  • In the absence of a magnetic field, the sensor's output is almost 0.
  • The distance between the magnet and the Hall sensor decides the amount of potential difference generated.
  • The greater the distance between the two, the smaller the hall voltage or potential difference will be.
  • We have attached an image from the Arduino IDE serial monitor for your reference.

This concludes the tutorial. I hope you found this helpful, test it out and if feel any difficulty, let me know in the comments. In the next tutorial, we will have a look at another built-in sensor of ESP32 i.e. Capacitive Touch Sensor. Thanks for reading.

Car Parking System with Automatic Billing using Arduino

Hi Geeks, welcome to our new project. Our new project is one of the most common issues you’ve seen in your cities. In this project, we are going to make a car parking system with automatic billing. In the entire world, there are an estimated 1.4 billion cars on the road, which is absolutely great news if we are considering the development of the Automobile industry. But the most serious issue is that the number of cars exceeds the number of available parking places, resulting in traffic congestion. Damaged cars due to this lack of space, fewer parking locations, lack of parking signage, informal parking, and overcharging for parking are just a few of the issues.

People are still choosing manual parking methods, which have a number of drawbacks, such as searching for a vacant spot in a parking lot without knowing if the lot is full or not, resulting in time and fuel waste. Vehicle safety is also a concern that may be addressed. We've all been in a position when we've spent a long time looking for parking at a location just to discover that none is available. You would think that if you knew the slots were full, you would've ended up finding another parking spot.

Based on these scenarios, we came up with the idea of a Car Parking System with Automatic Billing which will also reduce manpower such as security, booth attendants, etc., required in parking lots. Everything in the modern day is automated, and with this project, we can automate this procedure using simple electronics components and Arduino. Let's get started.

Where To Buy?
No.ComponentsDistributorLink To Buy
1DS1307AmazonBuy Now
2Keypad 4x3AmazonBuy Now
3LCD 20x4AmazonBuy Now
4Arduino UnoAmazonBuy Now

Software to install:

Instead of using real components, we'll use the Proteus Simulation tool to design this project. It's also a good habit to experiment with simulations before attempting to build everything with real components. By simulating an issue that may develop when working on actual components, we may identify the problem and avoid any damage to our components.

Proteus is an interesting software that lets you model and build electronics circuits. Despite having a huge library of electronics components, Proteus software lacks pre-installed modules such as Arduino boards, Ultrasonic sensors, RTC modules, LCD modules, and so on.

Now, we’ll start installing the libraries, which is needed for our project:

By clicking the button below, you can download the entire project, including Proteus Simulation and Arduino Code.

Project Overview:

These are required components for Accident Detection, which are as follows:

  • Arduino Uno: Arduino Uno is a development board from the Arduino family, which is the main component of this project and acts as the brain. The Microcontroller i.e., Arduino is responsible for the decisions that are going to be processed in the project.
  • 20X4 LCD display: It is used to display the information regarding parking slots and shows the amount that has to be paid by the driver at the Check out time from the parking lot.
  • Ultrasonic Sensor: It is used to calculate the distance from the car to the entry gate and detects that a car has reached near the gate.
  • RTC Module: Real-Time Clock Module is used to calculate the time and plays a key role in determining the total amount for the parking slot.

Components Needed:

  1. Arduino Uno
  2. LCD Module
  3. Ultrasonic Sensor
  4. Keypad 3x4
  5. LED’s
  6. RTC Module

Components Details

Arduino Uno:

  • Any Arduino development board can be used in this project, however, we'll be using Arduino UNO development boards. The Arduino UNO is a programmable, open-source microcontroller board from the Arduino series.
  • It contains an ATMega328P microcontroller from Atmel, which has an 8-bit RISC processing core and 32 KB of flash memory.
  • The Arduino UNO includes 14 digital I/O pins i.e., D0 - D13, with a resolution of 10 bits, including 6 PWM pins and 6 analog I/O pins (0-1024) i.e., A0 - A5.
  • Only one hardware UART peripheral pin, one I2C peripheral pin, and one SPI peripheral pin are available on the Arduino UNO (however we can use other pins for UART communication using the SoftwareSerial package in Arduino).
  • The Arduino UNO can be powered from a voltage range of 7 to 12 volts, the voltage regulator embedded inside the board will reduce the excess voltage. however, not more than 9 volts is suggested since it might harm the Arduino board.
  • A USB-B cable (the same cable that we used to upload the sketch to Arduino UNO), a DC power jack, and the Vin pin on the board may all be used to power Arduino UNO.
  • Using the Arduino IDE Software, the sketch is written and uploaded to the Arduino UNO. It is completely free, simple to comprehend, and easy to combine with a variety of electronic components.

LCD Module:

In this project, an LCD display is used to present the information to the user.
  • LCD stands for Liquid Crystal Display, and it is a type of display that is made using Liquid Crystal technology.
  • LCDs come in a variety of sizes; in this project, we utilized a 20X4 size.
  • The 20X4 indicates that it can show 80 ASCII characters at once.
  • The LCD has 16 pins. In which the necessary pins are connected in the circuit.
  • It contains eight data pins, one Read/Write select pin, one Register mode pin, one Enable pin, two backlight pins, two power supply pins, and one contrast control pin.
  • In the LCD, there are primarily two types of registers: Command Register and Data Register.
  • When the RS(Register Select) pin is set to logic high, the data register mode is selected, and when it is set to logic low, the command register mode is selected.

The RS pin will be set to logic high to display the data on the LCD.

Ultrasonic Sensor (HR-SR04):

  • The HC-SR04 ultrasonic sensor employs SONAR to estimate the distance of an object.
  • The ultrasonic sensor sends out a signal wave that has a frequency of about 40 kHz, with a high pitch that humans are unable to hear.
  • From 2 cm to 400 cm (1" to 13 feet), it provides the detection of objects with high accuracy and the pulse will not be disturbed by sunlight or any climate conditions.
  • It consists of four pins, Trig, Echo, VCC, and GND.
  • The operating voltage of an Ultrasonic sensor is 5V. We can connect the VCC pin of the sensor with 5V output in Arduino and the sensor will work perfectly.
  • Ultrasonic sensors work on the principle of sound wave reflection.
  • The trig pin works as an ultrasound transmitter which emits the high frequency sound waves in pulses. And the echo pin works as an ultrasound receiver. It receives the reflected ultrasonic waves which are bounced back from the object.
  • We calculate the distance from the object and the sensor by measuring the time taken between the transmission and the reception of the signal.
  • To measure the distance of sound traveled from trig to echo,

Distance = (Time x SpeedOfSound) / 2.

Speed of Sound: 340 meters per second i.e., 0.034
  • The easiest way to calculate the distance in cm is using this formula,

Distance in Centimeters = (( Time taken by pulse signal (in microseconds) / 2) / 29)

Keypad 3x4:

  • A keypad button is used for user input.
  • The keypad's buttons are arranged as a matrix of 3x4. Which means it has four rows and three columns.
  • They work on the principle of membrane keypads. They are very flexible and feel like a push button.
  • The switch between a column and a row trace is closed when a button is pressed, allowing current to pass between a column pin and a row pin.
  • A copper padding and line beneath the pad connects each switch in a row to the other switches in the row.

RTC Module (DS1307):

  • The DS1307 IC is a low-cost, high-accuracy RTC that uses the I2C protocol as an interface.
  • The DS1307 features a backup battery mounted on the rear of the module to maintain track of time even if the main power supply is disconnected.
  • When necessary, the chip shifts between the primary and backup power sources.
  • The RTC records information such as seconds, minutes, hours, days, dates, months, and years.
  • This module includes a Reference clock, programmable Square wave output(SQW), SCL, SDA, VCC, and GND.
  • Automatic Power-Fail Detect and Switch Circuitry
  • Low Power Operation Extends Battery-Backup Run Time.
  • The RTC module works on operating voltage 5V.

Proteus Simulation of Car Parking System:

Now, it’s time to start the design of the Proteus Simulation of our Car parking system

  • Before you begin designing, make sure Proteus is installed on your computer and that you have downloaded all of the necessary libraries.
  • We'll need Arduino libraries and LCD modules for this project. Make sure you've read the section on using libraries in Proteus software.
  • Let's begin by creating a new project, and importing all of the required components, and placing them within the working area.
  • Select all of the components from the Proteus component library that we'll require.

Circuit Diagram and Working:

After importing all required components to the workplace, let’s move to connecting them.

  • Starting with the connection of LEDs, we are using digital pins 2,3,4,5,6 for LEDs. Connect the positive side of the LEDs to the Arduino UNO board.
  • After that, connect the Ultrasonic sensor module’s Trig pin and Echo pin to digital pin 8 and 7 respectively, Vcc to 5v volt power and GND to Ground.
  • In the simulation. it will not be possible to change the distance from the Ultrasonic sensor so for that we have connected a potentiometer with the test pin of the module.
  • Now start the connection of the Keypad, as this is a 3x4 keypad so it will use 3 pins for columns and 4 pins for rows.
  • As there are limited digital pins on Arduino UNO, we have to use the analog pins of Arduino UNO as digital pins.
  • Now let’s connect the row pins A, B, C, D with A0, A1, A2, A3 respectively and column pins 1, 2, 3 with digital pins 9, 10, 11 respectively. And we have to connect the pins in an exact manner.
  • RTC module uses the I2C protocol, so we will connect SDA and SCL pins to Arduino UNO’s SDA (A4) and SCL (A5) pins respectively. Vcc with 5v power supply and Gnd with the ground.
  • As there are no pins left for connecting the LCD module therefore we will use an I2C GPIO expander for connecting the LCD module.
  • Connect the SDA and SCL pins of GPIO expander with the SDA and SCL pins of Arduino UNO and we have to set the slave address of GPIO expander, for that we will connect the A0, A1, A2 pins with ground, that will set the I2C slave address to 0x20.

Now we have done the circuit, it’s time to move to the coding side of this project.

Arduino code for the accident detection:

  • We must add relevant libraries, which operate as header files in programming languages before we begin writing the code.
  • So, if the necessary libraries aren't already installed in the Arduino IDE, we'll need to download them first.
  • We can install Arduino libraries by going to 'Sketch > Include Library > Manage Library' in the Arduino IDE. In the library manager, we can now search for our essential libraries. The libraries can also be installed via zip files.
  • We can download the libraries from the above instruction, but if they are not available, we can use the following links to download the zip files of libraries.
  • Here we used “Wire.h” to enable I2C communication and it is pre-installed.
  • “LiquidCrystal_I2C.h” is used for the LCD.
  • “Keypad.h” is used for the integration of the keypad module.
  • “RTClib.h” is the library for RTC modules.
  • Let’s declare the pins for modules. We mainly use two pins i.e. Trig and Echo for the object detection and distance calculation. Here we have connected the Echo pin to D7 and Trig pin to D8 in Arduino Uno and an array for storing the pins for LEDs as D2, D3, D4, D5, D6. Two arrays for storing the pins for keypads such as rowPins for A0, A1, A2, A3 pins and colPins for D9, D10, D11.
  • Now, Let’s declare configuration related variables for the keypad. Here we are declaring variables to store the number for Rows and Columns. We will use a 2D char array named ‘hexaKeys’ for storing the symbols of keypad.
  • Now declare some general variables for storing the values for ultrasonic sensors, charge, total charged amount, check-in time and check-out time of vehicles.
 
  • Now, Let’s declare the objects of the modules.
 
  • The “customkeypad” is initializing an instance of class NewKeypad. The statement is going to map these symbols with the pins we have declared to connect with Arduino. Hence, it will map according to the row and column pins.
  • Next, we are initializing the LCD display with an I2C serial interface and setting the address to 0x20 Hex.
  • And we are declaring an object named ‘rtc’ for the “RTC_DS1307” module.

Void Setup():

  • The void setup() is an important function in the sketch that will execute only once in the whole program. The input, output, and other serial communication initializations are done inside the void setup. Let’s write the void setup sketch now.
  • In this setup function, firstly we have enabled the serial communication with “Serial.begin” with the default baud rate of 9600.
  • Next, we are initializing the LCD and turning on the backlight of the LCD.
  • We have already declared the Trig and Echo pins before in the declaration part, and now we are going to set them up as output and input pins respectively.
  • There may be a doubt why we have declared a Trig as output and Echo as input. That is because the Trig pin will generate the ultrasonic wave pulses and the Echo pin will work as a receiver for reflected waves.
  • We are using five led’s for the five slots in the parking lot and to make the logic simpler, declare the led pins as output mode.
  • Now, we are printing a line in the serial monitor and LCD. We are using the cursor function and printing “Made by” in the first row and “Tushar Gupta” in the second row. (0,0) is representing (column, row) in the LCD.
  • After printing the line, clear the LCD screen.
  • Now, we are trying to initialize the RTC module and if the RTC is not found, it will print that “Couldn’t find RTC”. and halt the further processing of code.

  • After successful initialization of the RTC module we will know if the RTC module is running already , if yes then we don’t have to set the time explicitly otherwise we have to .
  • We will use a “dist()” function to calculate the distance using the formula mentioned in component details.
  • For the calculation of distance, we will generate the pulses using the Trig pin.
  • To generate the pulses , switch the TRIGpin to LOW for 4 microseconds and then HIGH for 10 microseconds then again LOW .
  • By using ‘pulseIn’ we can calculate the time duration the wave has taken to travel back from the object.
  • “ distance = duration*(0.034/2); ” and here 0.034 is the speed of sound and with this formula, we can calculate the distance in cm and set the threshold values.
  • “pulseIn” takes two arguments, first pin number and second logical state. This will read the pin for logic HIGH and return the time period in which that pin was at a HIGH state.
  • For more knowledge of “pulseIN “ refer to this link: pulseIN function

Void loop():

  • It is the next most important function of Arduino code/ sketch. The “void loop()” will run after the execution of “void setup()”.
  • We'll write the code required to run in a continuous loop in this part. So here we'll write our main application code.
  • Here, we are going to first discuss the Automatic billing part near the gate in our parking system.
  • In the loop function, the Date and Time of that current time are set by “rtc.now”, and the user will enter his slot number in the keypad when he/she is exiting from the slot.
  • The user will click the allocated slot number on the keypad and we are collecting that in the “customkey” variable using the “getkey” function.
  • The serial monitor will print the custom key entered by the user. Then we will check the slot status by “digitalRead (led[i])”.
  • If the led status is HIGH which means the slot was occupied now we will generate the bill for that slot and display that amount on the LCD display for1 second after clear the LCD and set that slot LED to LOW state.
  • The next step we are going to do is to calculate the total amount according to his vehicle staying inside the parking lot. And for that, we can do the simple calculation that is “amount = charge*(gotime [i] - cometime [i]) ;”.
  • We have already declared the charge amount in the above sections of the program. The charge will be multiplied by “go time - come time”, which is the total time the vehicle stayed inside the lot. And the multiplied result of stay time and charge is the final amount the driver has to pay for his parking slot.
  • Now, the driver can pay the amount and exit through the gate. Here, after a second delay, we are clearing the LCD display.
  • “What if the driver pressed any wrong key which has a free slot?” That might be the question in your mind. Well, we can cover that condition with an else statement, where we can print “The slot is already empty” on the LCD and let the driver know that he has entered the wrong key in the keypad near the exit gate.
  • Till now, we have seen the Automatic billing logic near the exit gate. But let’s see what is the slot allocation process at the entry gate.
  • As we have already calculated the distance with the ultrasonic sensor using the “dist()” function, we can set the distance limit to 100cm before the gate, and when a car reaches the entry gate the allocation of the slot will be started.
  • The “for loop” here will see what are the slots showing Low/empty in the parking and allocate that empty one to the car by printing “Park your car at ” and “Slot i” in the LCD.
  • As this slot was allocated, we have to write this LED as High which indicates the slot is not empty. This is the reason where the slot led is high at the exit gate when the user pressed his slot number in the keypad. We are turning on the LED when we are allocating the slot to a car.
  • Now we also have to collect the “come time” by the RTC module for further calculation at the end or near the exit gate.
  • We are implementing an if statement where the all LEDs are high, which means all the slots are filled, the LCD should print (“No more slots”) and inform the driver and clear the LCD screen.

Results / Working:

We have completed the Proteus simulation circuit and Arduino code for the Car Parking project. And it is ready for testing.

  • Before going to start the simulation, we have to add the hex file of our application code in the Arduino UNO module in Proteus and a hex code for the ultrasonic sensor also.
  • To add the hex file, click on the Arduino UNO and a new window will open then click on the Program files, there we will browse to our hex file.
  • In the same way, we can add a hex file for the ultrasonic sensor.
  • Now start the simulation, on the first boot of the circuit, LCD will display the welcome message and the same message will be displayed in the serial terminal also
  • Just for debugging purposes, we are continuously printing the ultrasonic sensor values.
  • In the simulation to change the distance between the vehicle and ultrasonic sensor we have used a potentiometer. Now change the value on the potentiometer.

As we can see that for 50% value on the pot ultrasonic sensor value is near to 500 cm and for 77% value on the pot ultrasonic sensor value is near to 850 cm.

  • Let's test the condition when the vehicle approaches the sensor, to satisfy that condition the object must be at a distance of less than 100 cm. For that, we have to change the pot value. Set the pot value near to 10 %.
  • After that LCD will display a message if that spot is vacant like “Park your car at Slot 1” and LED for the same location will glow.
  • To take the bill for any location press the keypad for that location number let’s suppose here the location is 1 so we will click on ‘1’
  • After that, it will generate the bill with the total charged amount and the LED for that location will be turned off.
  • In case if we click any slot button which is already vacant then LCD will display the message for the slot is vacant.

Here it is not visible which button on the keypad has clicked but suppose we have clicked ‘1’ and if that location is vacant then it will display that message.

  • Let’s take another case when we want to park another car. Now slot 1 is already busy so we will park at slot 2.
  • This time when the sensor value changes less than 100 cm, then the LCD display will show “Park your car at slot 2” because slot 1 is preoccupied.
  • In the image, we can see that both LEDs are glowing as both slots are occupied now.
  • For billing, we will click the button on the keypad for the respective slot.
  • Let’s take a case when all slots are occupied. Here we can see all slot LEDs are glowing.
  • Now we will try to park another car. Then LCD will display ‘no more slot’ as there is no vacant slot available at parking.

I hope you have a good understanding of how our Car parking system project works and that you have liked it. Although it’s a tough nut to crack in the first read, I strongly recommend you to read the logic part twice for better understanding. I believe we have covered almost everything, please let us know if you have any questions or suggestions in the comments section.

Thank you very much for reading this project. All the best for your projects!

ESP32 Over The Air (OTA) Web Updater

Hello readers, I hope you are all doing great. In this tutorial, we are going to discuss the OTA web updater on the ESP32.

We already covered the fundamentals of OTA programming in ESP32, in our previous tutorial where we used the Arduino IDE to upload OTA code into the ESP32 module using the network port.

In the OTA web updater, you need to create a web server page for OTA programming.

[caption id="attachment_166886" align="aligncenter" width="1920"] ESP32 OTA web updater[/caption]

Fig.1 ESP32 OTA web updater

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

Over the Air Web Updater

  • "Over-the-air" refers to the ability to wirelessly download an application, configuration, or firmware to internet-enabled devices, also known as IoT. (OTA). It functions similarly to our computers, laptops, tablets, and phones.
  • Instead of using a serial port and a wired medium to upload a code, the OTA web updater allows the user to update the code or firmware wirelessly via a web server.
  • When sensor nodes are frequently placed in remote or difficult-to-reach locations, OTA programming can be used.

Steps to implement an OTA web updater using ESP32

  • Using the serial communication port, upload the code containing the instructions to enable the OTA web updater (so that in the future you can update the code using a browser instead of a wired medium).
  • The code uploaded via the serial port will launch a web server, allowing you to upload new code over the air.
  • The new code, which has been uploaded using a web server, should contain instructions to keep the OTA web updater enabled on the ESP32 board so that you can use the OTA programming feature in future applications as well.
  • Create a .bin using Arduino IDE compiler and upload the file on the server.

Fig. 2

Code for OTA web updater implementation in ESP32

In this tutorial, we will discuss only the OTA web updater method using Arduino IDE and ESP32 dev-Kit V1 module.

If you want to know more about the basics of ESP32 and how to get started with Arduino IDE, then read Introduction to ESP32 Programming Series.

  • You can find the code through File> Examples> ArduinoOTA> BasicOTA.
  • An image has been attached below for reference:

Fig. 3

  • This code should be uploaded serially through a serial communication port only then you can access the OTA web updater feature.

Code

#include <WiFi.h> #include <WiFiClient.h> #include <WebServer.h> #include <ESPmDNS.h> #include <Update.h>   const char* host = "esp32"; const char* ssid = "SSID"; const char* password = "password";   WebServer server(80);   /* * Login page */   const char* loginIndex = "<form name='loginForm'>" "<table width='20%' bgcolor='A09F9F' align='center'>" "<tr>" "<td colspan=2>" "<center><font size=4><b>ESP32 Login Page</b></font></center>" "<br>" "</td>" "<br>" "<br>" "</tr>" "<td>Username:</td>" "<td><input type='text' size=25 name='userid'><br></td>" "</tr>" "<br>" "<br>" "<tr>" "<td>Password:</td>" "<td><input type='Password' size=25 name='pwd'><br></td>" "<br>" "<br>" "</tr>" "<tr>" "<td><input type='submit' onclick='check(this.form)' value='Login'></td>" "</tr>" "</table>" "</form>" "<script>" "function check(form)" "{" "if(form.userid.value=='admin' && form.pwd.value=='admin')" "{" "window.open('/serverIndex')" "}" "else" "{" " alert('Error Password or Username')/*displays error message*/" "}" "}" "</script>";   /* * Server Index Page */   const char* serverIndex = "<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>" "<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>" "<input type='file' name='update'>" "<input type='submit' value='Update'>" "</form>" "<div id='prg'>progress: 0%</div>" "<script>" "$('form').submit(function(e){" "e.preventDefault();" "var form = $('#upload_form')[0];" "var data = new FormData(form);" " $.ajax({" "url: '/update'," "type: 'POST'," "data: data," "contentType: false," "processData:false," "xhr: function() {" "var xhr = new window.XMLHttpRequest();" "xhr.upload.addEventListener('progress', function(evt) {" "if (evt.lengthComputable) {" "var per = evt.loaded / evt.total;" "$('#prg').html('progress: ' + Math.round(per*100) + '%');" "}" "}, false);" "return xhr;" "}," "success:function(d, s) {" "console.log('success!')" "}," "error: function (a, b, c) {" "}" "});" "});" "</script>";   /* * setup function */ void setup(void) { Serial.begin(115200);   // Connect to WiFi network WiFi.begin(ssid, password); Serial.println("");   // Wait for connection while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("Connected to "); Serial.println(ssid); Serial.print("IP address: "); Serial.println(WiFi.localIP());   /*use mdns for host name resolution*/ if (!MDNS.begin(host)) { //http://esp32.local Serial.println("Error setting up MDNS responder!"); while (1) { delay(1000); } } Serial.println("mDNS responder started"); server.on("/", HTTP_GET, []() { server.sendHeader("Connection", "close"); server.send(200, "text/html", loginIndex); }); server.on("/serverIndex", HTTP_GET, []() { server.sendHeader("Connection", "close"); server.send(200, "text/html", serverIndex); });   /*handling uploading firmware file */ server.on("/update", HTTP_POST, []() { server.sendHeader("Connection", "close"); server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK"); ESP.restart(); }, []() { HTTPUpload& upload = server.upload(); if (upload.status == UPLOAD_FILE_START) { Serial.printf("Update: %s\n", upload.filename.c_str()); if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size Update.printError(Serial); } } else if (upload.status == UPLOAD_FILE_WRITE) { /* flashing firmware to ESP*/ if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { Update.printError(Serial); } } else if (upload.status == UPLOAD_FILE_END) { if (Update.end(true)) { //true to set the size to the current progress Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize); } else { Update.printError(Serial); } } }); server.begin(); }   void loop(void) { server.handleClient(); delay(1); }

Code Description

The first task is to add the header files, required to perform over the air (OTA) web updates using the ESP32 module.
  • WiFi.h : This header file allows the ESP32 board to connect to the internet. It can serve either as a server or a client.
  • ESPmDNS.h : This library is used to implement multicast DNS query support for the ESP32 chip. A multicast UDP service is used to provide local network service.
  • WiFiClient.h : It is used to create a client that can connect to a specific port and IP address.

Fig. 4

  • Enter the SSID and password.

Fig. 5

  • You can style the HTML page anytime as per your requirements or use the default style given in the example code.

Setup()

  • Initialize the serial monitor at a 115200 baud rate.
  • WiFi.begin() function is used to initialize the Wi-Fi module with Wi-Fi credentials used as arguments.

Fig. 6

  • Wait until the ESP32 is connected to the Wi-Fi network.

Fig. 7

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

Fig. 8

  • Use multicast Domain Name System (mDNS) for hostname resolution.
  • Hostname has been defined as a global variable at the beginning of code.
  • Start the mDNS responder for esp32 or host using MDNS.begin() function.

Fig. 9

  • Return the index page which is stored in serverIndex.
  • Send the status OK (200 represents ‘OK’) to inform the client.

Fig. 10

  • Handling the uploading of firmware files.

Fig. 11

  • Start uploading the new firmware into the ESP32 board.

Fig. 12

  • Server.begin() function will start the server to listen for incoming connections.

Fig. 13

Loop()

  • Server.handleCLient() function is used to handle the client devices.
  • It will monitor the client devices and provide the requested HTML page.

Fig. 14

  • After successfully uploading the code into ESP32 board using serial communication port, open the serial monitor with 115200 baud rate.
  • Press EN or enable button from the ESP32 board.
  • You can see the IP address printed on the serial monitor, once the ESP32’s Wi-Fi module is connected to wi-fi network.
  • We have attached a screenshot below for your reference:

Fig. 15 Serial monitor

Testing

  • Now the ESP32 module is ready for over the air (OTA) programming.
  • For testing the OTA web updater, remove the ESP32 module from your computer and power the ESP32 board using another power source.
  • Open the browser and enter the IP address from the Serial Monitor as shown in the above image.
  • A web page with an IP address of 168.43.223 is shown below:

Fig. 16

  • Enter the username and password on the login page. As per the example code:
Username: admin Password: admin
  • You can change the username and password details if you wish to.
  • Click on Login.
  • A new browser page with URL 192.168.43.223/serverIndex will be displayed on the screen, as shown below:

Fig. 17

  • You can style the browser page as per your requirements.

Test code

  • Write a new code in Arduino IDE.
  • The code should contain two sections:
  1. The instructions to keep OTA web updater feature enabled
  2. Instructions to blink the LED (you can replace the LED code with another code as per your requirements).
#include <WiFi.h> #include <WiFiClient.h> #include <WebServer.h> #include <ESPmDNS.h> #include <Update.h>   const char* host = "esp32"; const char* ssid = "SSID"; const char* password = "password";   //variabls to blink without delay: const int led = 2; unsigned long previousMillis = 0; // will store last time LED was updated const long interval = 1000; // interval at which to blink (milliseconds) int ledState = LOW; // ledState used to set the LED   WebServer server(80);   /* * Login page */   const char* loginIndex = "<form name='loginForm'>" "<table width='20%' bgcolor='A09F9F' align='center'>" "<tr>" "<td colspan=2>" "<center><font size=4><b>ESP32 Login Page</b></font></center>" "<br>" "</td>" "<br>" "<br>" "</tr>" "<td>Username:</td>" "<td><input type='text' size=25 name='userid'><br></td>" "</tr>" "<br>" "<br>" "<tr>" "<td>Password:</td>" "<td><input type='Password' size=25 name='pwd'><br></td>" "<br>" "<br>" "</tr>" "<tr>" "<td><input type='submit' onclick='check(this.form)' value='Login'></td>" "</tr>" "</table>" "</form>" "<script>" "function check(form)" "{" "if(form.userid.value=='admin' && form.pwd.value=='admin')" "{" "window.open('/serverIndex')" "}" "else" "{" " alert('Error Password or Username')/*displays error message*/" "}" "}" "</script>";   /* * Server Index Page */   const char* serverIndex = "<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>" "<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>" "<input type='file' name='update'>" "<input type='submit' value='Update'>" "</form>" "<div id='prg'>progress: 0%</div>" "<script>" "$('form').submit(function(e){" "e.preventDefault();" "var form = $('#upload_form')[0];" "var data = new FormData(form);" " $.ajax({" "url: '/update'," "type: 'POST'," "data: data," "contentType: false," "processData:false," "xhr: function() {" "var xhr = new window.XMLHttpRequest();" "xhr.upload.addEventListener('progress', function(evt) {" "if (evt.lengthComputable) {" "var per = evt.loaded / evt.total;" "$('#prg').html('progress: ' + Math.round(per*100) + '%');" "}" "}, false);" "return xhr;" "}," "success:function(d, s) {" "console.log('success!')" "}," "error: function (a, b, c) {" "}" "});" "});" "</script>";   /* * setup function */ void setup(void) { pinMode(led, OUTPUT);   Serial.begin(115200);   // Connect to WiFi network WiFi.begin(ssid, password); Serial.println("");   // Wait for connection while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("Connected to "); Serial.println(ssid); Serial.print("IP address: "); Serial.println(WiFi.localIP());   /*use mdns for host name resolution*/ if (!MDNS.begin(host)) { //http://esp32.local Serial.println("Error setting up MDNS responder!"); while (1) { delay(1000); } } Serial.println("mDNS responder started"); /*return index page which is stored in serverIndex */ server.on("/", HTTP_GET, []() { server.sendHeader("Connection", "close"); server.send(200, "text/html", loginIndex); }); server.on("/serverIndex", HTTP_GET, []() { server.sendHeader("Connection", "close"); server.send(200, "text/html", serverIndex); }); /*handling uploading firmware file */ server.on("/update", HTTP_POST, []() { server.sendHeader("Connection", "close"); server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK"); ESP.restart(); }, []() { HTTPUpload& upload = server.upload(); if (upload.status == UPLOAD_FILE_START) { Serial.printf("Update: %s\n", upload.filename.c_str()); if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size Update.printError(Serial); } } else if (upload.status == UPLOAD_FILE_WRITE) { /* flashing firmware to ESP*/ if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { Update.printError(Serial); } } else if (upload.status == UPLOAD_FILE_END) { if (Update.end(true)) { //true to set the size to the current progress Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize); } else { Update.printError(Serial); } } }); server.begin(); }   void loop(void) { server.handleClient(); delay(1);   //loop to blink without delay unsigned long currentMillis = millis();   if (currentMillis - previousMillis >= interval) { // save the last time you blinked the LED previousMillis = currentMillis;   // if the LED is off turn it on and vice-versa: ledState = not(ledState);   // set the LED with the ledState of the variable: digitalWrite(led, ledState); } }

Test Code Description

  • We are using the same old code with an additional LED blinking part.
  • In this code, we are using inbuilt LED for testing.
  • Define the GPIO pin to which LED is connected.
  • GPIO 2 is connected to the inbuilt LED.
  • To add delay, we are using timers instead of delay() function.
  • The variable interval is defining the time delay.
  • Set LED’s state to low.

Fig. 18

Arduino Loop() Function

  • Blink the LED after every 1000ms or 1sec delay as defined in variable ‘interval’.

Fig. 19

How to generate a bin file

  • Compile the code in Arduino IDE.
  • Go to Sketch > Export compiled Binary or press Crl+Alt+S to generate .bin file.

Fig. 20

Fig. 21 bin file

  • Upload the .bin file on the browser with 192.168.43.223/serverIndex URL and click on update option.
  • At 100% progress the inbuilt LED from the ESP32 board will start blinking.

Fig 22

Fig. 23 LED blink

  • Similarly, you can upload a new code using over the air web updater.

This concludes the tutorial. I hope, you found this helpful and I hope to see you soon for the new ESP32 tutorial.

Simple 4-Way Traffic Light Control using Arduino

Hello friends, I hope you’re all well and healthy. In today’s tutorial, we will be going through a simple, yet effective practice to design a 4-way traffic light simulation in Proteus software. This project is designed for undergrad engineering students with majors in electronics, electrical and mechatronics engineering. It is also useful for people that want to learn the basics of circuit design and Arduino programming.

Where To Buy?
No.ComponentsDistributorLink To Buy
1LEDsAmazonBuy Now
2Arduino Mega 2560AmazonBuy Now

4-Way Traffic Light Control using Arduino:

Traffic lights are an integral part of the world’s transportation systems. Over the years a number of different algorithms regarding traffic lights have been developed. The algorithm being used at any place for the purpose of controlling traffic takes into account of various factors, such as number of lanes, people that cross a certain road, etc. The most common usage of traffic lights is to control the flow of traffic, which means providing a steady flow for people to go about their daily business on the road. Traffic lights help reduce accidents by a large margin since they allow the flow of vehicles in only one direction at a time. Traffic lights also help in avoiding traffic jams. The most common traffic light pattern being used in the world today is a 4-way traffic control that accounts for pedestrians as well. This sort of pattern is used in main city blocks and squares since these possess both vehicular traffic as well as pedestrian traffic. Traffic lights have a universal color understanding that red light signals for the traffic to stop, yellow light serves as a transition light from going to stop and vice versa.

Software to Install:

Since we are simulating this project instead of designing it using hardware components, you need to fill some requisites so that you can follow our procedure. At first, we need to have the simulating software. For simulation purposes, we will use the Proteus software, if you already have that installed, that is excellent. However, if you don’t, you should Install Proteus Software. Proteus is a circuit simulating software that has an open database that can be customized quite easily, leaving room to add new components along with their libraries. To start working with Proteus for this project, you need to add the following libraries:

  • Arduino Library for Proteus: This library includes all the Arduino boards, giving you options to simulate your circuit exactly according to your needs.

Project Overview:

The main components of a 4-way traffic light are:

  • Arduino Mega: For this circuit, we recommend using Arduino mega, that is because to control 4-way traffic along with pedestrian lights, we need 20 output pins while an Arduino UNO only has 14 digital I/O pins.
  • Traffic light module: This is an inbuilt traffic light module you can find in Proteus, there is no need for any additional libraries for this.
  • Pedestrian Lights: To distinguish pedestrian lights, we will use simple LEDs.

In this certain design, we have used delays to control the ON and OFF time of the traffic lights. There are other ways around this as well but using delays with Arduino is the simplest and most effective way for small projects.

The pedestrian lights are set up so that whenever a certain traffic light is GREEN, its opposing pedestrian light on which there is no traffic is turned ON and signals for the pedestrians to walk.

Components Needed:

  • Arduino Mega
  • Green and Red LEDs
  • Traffic Lights

Component details:

Arduino Mega:

Arduino Mega is a programmable microcontroller board.

Arduino Mega contains ATMegaGA2560 and is based on that microcontroller.

Every Arduino board is equipped with voltage regulators to make sure an excessive input does not burn components on the board.

Arduino Mega has 53 digital I/O pins.

Figure 1: Arduino Mega

Traffic Lights:

This module consists of three lights, namely, Red, Yellow and Green.

All three lights have separate input pins through which each light is controlled independently.

Make sure you connect all three pins to the Arduino, even if you are not using a certain light. This is because Proteus simulation only works when all the pins of traffic light are connected.

Figure 2: Traffic Lights

Proteus Simulation of Traffic Light Control:

We will first make the circuit on our Proteus software, after doing the connections of the circuit, we will work on the Arduino code based upon the circuitry and connections made.

First of all, make sure you have downloaded and installed Proteus software on your system and have downloaded and integrated the required libraries with the downloaded software.

Open Proteus and then open a new project, there is no need to change settings and simply select okay to default selected settings.

Import all the components of this project mentioned above and shown in the figure below:

Figure 3: Required Components

Place the components in the worksheet as illustrated below:

Figure 4: Component Placement

After placing the components in the worksheet, make connections as follows:

  • Connect 0,1 and 2 digital pins of Arduino to red, yellow and green of traffic light 1 respectively.
  • Connect 3,4 and 5 digital pins of Arduino to red, yellow and green of traffic light 2 respectively.
  • Connect 6,7 and 8 digital pins of Arduino to red, yellow and green of traffic light 3 respectively.
  • Connect 9,10 and 11 digital pins of Arduino to red, yellow and green of traffic light 4 respectively.
  • Connect 12and 13 digital pins of Arduino to red and green LEDs of pedestrian light 1 respectively.
  • Connect 14 and 15 digital pins of Arduino to red and green LEDs of pedestrian light 2 respectively.
  • Connect 16 and 17 digital pins of Arduino to red and green LEDs of pedestrian light 3 respectively.
  • Connect 18 and 19 digital pins of Arduino to red and green LEDs of pedestrian light 4 respectively.
  • Ground the negative terminals of all LEDs.

With this, your circuit connections are complete and we will now move on to the firmware setup of this circuit.

Arduino Code:

We have divided the Arduino code into 3 segments:

  • Declaration Code
  • Void setup
  • Void loop

We will look at these sections separately now.

Declaration Code:

The first step in the code is the declaration of variables that we will utilize in our program. At first is the declaration of traffic lights and setting them up with their respective pins of Arduino board. The syntax of this code is as follows.

Figure 5: Arduino Code

The next declaration is of pedestrian lights. The syntax of pedestrian light declaration is illustrated as follows.

Figure 6: Arduino Code

Void Setup:

This part of the code along with the declaration part is run only once, we will use this to define output and input pins. This helps Arduino to understand which pins to take data from and which pins to write data on.

Since there is no input, we will only define traffic lights and pedestrian lights as output pins. The syntax to do this is shown in figure 7.

Figure 7: Arduino code, Void Setup

Void Loop:

This part of the code runs in a loop consistently and is used to write the main section of the code.

In the first section, we will turn on the green light of signal 1 while all other signals are red. The pedestrian lights are red for pedestrian signals 1, 2 and 3. While the pedestrian 4 light is green since it is opposite to traffic signal 1.

Figure 8: Arduino Code

After a delay of 2000ms, we will turn on the yellow light for signal 1 and signal 2 to indicate that a transition from signal 1 to signal 2 will be made shortly. We will also turn all pedestrian lights red in order to ensure pedestrian safety.

Figure 9: Arduino Code

After a delay of 1000ms, all traffic and pedestrian lights will turn off for 100ms.

Figure 10: Arduino Code

For the second signal, we will turn on the green light of signal 2 while all other signals are red. The pedestrian lights are red for pedestrian signals 2, 3 and 4. While the pedestrian 1 light is green since it is opposite to traffic signal 2.

Figure 11: Arduino Code

After a delay of 2000ms, we will turn on the yellow light for signal 2 and signal 3 to indicate that a transition from signal 2 to signal 3 will be made shortly. We will also turn all pedestrian lights red in order to ensure pedestrian safety.

Figure 12: Arduino Code

After a delay of 1000ms, all traffic and pedestrian lights will turn off for 100ms.

Figure 13: Arduino Code

For signal 3, we will turn on the green light of signal 3 while all other signals are red. The pedestrian lights are red for pedestrian signal 1, 3 and 4. While the pedestrian 2 light is green since it is opposite to traffic signal 3.

Figure 14: Arduino Code

After a delay of 2000ms, we will turn on the yellow light for signal 3 and signal 4 to indicate that a transition from signal 3 to signal 4 will be made shortly. We will also turn all pedestrian lights red in order to ensure pedestrian safety.

Figure 15: Arduino Code

After a delay of 1000ms, all traffic and pedestrian lights will turn off for 100ms.

Figure 16: Arduino Code

For the final signal, we will turn on the green light of signal 4 while all other signals are red. The pedestrian lights are red for pedestrian signals 1, 2 and 4. While the pedestrian 3 light is green since it is opposite to traffic signal 4.

Figure 17: Arduino Code

After a delay of 2000ms, we will turn on the yellow light for signal 4 and signal 1 to indicate that a transition from signal 4 to signal 1 will be made shortly. We will also turn all pedestrian lights red in order to ensure pedestrian safety. This will also complete the loop and the sequence will keep running on its own.

Figure 18: Arduino Code

After a delay of 1000ms, all traffic and pedestrian lights will turn off for 100ms.

Figure 19: Arduino Code

With this, the program of the void loop will end and start again from signal 1 on its own.

Results/Working:

Generate a hex file from the Arduino program made above. Be sure to select

Integrate the hex file into your Arduino board on Proteus.

Run the simulation.

The results of the simulation should be something like our simulation results.

The simulation results for each scenario are illustrated in the figure below.

At first, traffic signal 1 is turned ON and the green light is displayed for 2000ms. The green pedestrian light 4 is also turned ON since it is opposite to signal 1.

Figure 20: Signal 1 is ON while Pedestrian 4 is ON.

Then the yellow light of signals 1 and 2 are turned ON showing transition is about to happen. The red pedestrian lights during this are turned ON to ensure pedestrian safety.

Figure 21: Yellow light showing the transition.

Then traffic signal 2 is turned ON and the green light is displayed for 2000ms. The green pedestrian light 1 is also turned ON since it is opposite to signal 2.

Figure 22: Signal 2 is ON while Pedestrian 1 is ON.

Then the yellow light of signal 2 and 3 is turned ON showing transition is about to happen. The red pedestrian lights during this are turned ON to ensure pedestrian safety.

Figure 23: Yellow light showing transition.

Then traffic signal 3 is turned ON and the green light is displayed for 2000ms. The green pedestrian light 2 is also turned ON since it is opposite to signal 3.

Figure 24: Signal 3 is ON and Pedestrian 2 is ON

Then the yellow light of signal 3 and 4 is turned ON showing transition is about to happen. The red pedestrian lights during this are turned ON to ensure pedestrian safety.

Figure 25: Yellow light showing the transition.

Then traffic signal 4 is turned ON and the green light is displayed for 2000ms. The green pedestrian light 3 is also turned ON since it is opposite to signal 4.

Figure 26: Signal 3 is ON and Pedestrian 2 is ON

Then the yellow light of signal 4 and 1 is turned ON showing transition is about to happen. The red pedestrian lights during this are turned ON to ensure pedestrian safety.

Figure 27: Yellow light showing the transition.

That is all for today’s tutorial, I hope you enjoyed learning with us. We wish you have a good day ahead of you. Thanks for reading.

ESP32 OTA (Over The Air) Programming

Hello readers, hope you all are doing great. In this tutorial, we are going to discuss a mechanism that allows users to update the ESP32 with a new program wirelessly or over the air (without using a USB cable to upload a new program).

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

Over-The-Air (OTA) programming

Fig. 1 ESP32 OTA

  • OTA programming is the mean by which a product manufacturer or product service provider can update the features or functionality of the device wirelessly or over the air, after the device has been deployed in the field where connecting a cable or uploading the code serially is difficult.
  • One key advantage of OTA is that a single central node can send an update to multiple ESPs on the same network.
  • The device must have a provisioning client capable of receiving, processing, and setting parameters in order to receive, process, and set parameters in a mobile device over the air.

Applications of OTA programming

Mobile Phones:

  • In order to improve the compatibility with hardware and enhance the stability of software and applications, software updates are required.
  • OTA updates are intended to improve the underlying operating system, time zone rules, read-only apps installed on the system partition these updates have no effect on user-installed applications.

IoT (internet of things) application:

  • The ability to wirelessly download an application, configuration, or firmware to internet-enabled devices, also known as IoT, is referred to as over-the-air (OTA). It works in the same way that our computers, laptops, tablets, and phones do.
  • Application, where sensor nodes are frequently placed in remote or difficult-to-reach locations OTA programming can be used.

Fig. 2 OTA programming for IoT

 

How does OTA programming work?

There are two methods of OTA implementation.

  • Basic OTA: In the basic OTA method the program is updated into ESP32 over the air using Arduino IDE.
  • OTA web updater: In web updater OTA the program is updated over the air using a web browser.

Implementing OTA Update feature using ESP32

In this tutorial, we will discuss only the basic OTA method using Arduino IDE and ESP32 module.

If you want to know more about the basics of ESP32 and how to get started with Arduino IDE, then follow the tutorial Introduction to ESP32 Programming Series.

  • For Basic OTA programming with ESP32, it is required to install the python 2.7.x version in your system.
  • Follow the link to download python: https://www.python.org/downloads/
  • Install the python into your system.
  • Upload the basic OTA code into ESP32 using the serial port.
  • Upload the new ESP32 test code over the air using the network port into esp32 module.

To implement the Basic OTA method, an example is available is Arduino IDE.

  • You can find the code through File> Examples> ArduinoOTA> BasicOTA.
  • An image has been attached below for reference:

Fig. 3

Arduino IDE Code

  • It is required to first upload the basic OTA code serially (using serial com port).
  • Because in default mode the ESP32 is not ready for OTA updates (as there is no inbuilt OTA firmware available inside the ESP32 board).
  • Only after that you can access the OTA feature
#include <WiFi.h> #include <ESPmDNS.h> #include <WiFiUdp.h> #include <ArduinoOTA.h>   const char* ssid = "SSID"; const char* password = "Password";   void setup() { Serial.begin(115200); Serial.println("Booting"); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.println("Connection Failed! Rebooting..."); delay(5000); ESP.restart(); } ArduinoOTA.onStart([]() { String type; if (ArduinoOTA.getCommand() == U_FLASH) type = "sketch"; else // U_SPIFFS type = "filesystem";   // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() Serial.println("Start updating " + type); }) .onEnd([]() { Serial.println("\nEnd"); }) .onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }) .onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); }); ArduinoOTA.begin(); Serial.println("Ready"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); } void loop() { ArduinoOTA.handle(); }

Code Description

  • The first step is to add all the necessary header files. Here we are using four header files.
  • WiFi.h: This header file allows the ESP32 board to connect to the internet. It can serve either as a server or a client.
  • ESPmDNS.h: This library is used to implement multicast DNS query support for the ESP32 chip. A multicast UDP service is used to provide local network service.
  • WiFiUdp.h: This is a library for Arduino wifi shield. It is used to send data to a UDP host over a wireless network.
  • ArduinoOTA.h: this library allows users to update the code in the ESP32 board using wifi instead of using the serial port.
  • Next, you need to add your wifi credentials. Enter the SSID and password.

Arduino Setup() Function

  • Inside the setup () function, the first task is to begin the serial monitor at a 115200 baud rate so that, you can print the results and other required details on the serial monitor for verification purposes.
  • Set ESP32 Wi-Fi module in station mode(esp32 will act as a client device) using WiFi.mode() function.
  • Enable ESP32’s Wi-Fi module using WiFi.begin() function which is using SSID and password as arguments.
  • Wait until the ESP32 is not connected with the wifi network.
  • ESP.restart() function will reset the ESP32. ESP.restart() function tells SDK to reboot.
  • If an error occurred in OTA programming, print the error on the serial monitor

  • ArduinoOTA.begin() function is used to initialize the OTA updater.
  • Wi-Fi.lockIP() is used to fetch the IP address.
  • Print the IP address on the serial monitor.

Arduino Loop() Function

  • Inside the loop() function, ArduinoOTA.handle() function is used for updating the ESP32 code over the air using the network port instead of the serial port.
  • Compile the code and upload serially using serial com port.
  • Open the serial monitor, set the baud rate to 115200.
  • You can see the IP address on the serial monitor once the ESP32 is connected to the Wi-Fi network.

Fig. 11 Serial monitor

Uploading new program into ESP32 module Over the Air

Code

#include <WiFi.h> #include <ESPmDNS.h> #include <WiFiUdp.h> #include <ArduinoOTA.h>   const char* ssid = "public"; const char* password = "ESP32@123";   //variabls for blinking an LED with Millis const int led = 2; // ESP32 Pin to which onboard LED is connected unsigned long previousMillis = 0; // will store last time LED was updated const long interval = 1000; // interval at which to blink (milliseconds) int ledState = LOW; // ledState used to set the LED   void setup() {   pinMode(led, OUTPUT);   Serial.begin(115200); Serial.println("Booting"); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.println("Connection Failed! Rebooting..."); delay(5000); ESP.restart(); } ArduinoOTA .onStart([]() { String type; if (ArduinoOTA.getCommand() == U_FLASH) type = "sketch"; else // U_SPIFFS type = "filesystem";   // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() Serial.println("Start updating " + type); }) .onEnd([]() { Serial.println("\nEnd"); }) .onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }) .onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); });   ArduinoOTA.begin();   Serial.println("Ready"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); }   void loop() { ArduinoOTA.handle();   //loop to blink without delay unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { // save the last time you blinked the LED previousMillis = currentMillis; // if the LED is off turn it on and vice-versa: ledState = not(ledState); // set the LED with the ledState of the variable: digitalWrite(led, ledState); } }
  • In the test code, which we are going to upload using a wireless network port over the air, a LED blinking function is added just to test whether the OTA functionality is working fine or not.

Note: It is required to upload the OTA programming handler code every time you upload a new code into ESP32 over the air. So that, OTA programming remains enabled for future use.

Code Description

  • Add the required header files.

  • Enter Wi-FI credentials over which you are going to upload the code wirelessly.
  • Define the GPIO pin to which LED is connected.
  • GPIO 2 is connected to the inbuilt LED.
  • To add delay, we are using timers instead of delay() function.
  • The variable interval is defining the time delay.
  • Set LED’s state to low.

Arduino Setup() Function

  • Although in the example code serial monitor is initialized but it is not required anymore as we are using the network port for communication.
  • Initialize ESP32 Wi-Fi in station mode using WiFi.mode() function.
  • Wait until esp32 is connected to the Wi-Fi network.

  • ArduinoOTA.begin() function is used to initialize the OTA updater.
  • Wi-Fi.lockIP() is used to fetch the IP address.
  • Print the IP address on the serial monitor.

Arduino Loop() Function

  • Blink the LED after every 1000ms or 1sec delay as defined in variable ‘interval’.

  • Compile the above code.
  • Go to the Tools menu, then click on port and select the network port as shown in the image below.

This concludes the tutorial. I hope you found this helpful. In the next tutorial, we will discuss the OTA web updater in ESP32.

Accident Detection System using Arduino

Hello everyone, Welcome to our new project. Our new project plays a very important role in our daily life as it is directly connected to our lives. In this project, we are going to design an Accident Detection module. Accidents are the most common thing we hear about in the news, and in social media. Everyone here or there has seen accidents or has been with one. So when any such incidents happen, we inform respective stations or hospitals in that emergency situation. But what about the accidents that happen at night, or in places where there is very less crowd or you are alone. So, to address this issue and provide a potential solution for that, we are going to learn how to detect an accident automatically and inform nearby aid/help stations.

We can use this useful project for an engineering project’s showcase for electronics, electrical engineering students, and can be used in real-life situations where it can help people in disastrous situations.

According to WHO, research says that in the current scenario, 1.3 million people are the victims of road traffic crashes, and 40% of these accidents of all fatal accidents occur at night. In most cases, the accidents are not reported immediately, or the injured doesn’t receive any help during that time. The time between the accident and the arrival of medical help for the injured can sometimes make the difference between his life or death. In the future, we can interface with the vehicle airbag system. This will optimize the proposed technology to the maximum extent and result in the finest accident detection system possible. In this Modern era, everything is being automated and with this project, we are going to automate this process with some electronic components and Arduino. So Let’s dive in. Here's the video demonstration of this project:

Where To Buy?
No.ComponentsDistributorLink To Buy
1NEO-6MAmazonBuy Now
2SIM900AmazonBuy Now
3Arduino UnoAmazonBuy Now

Software to Install:

Instead of using real components, we will design this project using Proteus Simulation. Working with simulation before attempting to make it with real components is also a smart practice. We can figure out the issue that may arise while working on real components and avoid any kind of damage to our components by simulating it.

Proteus is a very fascinating tool that allows us to simulate and create electronic circuits. Despite the fact that Proteus software contains a large library of electronics components, it still lacks pre-installed modules such as Arduino boards, GPS or GSM modules, and so on.

Let’s install the required libraries which, we are going to use in this project:

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

Accident Detection System using Arduino

Project Overview:

These are required components for Accident Detection, which are as follows:

  • Arduino Uno: Arduino Uno is a development board from the Arduino family, which is the main component of this project. The Microcontroller i.e., Arduino is responsible for the decisions that are going to be processed in the project.
  • Accelerometer: An accelerometer is a device that measures acceleration, which is the change in speed (velocity) per unit time. By measuring acceleration we can get information like object inclination and vibration which helps in detecting unusual activities/ accidents.
  • GSM: A GSM/GPRS Module is a device that is actually responsible for the wireless communication with the GSM Network, in this case, it is responsible for sending the appropriate information to rescue stations.

Components Needed:

  1. Arduino Uno
  2. GPRS Module
  3. Accelerometer
  4. GSM Module
  5. Bread Board
  6. Jumper Wires

Component details:

Arduino Uno:

  • The Arduino UNO is one of the Arduino family's programmable, open-source microcontroller boards.
  • It includes an Atmel Microchip ATMega328P microcontroller with an 8-bit RISC processing core and 32 KB flash memory from Atmel.
  • It has 14 digital I/O pins, including 6 PWM pins and 6 analog I/O pins with a resolution of 10 bits (0-1024).
  • It comes with one hardware UART, one I2C, and one SPI peripheral.
  • We can use the Arduino UNO with a voltage range of 7-12 volts, but not more than 9 volts is recommended because it may damage the Arduino board
  • To power the Arduino UNO we can use a USB-B cable (the same cable that we use to upload the sketch to Arduino UNO), a DC power jack, or the Vin pin on the board.

GPS Module:

  • The Global Positioning System (GPS) is a space-based global navigation satellite system that gives accurate location and timing in all weather and at all times around the world.
  • It sendLongitude, latitude, height, and time are the four variables that a GPS receiver determines.
  • Data determined by the module will be sent to the microcontroller (Arduino Uno) through the UART protocol.
  • With a USB interface, the GPS module is simple to operate. It operates on a 3.2 to 5V supply range, allowing it to interface with both 3.3V and 5V microcontrollers.
  • It has a default baud rate of 9600 and can be modified as per our requirement.
  • We have used this to get the current location of the user.

Accelerometer:

  • Accelerometer sensors are integrated circuits (ICs) that are used to measure acceleration, inclination, and various parameters regarding the x,y,z axes. It is the main component to detect the accident.
  • Here we used the MEMS (Microelectromechanical Systems) accelerometer. These types of accelerometers are used where we have to measure the vibration or shock without any fixed reference.
  • It monitors changes in the capacitance and converts that value to analog output voltage.
  • Gyro Range of the Accelerometer sensor is ± 250, 500, 1000, 2000 °/s (may vary depending upon the sensor).
  • Accelerometer Range of the sensor module is ± 2 ± 4 ± 8 ± 16 g (may vary depending upon the sensor).

GSM module:

  • This module is used to send the notification to the rescue station or the emergency numbers.
  • It communicates with the Arduino UNO using the UART protocol.
  • It works in a voltage range of 3.5 - 5 volts.
  • There are different types of GSM modules available but in this project, we have used the SIM900D module.
  • We operate them using the AT commands. As there are hundreds of AT commands but we will use some basic only just to send the message.

Proteus Simulation of Accident Detection Circuit:

Now, it is time to start designing the main circuit of Accident detection in Proteus Simulation software.

  • Most importantly, ensure that Proteus is installed on your PC/Laptop and download all the required libraries for Proteus ahead of starting the designing steps.
  • For this project, we are going to use libraries for Arduino Uno, GPRS Module, GSM module.
  • To add the libraries in the Proteus suite we have to go to the C drive then LabCenter Electronics >> Proteus 8 professional >> Data >> Library and paste the downloaded library files here.
  • The download links of all the libraries have been provided to you in the above sections, please go check them out.
  • Let’s start the making of a new project, open the new project in Proteus.
  • After that enter the name of your new project.
  • Now our working area will be open here we will import all the required components which we are going to use.
  • The following components need to be selected from the Proteus component library. We’ll connect the components and make the circuit complete.
  • Now we have imported all the required components for this project, after this, we will start connecting them.

Circuit Diagram and Working:

  • There are two modules GPRS and GSM modules, both communicate using the UART protocol but in the Arduino UNO there is only one hardware UART’s provision. Now, you may have doubts about how we are going to connect them. No worries, we will handle that on the coding side by declaring the different pins as UART pins.
  • We can use different pins for UART using the SoftSerial library of Arduino, which will be discussed in the code.
  • We will use the digital pins for UART connections, digital pins 2 and 3 for communication of the GSM module, which means connecting the Rx and Tx of the GSM module with the D2 and D3 pins of Arduino UNO respectively.
  • Connect the Rx and Tx of the GPRS module with the D10 and D11 pins of Arduino UNO respectively.
  • As modules are connected, now we will connect the accelerometer. As it will not be possible to simulate the accelerometer in Proteus so we have used the potentiometers to change the value of the X-axis, Y-axis and Z-axis.
  • You may have doubts about how we can replace the accelerometer with potentiometers. As we will use the MEMS accelerometer, which sends the analog voltages for each axis, so we can simulate that using the potentiometer because we will receive the same type of data.
  • We need three potentiometers, one for each axis. Potentiometers of the X-axis, Y-axis and Z-axis will be connected to A1, A2 and A3 pins of Arduino respectively.
  • We will connect a serial terminal for debugging purposes.

Arduino code for Accident Detection System

Before going to start the coding, it would be easy if you understood the circuit diagram connections.

  • When we start writing the code(called a sketch in Arduino IDE), we will first include all of the necessary libraries for this project.
  • So, if the essential libraries aren't already installed in the Arduino IDE, our first step would be to get them.
  • Here we use mainly two libraries, one for serial communication and parsing data from the GPS module.
  • By heading to 'Sketch > Include Library > Manage Library' in the Arduino IDE, we can install libraries related to Arduino. We can now search for our essential libraries in the library manager. We can also use zip files to install the libraries.
  • As we've installed all the specified libraries. Let’s include them in our sketch.
  • Now, we are declaring D2 and D3 pins for serial communication with GPRS modules and declaring GPS objects as well, which will pretty much do all the grunt work with the NMEA data.
  • After that, we will declare variables to store the GPS module data.
  • Now, we are declaring pins and variables for the accelerometer which we will use in our project. Here, we are using Analog Pins because we are reading the analog voltages from the potentiometer.
  • We need to declare two threshold values for change in acceleration when an accident is detected.
  • The min and max values can vary. So, it is highly recommended to measure the values by accelerometer for devices using.

Void Setup():

  • It is one of the most important functions which will execute only once in the whole process.
  • As we are using a GPS module in our project, We should first start serial communication between the components and Monitor them through “Serial Monitor” in the Arduino IDE.
  • “Serial.begin” is used to set up the serial configuration for the device which is connected to the Serial Port of the Arduino. Here, we will set the baud rate for that device i.e 9600 in our case.
  • “serial_connection.begin(9600)” is used to set up the UART configuration for the GPS module. As the GPS module communicates to the Arduino at the baud rate of 9600.
  • We are using an Accelerometer in the circuit and it was clearly explained in detail that it will sense the x,y,z coordinates of the device and send them to Arduino.
  • Here, we have initialized a for loop to collect the sample data for x, y, and z coordinates of the device in the ideal state.
  • Afterward, the sample coordinates have been successfully measured by the Accelerometer sensor, but we need an average value for smoothing the sample coordinate values. So here, we will calculate the average of each coordinate and print them in the serial monitor.
  • After the setup, we will write our main application code in the Void loop function.

Void loop():

  • It is the second most important function of Arduino code. It will come to action after the execution of “void setup()”
  • We'll write the code required to run in a continuous loop in this part. So this is where we'll write our primary application code.
  • As a result, when the code gets to the void loop portion, We firstly take the NMEA data from the GPS module and print it in the serial monitor.
  • Wait a minute, NMEA??, I can understand all the questions in your mind. Let us give you a simple explanation regarding NMEA and its applications.
  • The word NMEA stands for the National Marine Electronics Association, which is a mode of communication that existed before inventing GPS. NMEA-format GPS data can be accessed with a wide variety of GPS receivers, instead of creating a new custom interface every time. Thus, it makes our lives easier using the GPS Module.
  • When we are printing the NMEA data into the serial monitor, it will be printed in a specific structure. This NMEA data was output from a GPS receiver:

“$GPGGA,191605.00,4521.7785210,N,07331.7656561,W,2,19,1.00,674.354,M,19.900,M,0.90,0000*60”

  • All NMEA signals start with the ‘ $ ’ character and for every data field such as coordinates, and various parameters are separated by a comma. The data further includes Timestamp, Latitude, Longitude, Quality indicator, Number of satellites involved, Altitude, etc., which is not necessary to remember. Make sure to get the data from the GPS module. If we have succeeded in this step and get the data on the serial monitor, then we are good to go for further processing.
  • The “if” statement is to process the NMEA data and separate the data into the required format if there is any location updated to the GPS receiver.
  • As we have already received NMEA data in the previous step, the data will be separated into Latitude, Longitude and Altitude.
  • In the Loop function, the values of GPS and accelerometer will be continuously tracked.
  • Here, the analog values of x,y,z coordinates are being measured and printed in the serial monitor.
  • These are not the values we measured in the void setup, those were the values to take the readings in the ideal state of the device.
  • But in the loop, the values are the present x,y and z coordinates measured by the accelerometer.
  • This is the condition for accident detection, we have already discussed before that in the void loop the x,y,z coordinate values are continuously extracted and the “if” statement here compares the recent values with fixed min and max values of the coordinates.
  • If the recent values are indistinct or do not match with threshold values i.e., max value and min value, then it indicates that an accident has been detected.
  • When the accident detection condition is satisfied, the GPRS module will be activated and will call to rescue stations for aid/help and their home.
  • Here, we have programmed to give a call 5 times to the appropriate numbers in the “for” loop.
  • And the process also includes a messaging feature along with calling to rescue stations.
  • When the same accident condition is satisfied, the messaging feature will be activated and we are going to send the alerting message including the Location, Latitude, Longitude, and Google map location link by appending latitude and longitude values the to respective numbers.

Results / Working:

We have successfully completed our Accident detection project and it’s ready to test!
  • Before going to start the simulation, we need to import the hex files of Arduino code in the Proteus, to do so click on the Arduino and browse to the hex file of the code and select.
  • Now we need to add the program files for the GPS and GPRS modules.
  • Here we should note that we only need to upload the program files for the modules while we are working in simulation. In the real modules, they come up with pre-installed codes.

Now we have done all the prerequisites of simulation.

  • Let’s power the circuit and start the simulation, firstly the void setup function will run and it will initialize all the required pins and variables and will read the ideal state values of the potentiometer.
  • Now to simulate the accident case, we will change the values from the potentiometer, so when the potentiometer’s value changes and the falls in the Min and Max value range the if condition will be stratified.
  • After this GSM module will call the stored number 5 times and send the GPS location with Google maps link in that.
  • We have used some serial monitors for debug purposes, you can see the current state of the project using them.

I hope you have a good understanding of how our Accident Detection project works and that you have liked it. Although I believe we have covered almost everything, please let us know if you have any questions or suggestions in the comments section.

Thank you very much for reading this project. All the best for your projects!

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