IoT Based Motion Detection with Email Alert using ESP32

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

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

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

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

Fig.1

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

Overview

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

Software and Hardware requirements

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

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

Fig. 2 PIR Motion Sensor

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

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

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

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

SMTP

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

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

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

Fig. 3 SMTP

How does SMTP work?

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

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

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

SMTP commands:

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

SMTP server parameters for email service

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

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

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

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

Create a new Gmail account (Sender)

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

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

In this tutorial we are using a Gmail account.

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

Fig. 4 create new gmail account

Access to Less Secure apps

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

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

Fig. 5 permission to less secure apps

Interfacing ESP32 and HCSR-501

Table 1

Fig. 6 ESP32 and HCSR-501 connections

Arduino IDE Programming

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

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

Necessary Library

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

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

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

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

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

Fig. 7 Adding ESP-Mail-Client Library

  1. Click on

Arduino IDE Code

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

//----Add the header files

#include <WiFi.h>

#include <ESP_Mail_Client.h>

//-----define network credentials

#define WIFI_SSID "public"

#define WIFI_PASSWORD "ESP32@123"

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

#define SMTP_HOST "smtp.gmail.com"

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

 

//----The log in credentials

#define AUTHOR_EMAIL "techeesp697@gmail.com"

#define AUTHOR_PASSWORD "Tech@ESP123"

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

SMTPSession smtp;

//---Declare the message class

SMTP_Message message;

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

void smtpCallback(SMTP_Status status);

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

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

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

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

void setup()

{

pinMode(inputPin, INPUT);

pinMode(LED_BUILTIN, OUTPUT);

Serial.begin(115200);

pir_output = digitalRead(inputPin);

Serial.println();

Serial.print("Connecting to AP");

WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

while (WiFi.status() != WL_CONNECTED)

{

Serial.print(".");

delay(200);

}

Serial.println("");

Serial.println("WiFi connected.");

Serial.println("IP address: ");

Serial.println(WiFi.localIP());

Serial.println();

/** Enable the debug via Serial port

* none debug or 0

* basic debug or 1

*

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

*/

smtp.debug(1);

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

smtp.callback(smtpCallback);

/* Declare the session config data */

ESP_Mail_Session session;

/* Set the session config */

session.server.host_name = SMTP_HOST;

session.server.port = SMTP_PORT;

session.login.email = AUTHOR_EMAIL;

session.login.password = AUTHOR_PASSWORD;

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

/* Set the NTP config time */

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

session.time.gmt_offset = 3;

session.time.day_light_offset = 0;

/* Set the message headers */

message.sender.name = "ESP Mail";

message.sender.email = AUTHOR_EMAIL;

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

message.addRecipient("Anonymous",

"replace this with receiver email adderss");

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

message.text.content = textMsg;

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

message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;

message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;

/* Set the custom message header */

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

/* Connect to server with the session config */

if (!smtp.connect(&session))

return;

}

void loop()

{

if (pir_output == HIGH)

{

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

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

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

digitalWrite(LED_BUILTIN, HIGH);

Serial.println("Motion detected!");

Serial.println("Email sent");

}

else {

digitalWrite(LED_BUILTIN, LOW);

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

}

delay(1000);

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

//to clear sending result log

smtp.sendingResult.clear();

}

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

void smtpCallback(SMTP_Status status)

{

/* Print the current status */

Serial.println(status.info());

/* Print the sending result */

if (status.success())

{

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

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

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

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

struct tm dt;

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

{

/* Get the result item */

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

time_t ts = (time_t)result.timestamp;

localtime_r(&ts, &dt);

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

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

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

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

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

}

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

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

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

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

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

smtp.sendingResult.clear();

}

}

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

Code Description

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

Fig. 8

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

Fig. 9

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

Fig. 10

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

Fig. 11

  • Insert recipient’s email address.

Fig. 12

  • SMTPSession object is used for sending emails.

Fig. 13

  • Next step is declaring a message

Fig. 14

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

Fig. 15

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

Fig. 16

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

Fig. 17 Variable for PIR sensor

Setup()

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

Fig. 18

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

Fig. 19

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

Fig. 20

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

Fig. 21

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

Fig. 22

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

Fig. 23

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

Fig. 24

Loop

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

Fig. 25 ‘If motion detected’

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

Fig. 25 No motion detected

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

Fig. 26 Clear the email log

Testing

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

Fig. 27 select development board and COM port

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

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

  • Open the serial monitor with 115200 baud rate.

Fig. 29 Serial monitor

  • Check the receiver email account.

Fig.30 received email on motion detection

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

What is Edge Computing?

 Hi Friends! Hope you’re well today. In this post, I’ll walk you through What is Edge Computing?

Edge computing is the extension of cloud computing. Cloud computing is used for data storage, data management, and data processing. While Edge Computing does serve the same purpose with one difference: edge processing is carried out near the edge of the network which means data is processed near the location where it’s produced instead of relying on the remote location of the cloud server.

Confused?

Don’t be.

We’ll touch on this further in this article.

Curious to know more about what is edge computing, the difference between edge computing and cloud computing, benefits, and applications?

Keep reading.

What is Edge Computing?

Edge computing is the process where data is processed near or at the point where it’s produced. The word computing here is used for the data being processed. Simply put, Edge computing allows the data to be processed closer to the source of data (like computers, cell phones) rather than relying on the cloud with data centers. This process is used to reduce bandwidth and latency issues.

For instance, Surveillance cameras. When these cameras are required simultaneously to record a video, if you use cloud computing and run the feed through the cloud, it will increase its latency (latency is the time delay between actual data and processed data) and reduce the quality of the video.

This is where edge computing comes in handy. In this particular case, we can install a motion detector sensor that will sense the movement of the physical beings around the camera. This motion-sensing device will act as an edge device that is installed near the data source (camera). When live feed data is processed near the edge devices instead of the cloud or data centers, it would increase the video quality and practically reduce the latency to zero.

Cloud storage takes more time to process and store data, while edge computing can locally process data in less time. The market of edge computing is expected to grow from $3.5 billion to $43.4 billion by 2027, according to experts in Grand View Research. Many mobile network carriers are willing to apply edge computing into their 5G deployment to improve their data processing speed instead of picking the cloud server.

How does Edge Computing Work?

Normally in cloud computing, two components are used: the device and the cloud server. In edge computing an intermediate node is introduced between the device and the cloud server, this node is called an edge device.

How data was stored in data centers before edge computing stepped in? Yes, this is the main question to discuss before we explain how edge computing works.

Before edge computing, data was gathered from distributed locations. This data was then sent to the data center which could be an in-house facility or the public cloud. These data centers were used to process the stored data.

In edge computing that data processing is carried out near or at the point from where data originates. This is very useful for making real-time decisions that are time-sensitive. Like in the case of automatic cars interacting with each other.

Plus, less computing power is required in edge computing since we don’t need to push back all data to the data center. Like in the case of a motion-detecting sensor installed near the camera. In case we require a video of a particular instance, we need to pull out the entire information recorded inside the camera to reach that particular instant clip. However, when the motion sensor is installed near the camera that acts as an edge device, we only require that information where that sensor has detected the movement of any physical beings, and we can easily discard the rest of the information and we don’t need to store that information into the cloud server.

Know that edge data centers are not the only way to store and process data. Rather, edge computing involves the network of different technologies. Some IoT devices can become a part of this edge computing and can process data onboard and send that data to the smartphone or edge server to do the difficult calculations and efficiently handle the data processing.

Cloud Computing Vs Edge Computing

An edge computing environment is developed using a network of data centers spread across the globe. The data centers in edge computing are different than the data centers at cloud computing. In former data centers store and process information locally and comes with the ability to replicate and transfer that information to other locations. While in the latter, data centers are located hundreds of thousands of miles away. The network latency issues and unpredictable pricing model of the cloud storage allow the organizations to prefer private data centers and edge locations over public cloud.

Google Cloud, Amazon Web Services, and Microsoft Azure are the best examples of cloud computing. They use cloud computing infrastructure which is developed to transfer the data from data source to one centralized location called data centers.

While facial recognition lock feature of the iPhone uses an edge computing model. If the data in this feature runs through cloud computing, it would take too much time to process data, while the edge computing device, which is the iPhone itself, in this case, does this processing within a few seconds and unlocks the mobile screen.

For massive data storage or for software or apps that don’t require real-time processing needs, cloud computing is the better solution and is commonly called the centralized approach. And if you require less storage with more real-time processing power that is carried out locally, edge computing is the answer and is called a decentralized approach where not a single person is making a decision, rather decision power is distributed across multiple individuals or teams.

Know that companies typically harness the power of both cloud computing and edge computing to develop advanced IoT frameworks. These two infrastructures are not opposite but are complementary for designing a modern framework.

Difference between Edge Computing and IoT

Edge computing is a form of distributed computing infrastructure that is location-sensitive while IoT is a technology that can use edge computing to its advantage. Edge computing is a process that brings the processing data as near to an IoT device as possible.

Don’t confuse an edge device with an IoT device. The device is the physical device where data is stored and processed while the IoT device, on the other hand, is the device connected to the internet. It is nothing but the source of the data.

Benefits of Edge Computing

Edge computing is changing the way how data is stored and processed. This gives a more consistent and reliable experience at a significantly lower cost.

  • With cloud computing, you require more bandwidth to transfer and communicate the data between the device and cloud server. With edge computing, on the other hand, you’ll require reduced bandwidth since edge devices are installed near the data source.
  • Edge computing guarantees low latency, better quality with better control over the transmission of sensitive data.
  • Moreover, edge computing allows conducting on-site big data analytics which helps in real-time decision making. This process keeps the computing power local which means you are not dependent on the centralized system, rather this creates a decentralized approach where decision power is distributed across the local edge data centers.
  • Edge computing comes in handy where bandwidth is reduced and the connectivity is unreliable. Such as in the places like a rainforest, remote farms, ships at sea, oil rigs, and desert. In such cases, edge computing does the processing work on the site or in other cases on the edge device itself – for instance, water sensors that check the quality of the water in remote villages. When the data is computed locally, the amount of required data you need to send can be reduced significantly, requiring less bandwidth, time, and cost which may otherwise be compulsory if data is processed remotely on a centralized location.

Challenges and Risks of Edge Computing

With new technology comes new security issues and edge computing is no different. From a security point of view, data at the edge computing can become vulnerable because of the involvement of local devices instead of the centralized cloud-based server. A few ricks of edge computing include:

Hackers always seek to steal, modify, corrupt, or delete data when it comes to edge computing. They strive to manipulate edge networks by injecting illegal hardware or software components inside the edge computing infrastructure. The common practice followed by these hackers is node replication where they inject malicious node into the edge network that comes with an identical ID number as assigned to the existing node. This way they can not only make other nodes illegitimate but also can rob sensitive data across the network.

Tampering of connected physical devices in edge networks is another malpractice carried out by potential hackers. Once they approach the physical devices they can extract sensitive cryptographic information, change node software and manipulate node circuits.

Routing attach is another security risk in edge computing. This approach can affect the way how data is transferred within the edge network. The routing information attacks can be categorized into four different types:

  • Wormholes
  • Grey holes
  • Hello Food
  • Black holes

In wormholes attach, hackers can record packets at one location and tunnel them to another. In grey holes attach, they slowly and selectively delete the data packets within the network. In a hello food attack, they can introduce a malicious node that sends hello packets to other nodes, creating routing confusion within the network. While in black holes attach the outgoing and incoming packets are deleted which increases the latency.

Know that these practices can be avoided by establishing reliable routing protocols and incorporating effective cyber security practices within the network. It’s wise to put your trust in manufacturers who have proper policies in practice to guarantee the effectiveness of their edge computing solutions.

Edge Computing Examples

Edge computing comes in handy where quick data processing is required. With computing power near the data source, you can make better and quick real-time decisions.

A few edge computing examples include:

  • Facial recognition
  • Virtual or augmented apps
  • Remote monitoring of assets in the oil & gas industry
  • In hospital patient-monitoring
  • Cloud gaming
  • Content delivery
  • Traffic management
  • Smart homes
  • Surveillance or security cameras
  • Alexa or Google assistant
  • Industrial automation

Predictive maintenance is another example where edge computing can play a key role. It helps to identify if the instrument needs maintenance before its major failure or total collapse. This saves both time and money which would otherwise require for entire instrument replacement.

Conclusion

Edge computing becomes common practice among many organizations since it provides more control over processed data.

This trend will continue to grow with time and it is expected by 2028 edge services will become widely available across the globe.

Wireless technologies such as WiFi 6 or 5G will work in favor of edge computing, giving chance to virtualization and other automation capabilities, at the same time making the wireless network more economical and flexible. Many carriers are now working to incorporate edge computing infrastructure into their 5G developments to provide fast real-time processing capabilities, particularly for connected cars, mobile devices, and automatic vehicles.

It is not about which one is better cloud computing or edge computing. It’s about the requirement. If you want data to be processed quickly near the source, you’ll adopt edge computing and if you want more data storage and data management, you will pick cloud computing.

The prime goal of edge computing is to reduce bandwidth and practically reduce the latency to zero. With the extension of real-time applications that require local computing and storage power, edge computing will continue to grow over time.

That’s all for today. Hope you find this article helpful. If you have any questions, you can reach out in the comment section below. I’d love to help you the best way I can. Thank you for reading this article.

What is Industrial IoT (Internet of Things)

Hi guys! Hope you’re well today. In this post today, I’ll cover What is Industrial IoT (Internet of Things?)

IIoT is now a talk of mainstream conversation. This term has blown up in the past couple of years. Before we move further to describe IIoT, it is evident that industries are no longer dependent on the traditional production processes that happened to be costly and guaranteed no optimal results. Now companies are willing to incorporate automation in manufacturing and production processes. Smart systems, no doubt, are dangerous for the traditional labor workforce, but on the other hand, they create more opportunities for the people equipped with the latest business trends.

Curious to know more about Industrial IoT, how does it work, the difference between IoT and IIoT, examples of IIoT, the impact of IIoT on jobs and workers, and the advantages of IIoT?

Keep reading.

What is Industrial IoT?

The Industrial Internet of Things, also known as Industry 4.0 or Industrial Internet, is the use of smart connected machines, embedded sensors, and actuators mainly used to enhance the overall efficiency and productivity of manufacturing and production processes.

At its core, it is used to automate processes for the production of optimal products that build a strong connection with the customers and create new revenue streams. Automation leads to accuracy and better efficiency and removes the likelihood of error that is difficult to attain by a simple human workforce. The Industrial IoT is used across a range of industries including manufacturing, oil and gas, logistics, mining and metals, transportation, aviation, energy/utilities, and more.

How does Industrial IoT work?

The smart devices deployed in Industrial IoT are used to capture, store and analyze data in real-time and that data is delivered to the company leaders to make faster, smarter business decisions.

A typical Industrial IoT system contains:

  • Intelligent systems are used to store and capture data.
  • Connected internet devices are used as a data communication structure.
  • Analytical applications that guarantee optimized processes by using that raw data.
  • Tools that allow managers and decision-makers to use that data for better decisions.

For example, I own a PCB manufacturing industrial unit. And I want to know which types of PCBs are most popular among customers. With IoT technology I can:

  • Use sensors to find out which areas of the industry are most crowded by the customers.
  • Hunt down the sales data to figure out which types of PCBs are selling faster.
  • Make sure demand and supply align so popular PCBs don’t go out of stock.

The information gathered by the smart devices helped me to make better decisions on which items to stock up on which ultimately helped me save both time and money.

Difference between IoT and IIoT

  • Both IoT and IIoT work on the same principle: using a network of intelligent devices and sensors for collecting, storing, monitoring, and analyzing data.
  • IIoT is nothing but an extension of IoT. The IoT is mainly used for commercial and domestic purposes, making the consumers’ life more easy and convenient. You can see its applications in wearable devices, smart microwaves, fitness devices, self-driving cars, and smart home automation systems.
  • While IIoT, on the other hand, is employed for increasing the productivity and overall efficiency of the industrial units. The set of smart devices and sensors used in IIoT collect and analyze data, automate production processes and guarantee a secure atmosphere by providing information in advance about industrial units that need maintenance.
  • The IIoT can be employed in supply chain robots, transportation and construction vehicles, agricultural systems, solar and wind power and smart irrigation system, and more.

Industrial IoT Examples

You’ll find a range of Industrial IoT examples. A few of them include:

  1. Predictive Maintenance

When a certain industrial process or a piece of instrument is at the brink of total failure, preventive and proactive maintenance is applied to allow a quick fix to the problem beforehand. This saves both time and money which otherwise results in costly instrument replacement. Traditional methods are obsolete to identify the problem in advance since they often required access of labor to remote places to perform manual testing. With IIoT, you get an alert when the problem starts developing, which provides a valuable insight into whether the instrument requires overhauling or complete replacement.

  • For instance, industries that manufacture elevators now install multiple sensors inside the product to make sure any problem can be identified before it halts the business operations. These sensors communicate with the cloud environment through data points that provide earlier automated notifications to the company technicians. This way any issue can be fixed in advance before it escalates to serious consequences.
  1. Process Automation

Automating the process is the main takeaway of employing IoT in industrial settings. When industrial processes are automated and involve no human intervention, it removes the likelihood of errors and improves operational productivity, and reduces overall production costs.

  • Only those industries excel and grow, that can produce maximum output with the minimum cost. In most industries, the energy cost is 30 to 50 % of the total cost of production processes. With process automation, the computer programs take inputs from the installed sensors and streamline the process that guarantees the optimal strategy for the plant. What makes these computer programs super important is their ability to learn from the given data and predict future trends to speed up the production process tailored to the changing conditions. The software directly controls the industrial equipment and allows it to move at a speed requiring minimum energy. Moreover, it also predicts if preventive maintenance is required, hence less energy, cost, and time is required to stop and restart the industrial unit for the regular inspection.
  • A smart irrigation system is another great example of IIoT used by farmers. Soil moisture and weather conditions are key factors to identify when watering is required for the crops. Soil moisture sensors are installed that provide moisture readings and send alerts to the system that automate the watering process. This way resources are used properly and more efficiently.
  1. Remote Monitoring

Remote monitoring is challenging for the industries. With traditional methods, not only is it difficult but also inefficient and risky. The businesses require consistent monitoring of the instruments working out in the field. Manual testing is risky since the field environment is often occupied with lots of heat, vibration, or humidity. And the access of humans is not recommended to those places.

  • For instance, tanks at production oil wells require consistent monitoring to identify if there is overflow which can be dangerous and often result in expensive cleanup costs. To minimize the risk and ensure a secure working environment, the company can install an IoT system that comes with an automated tank monitoring solution that monitors level readings and sends this data to the on-field engineer for managing pickups and deliveries. Moreover, it sends alerts for predictive maintenance based on the level readings and actual data. Using this method, companies don’t require any consistent physical existence of the human being on the field except when required.
  • In agriculture, it is often required to evenly distribute water across crop fields. Center pivots are mainly used for this purpose where water is sprinkled on the crops when center pivots move in a circle. Any damage to this center pivot can cause a loss of millions of dollars in revenue. Remote monitoring of the water pressure inside the center pivots can provide an insight into the disconnected fittings and leakage. Alerts and notifications are then sent to the farmers that take proper steps to nurture crop growth and avoid issues in advance before they aggravate a serious problem.

Impact of IIoT on workers and jobs

With the inception of digital technology, workforce transformation is on the rise. This new wave of technology, no doubt, removes the need for certain jobs but it also creates the possibility of generating new ones. According to the survey of business leaders in Accenture, this new digital era will create more jobs than it will eliminate.

The Industrial IoT provides scores of opportunities in optimization, automation, smart industry, intelligent decision making, industrial control, asset performance management, and in the sectors directly dealing with the customer’s behavior. They strive to create an environment tailored to the exact customer’s needs and demands so they keep coming back for what industries have to offer.

The IIoT makes the processes more efficient and improves productivity. It advocates for smart work, not hard work. Plus, the smart devices in IIoT removes the possibility of errors that may otherwise affect the production process if the traditional workforce is employed. Automation can gather data from hard-to-reach places, even reducing the risks to human lives. When a worker knows, they will get a notification on the smartphone about the tank leakage or the certain equipment that needs replacement, which means danger can be predicted in advance before it goes catastrophic.

This leads us to the conclusion: to survive in the ocean of digital transformation, it’s obligatory to equip yourself with the latest trends in engineering and information technology and liberate yourself from traditional research and development processes.

Advantages of Industrial IoT

There are many advantages of industrial IoT and low operating cost tops the list. With IIoT, you no longer need the physical presence of a human that requires monthly wages, paid leaves, healthcare costs, and holidays. Moreover, it doesn’t require commissions, monthly bonuses, and pensions that are compulsory if you induct human employees into your industry. More advantages of IoT include:

  1. To run production units consistently, companies need hundreds of employees in rotation for all three shifts and the plant still shuts down for maintenance and holidays. With IIoT, industrial units can run all day without any break 24/7 and 365 days a year. The plant only closes down when the maintenance is needed which is different than the regular maintenance since in this case maintenance is only needed when IoT sends alerts about the critical process or a piece of unit risks failure.
  2. When humans are employed in the industrial unit, there is always a likelihood of error no matter how hard they try to thwart it. With smart systems, no such errors occurred which guarantee the uniform and optimum quality of the products.
  3. With IIoT, manufacturing processes are more flexible. If you employ a worker for any task, you need to give them training in advance to get a hang of the entire instrument. Robots don’t require such training. They only need a program to perform any task.
  4. Industrial automation ensures the safety and security of human beings. Companies no longer need humans to send them to hard-to-reach places that are subjected to high risks like high temperature, vibration, and pressure. With IIoT you can remotely check the status of instruments on the field.
  5. Automated processes come with high precision and accuracy. They depend on the data gathered by sensors and streamline the overall industrial process based on the given information. Everything is done and controlled by the connected devices and no human intervention is involved which removes the possibility of error.

Conclusion

Industries have been incorporating automation into their production and manufacturing processes.

And this trend will increase over time and you’ll witness more industries are stepping into the realm of automation.

Industries are committed to upgrading their system and instruments to keep up with the modern trends and to make a footing in disruptive technologies.

This process is, no doubt, more efficient, delivers better results, maintains product quality, and is more economical. Even though it requires a high initial cost, it doesn’t need a regular labor force, reducing the overall operating cost of the processes.

If you want to make your worth in the industry, it is wise to keep you updated with the latest industry trends to make sure you’re not left out in the traditional industry jobs.

That’s all for today. Hope you find this article helpful. If you have any questions regarding IIoT, you are most welcome to ask in the section below. I’d love to help you the best way I can. Thank you for reading this article.

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

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

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

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

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

16x2 LCD Module

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

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

Let's have a look at the LCD pinout:

LCD Pinout

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

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

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

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

Now, let's interface the LCD with ESP32:

Interfacing LCD with ESP32

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

  • Data Mode
  • I2C Mode

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

LCD with ESP32 in Data Mode

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

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

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

    Components Required

    Here are the components required to interface LCD with ESP32:

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

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

    Circuit Diagram

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

    [Image]

    As you can see in the above figure:

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

    Here's our hardware setup for ESP32 LCD Interfacing:

    [Image]

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

    ESP32 Code for LCD

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

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

    Code Description

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

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

    Setup() Function

    In the Setup() Function:

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

    lcd.begin(16, 2);
    

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

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

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

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

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

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

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

    Results

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

    Common Errors faced while working on 16*2 LCD:

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

    Fig. 6

    Only a single row with dark blocks is visible.

    Sol. : Check the EN pin.

    Fig. 7

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

    Mathematical Calculations in Ladder Logic

    Hi friends, today we are going to explore mathematical computations in ladder logic. Like in any programing language you should find logic and mathematic computations, here in PLC programming you often need to process the input data that is collected from reading analog devices like temperature, level, flow et cetera. Then you need to run some calculations on this data to derive some other variables for deciding to run or stop some device or even to determine analog output to output to analog device i.e. valve or actuators. In the following sections, we are going to explore the mathematical functions and their input operators and outputs as well. Then we will show how to utilize such functions in ladder logic with simple examples and as usual enjoy practicing them thanks to the PLC simulator.

    What are mathematical operations we have

    You may find some minor changes in the set of mathematical functions from brand to brand of PLC controllers. However, you will find in most of them are common in every controller. For example, you will find the basic mathematical functions are available like addition, subtraction, multiplication, division, negation by applying two’s complement, modulus, increment and decrement, absolute, maximum, and minimum. In addition, trigonometric functions like sine, cosine, tangent are included. Let us go over these functions and explore their operators and output and how they can be utilized in PLC ladder logic programming.

    Functions operators and outputs

    For all these functions, they have input operators and one or more returned outputs. Most of them have two inputs like addition, subtraction, multiplication, and division. While some have only one input parameter like negating function, maximum, and minimum. And they all have only one input. Table 1 lists all these functions and their input operators and output.

    Table 1: the functions’ input parameters and outputs

     

    Operator and Output values data types

    It is very important to be familiar with the type of data you are trying to process using these mathematical functions. So, simply you just need to know that the smallest size data type is a bool data type which is true or false or “1” or “0” and it uses only one single bit. Then character “char” or byte data type which is 8 bits while word data type is formed of 2 bytes or 16 bits and that is the word size in PLC. Also, there are doubleword data types that occupy 4 bytes or 32 bits. Moving to mathematical data types there are integer data types that can be stored in one word and the double integer “DINT” which can be stored in two words or 32 bit for holding numbers up to = 4294967296 for unsigned integers and half of that value for signed integers. Also, there is a real data type for holding numbers with floating-point. It needs 2 words or 32 bits and for a long real LREAL data type extends to 4 words or 64 bits.

    How to use the mathematical function in ladder logic

    In the TIA portal for siemens, there are two ways to add mathematical functions in a rung of ladder logic program. Figure 1 shows the first method which uses an empty box in the block interface and then you can select the function and its inputs and outputs parameters.

    Fig. 1: Adding an empty box for including math functions

    Figure 2 shows a list of functions from which you can choose the mathematical function you want to use.

    Fig. 2: A list of math functions to select

    Figure 3 shows another way to add a mathematical function by going to the basic instructions and then going over the math functions on the most right part of the window as shown and selecting the function you want to use.

    Fig. 3: The second way to add a mathematical function

    Figure 4 shows how to define the input and output parameters of the used mathematical function. For example, in figure two input parameters are defined as the function’s input operators which are literal number five and variable “x” which is predefined as an integer in the variable declaration section in the middle top section. Also, the Variable sum is defined as an integer. So the add function will add X to 5 and assign the result to variable Sum.

    Fig. 4: Defining function parameters and outputs

     

    Mathematical function ladder example

    In this example, we are going to show how mathematical functions can be used in a ladder logic program and also show the simulation results. As in fig. 5, we design a simple calculator that uses the mathematical functions and each function can be triggered by a switch on a contact that is connected in series to the enable line of the function box.

     

    Addition function math example

    Figure 5 shows an additional example in ladder logic. It shows two operators A and B of integer data types. The variable A is located at address MW2 and variable B is located at address MW4 while the result is stored in variable RES which is located at address MW6. All of these variables are of type integer and size one word or 32 bits. The figure show simulation results on the PLC simulator and shows the RES variable holds summation of A and B.

    Fig. 5: Addition function example

     

    Subtraction math function example

    Figure 6 shows a subtraction example in ladder logic. It shows two operators A and B of integer data types. The variable A is located at address MW2 and variable B is located at address MW4 while the result is stored in variable RES which is located at address MW6. All of these variables are of type integer and size one word or 32 bits. The figure shows simulation results before triggering the subtraction function on the PLC simulator. So, the RES variable holds zero before enabling the function.

    Fig. 6: Subtraction function example not triggered

    Figure 7 shows the simulation results after enabling the subtraction by switch or the “SUB” command contact. The Res variable now reflects the results of subtraction.

    Fig. 7: Subtraction function example in ladder logic programming

    Multiplication math example

    Similarly, Fig. 8 shows an example for performing the multiplication process. First, the “MUL” is selected and two input operators of multiplications are given and output. The simulation result shows the RES variable holds the result of multiplication of the input operators.

    Fig. 8: Multiplication function example in ladder logic programming

       

    Division function example

    Similarly, Fig. 9 shows an example for performing the Division process. The “DIV” is selected as an instruction to be executed and two input operators of division are provided and output. The simulation result shows the RES variable holds the result of the division of the input operators.

    Fig. 9: Division function example after triggering

     

    MOD function example

    Similarly, Fig. 10 shows an example for performing the MOD function process. The MOD function determines the remainder of the division process, in this example we are dividing 25 by 10 which gives 2, and the remainder of 5. “MOD” function firstly is selected as an instruction to be executed and two input operators of MOD function are provided and output. The simulation result shows the RES variable holds the remainder of the division of the input operators.

    Fig. 10: MOD function example in ladder logic programming

    General calculation

    Now, one may ask how I need to do the calculation in form of an equation that has many processes? This is a very smart question! Many programming tools support this, fortunately. For example, in Siemens, there is a function called “calculate” which can take two inputs and perform mathematical equations on these two variables and return the result in an output variable as shown in Fig. 11. It shows the function which is called “CALCULATE” and it has two inputs “IN1” and “IN2” and one output “OUT”. I triggered the help to show you an example that states OUT can be determined from the equation in inputs and also shows all functions that can be used including logic and mathematical functions. So we can use this function, in general, to act like any mathematical or logical function separately or by combining two or more functions in one equation.

    Fig. 11: Using equations in ladder logic

     

    Example of performing equation in Ladder logic

    As you can see in the given example in fig. 12, the output variable can be determined based on multiplying the summation and subtraction of the input parameters as an equation. The result of the program is validated with a calculator.

    Fig. 12: Using equations in ladder logic

    Combining mathematical function

    There is another way to perform combine many mathematical functions as shown in fig. 13. As you can notice, the output variable “out” can be determined by multiplying the summation of input variables “in1” and “in2” by “in1”.

    Fig. 13: Combination mathematical function in ladder logic

    Negate function

    Negate function is one example of a single operator function in ladder logic programming. it reverses the sign of the input variable. For instance, fig. 14 shows an example of converting the sign of input variables “in1” to show the negative value reflected in the result in “res”.

    Fig. 14: Single operator mathematical function in ladder logic programming

    Absolute function

    Figure 15 shows an example of getting the absolute of variable “RES” and saving it in variable “b”.

    Fig. 15: Absolute function in ladder logic

    Minimum and maximum in ladder logic

    Getting minimum and maximum is one of the most frequently used in the mathematical operation. Figure 16 shows an example for getting a minimum of two input variables “in1” and “in2” while fig. 17 shows an instance of getting the maximum of two input variables as well.

    Fig. 16: Getting a minimum of two input variables in ladder logic programming

    Fig. 17: Getting a maximum of two input variables in ladder logic programming

     

    Decrement and increment in ladder logic

    One of the most commonly used functions is incrementing and decrementing one variable. For example, the counter variable all the time gets incremented and decremented through the logic of the program. Figure 18 shows an example for decrementing and incrementing an input variable. First, the initial value of the variable was 15, and then after incrementing it. The variable became 6 and then by applying decrementing operation it return to 5. It is very crucial to notice that, the user variable in increment and decrement operation works as input and output at the same time. Therefore, you can see in the increment and decrement blocks, it is defined as input-output “input”.

    Fig. 18: Increment and decrement operation in ladder logic

    Limiting variable in ladder logic

    Now, let us use one of the very useful functions to secure a variable at specific limits. Figure 19 shows an example of limiting the value of one variable “in” to be sited between the specified minimum and maximum values. In that very example, the input variable has had a value of 5 and because it exceeds the set limit of maximum it is set to 4 which is the maximum allowed value to the variable thanks to the limit function.

    Fig. 19: limiting variable in ladder logic programming

    Trigonometric functions in ladder logic

    Also, trigonometric functions like sine and cosine and other related functions can be executed in ladder logic. Figure 20 shows one example of how to use a sine function in ladder logic. The first rung in the example shows how to convert the degree into rad thanks to mathematical functions multiply and division. Ultimately, the sin function block is used to determine the sine of the given angle in rad.

    Fig. 20: Triogonometrical function in ladder logic programming

     

    What’s next

    I am so happy that you be that patient to reach these points of tutorial and you know got familiar with most of the mathematical functions and how to use them flexibly through your program. The next round will go with the comparison operators and more deeply in mathematical logic flow using operators such as >,<,>=,<=, and ==. So please be ready for our next session of that ladder logic tutorial.

    Up Down Counter using Arduino & 7-Segment Display

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

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

    Software to install

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

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

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

    We should first download the Arduino UNO library.

    Components required

    We will need the following components for this project

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

    Components details

    Arduino UNO

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

    7 Segment LED display

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

    Push buttons

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

    Project overview

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

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

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

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

    Circuit diagram and working

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

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

    Arduino Code for Up-Down counter

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

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

    Void setup()

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

    Void loop()

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

    Void changeNumber(int buttonpress)

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

    Result and test

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

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

    Conclusion

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

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

    Introduction to Raspberry Pi

    Hello friends, I hope you all are doing great. Today, I am going to start a new tutorial series on Raspberry Pi 4. It's our first lecture today, so I will explain the basics of Raspberry Pi boards.

    In this tutorial series, I will teach you each and everything about Raspberry Pi and its programming. I have designed this guide for beginners, so we will start from the very basics and will slowly move toward complex concepts. Python programming language is used in Raspberry Pi boards, so we will study Python as well.

    So, we will learn both programming and hardware circuit designing in this tutorial series. Let's first have a look at What is Raspberry Pi?

    What is Raspberry Pi?

    Raspberry Pi is a series of Single Board Computer, developed by the Raspberry Pi Foundation in England, to teach computer science in schools. When you buy the Raspberry Pi board, you only get the board. There are other components i.e. power adapter, HDMI cable and memory card etc. required to run the Raspberry Pi board. After these basic components are provided, the operating system must be installed on the Micro SD card.

    A Single board computer(such as Raspberry Pi) is a computer that contains basic units i.e. ram memory, input-output unit, microprocessor but unlike normal computers, it is not possible to expand the hardware features. For example, it does not contain a SLOT to increase the RAM memory from 1GB to 2GB. Since Raspberry Pi is designed as a single board and does not have a structure open to development for extra hardware to be installed on it, its cost is quite low. Single-board computers are not used as personal computers but are used in engineering projects where heavy computing is required i.e. robotics, IoT, image processing etc.

    Components i.e. memory, video card, network card, sound card etc. are usually integrated on-board in a single-board computer. The operating system is installed on the Micro SD card. Pictured is the Dyna-micro MMD1, the first single-board computer produced in 1976.

    Figure 1: DYNA-MICRO MMD1- First single board

    There are many alternatives to Raspberry Pi i.e. Orange Pi, Banana Pi, Asus Tinker Board etc. When examined in terms of features, Raspberry Pi boards are preferred, thanks to the community support behind them, even if the hardware features of the alternatives are better.

    The official operating system of the Raspberry Pi card is Raspberry Pi OS, but other operating systems can also be installed on Raspberry Pi boards.

    Raspberry Pi 4 is the latest version and it allows the use of both 32-bit and 64-bit operating systems.

    Figure 2: Raspberry pi os versions

    Figure 3: Recommended 3rd party operating systems for raspberry pi

    There is a processor with ARM architecture on the Raspberry Pi. The processor is based on the RISC(reduced instruction set computer) architecture developed by Advanced RISC Machines(ARM).

    Figure 4: Raspberry pi 4 -4gb version

    ARM-based processors are used in mobile devices, handheld terminals, mobile phones, media players, calculators, disk drives, VCDs, DVDs, cameras and even cars. To give a percentage, 75% of 32-bit processors in the world are ARM-based processors. The reason why this architecture is so preferred is the power saving, low cost and performance features of ARM-based processors.

    Figure 5: The processor used in the Raspberry pi4 version is a BCM2711-ARm based processor.

    The table shows the hardware comparison of all raspberry pi boards ever produced.

    When you buy the Raspberry Pi card, a power adapter and Micro SD card are needed to run the card and load the operating system into it. For Raspberry Pi 3 and previous versions, the power adapter must be micro-USB compatible and at least 2 Amps and 5 Volts. For Raspberry Pi 4 and above versions, the power adapter must be USB-Type C and at least 2.5 Amps.

    Figure 7: Raspberry Pi 4 power adapter

    Figure 8: While the USB-Type C connection shown on the left is used for Raspberry Pi 4, the micro USB connection is used for previous version cards.

    Figure 9A microSD card is needed to install an operating system. It is recommended to use a Class 10 type card.

    HDMI cable is used to interface card, monitor/display, keyboard, mouse etc. with Raspberry Pi 3 and previous versions, while micro HDMI cable is required for Raspberry Pi 4.

    Raspberry Pi 4 Applications

    Raspberry Pi 4 has a vast range of applications because of its portability, ability to produce integrated solutions, ram memory, internet connection, processor speed etc. Few applications of Raspberry Pi 4:

    • IoT Products.
    • Cryptocurrency Mining.
    • Printing on Servers.
    • Raspberry Pi Media Center.
    • Retro gaming station.
    • Control & Robotics.
    • Animations i.e. stop-motion camera, time-lapse video etc.
    • Build a Raspberry Pi web server.
    • Home automation & Security Systems.
    • Network monitoring system.
    • Stream live video on youtube.
    • Learn how to code( Python, C++, Code blocks etc.)
    • Bluetooth and Wifi Projects.
    • AI Projects.

    Raspberry Pi OS Installation

    Installing an operating system on the Raspberry Pi card to use it required. A minimum 8GB Micro SD card is required to install the Raspberry Pi OS operating system. https://www.raspberrypi.com/software/operating-systems/

    You can install the 32-bit or 64-bit raspbian os operating system on the Raspberry pi card. Especially if you have the Raspberry pi 4 8GB version, it would be appropriate to choose 64 bit OS. Because with a 32-bit operating system, you can only use up to 4GB of the RAM memory of the raspberry pi.

    Figure 10: Preferable operating systems for raspberry pi 4

    In Raspberry Pi OS installation, the image file (iso extension) must be downloaded to the computer and installed on the micro SD card via Win32 Disk Imager or a program that does the same job. In this step, we will examine how to upload the image file to the microSD card.

    A-Raspbian os installation steps with Raspberry pi imager

    The first step is to download the appropriate version of the imager application for our operating system to the PC.

    https://www.raspberrypi.com/software/ When we log in to the address, the imager application can be downloaded by clicking the "download for windows" button.

    https://downloads.raspberrypi.org/imager/imager_latest.exe

    Installation Steps:
    • When the imager application is run, the screen will appear as follows.

    Figure 11: Raspberry pi imager application screen

    In the first step, the operating system selection button is clicked. Select the operating system from the pop-up window. Here I prefer Raspbian os 32 bit operating system. If you want, you can choose other operating systems that you can use for different purposes from this menu.

    Figure 12: Choose OS screen

    If you want the operating system and all the applications that need to be installed on the raspberry pi, you can choose the Full version. For this, the Raspberry pi os (Other) tab is selected. Raspberry pi os Full tab is selected from the window that opens.

    Figure 13: full version raspbian os 32 bit version selection

    The settings button can be seen in the lower right corner of the opening screen. By clicking this button, we can change various settings that the raspberry pi will need during installation.

    Figure 14: The required settings can be changed during installation using the settings button.

    Many settings can be made, such as activating the SSH connection, wifi connection settings, entering the user name and password.

    If you do not have hardware for raspberry pi at the time of installation, such as monitor, keyboard, mouse, it is enough that your raspberry pi and your personal computer are connected to the same network. ssh connection can be used for this purpose. Thanks to the wifi setting we will make in the settings section, we can provide a remote connection to the raspberry pi card, which is on the same network as your pc.

    Figure 15: Setup settings window

    2-Select microSD Card: Your microsd card must be formatted in fat32 format.

    3-Write Button : All files in your selected microsd card will be deleted and after the work is finished, you will receive the operating system loaded.

    B- Installation using iso file

    In this section, the installation of the “Raspberry Pi OS with desktop and recommended software” version will be explained. In other versions, there are not some applications to be used as many packages have been removed to reduce the size. The MU Editor application will be used for programming the Raspberry Pi board. This application is only available in the "Raspberry Pi OS with desktop and recommended software" version. In addition, applications such as Scratch are only available in this version for the user to use.

    For installation, the file must be downloaded and extracted from the compressed folder. Looking at the extracted file, it will be seen that the file is a mirror file.

    Figure 16: Raspberry Pi disk image (ISO file)

    After downloading your preferred iso file to your computer, you need a program that will allow you to install your operating system on your sd card. For this purpose, you can choose the win32 imager application. Download this application from https://win32diskimager.org/#download and install it on your computer.

    Figure 17: Writing .img file to sd card.

    After the image file is loaded on the SD card, the operating system can be started by inserting the SD card into the Raspberry Pi.

    Interlock in Ladder Logic Programming

    Hi friends and hope you are all very well. Today, we are going to deal with one of the most important and common problems that would be there in everyday tasks in industry and its solution. The problem is the safety of equipment and operators by preventing the machine from running under specific conditions for realizing the safety of equipment and human as well. Not only does it fulfill safety but also it is for performing the designed sequence of operation. If there is a problem, then it should be the solution for it. the solution is what so-called “Interlock”. So, what is interlock? And why do we need it? And how we can design a good interlock? Well! We may find such concerns exist in two aspects which are safety and operation sequence. In the first aspect, safety happens when we need to make the execution of one operation or process locked by some condition for realizing the safety of the operator or equipment. The second one is operation sequence for which we need to sort the operation into sequential and concurrent tasks according to the logic philosophy of the operation. That can be realized by preventing one task of execution until one other task is finished or letting one task wait until one or more conditions are fulfilled. I hope that makes the reason why we need interlock close comes to your mind. Now, how we can perform interlock? Well! It can be done in many approaches. However, we can say simply there is only and only one idea to do interlock. It is by putting the condition “contact” on which it will be decided if the process will go on or not, or based on it, one piece of equipment can go running or keep stopped. By completing this article, you will have known what is interlock, why we need it in industry daily life problems, its techniques, and for sure how to program interlock. Furthermore, types of interlock, real examples from industry, and how you can implement it using ladder logic programming in different ways will be ready for you to learn and practice in this tutorial.

    What is interlock?

    Interlock is how to prevent one process or equipment from running to satisfy safety requirements or fulfill the logic of the operation. A clear example of an interlock is to prevent cutting weapons from executing as long as the hands of the operator are away from the working area. In this case, there will be two push buttons on the left and right of the operator and out of the working space to make sure, when the operator requests the cutting machine to operate, his hands were pressing those two push buttons which are out of the working space. The previous example shows how to employ interlock for realizing safety purposes. Another instance that shows how Interlock can be used to satisfy the operation logic requirements is when we need to drive the motor in two directions. In that case, we commonly use two relays or contactors for forward and reverse directions. So, there should be an interlock of each contactor to each other meaning we cannot activate both at the same time because that will end up with a short circuit on the motor or the supply.

    What are types of interlock?

    There are two main types of interlock which are safety interlocks and machine or equipment interlocks. Safety interlocks for securing people from getting hurt while they operate the machine. And machine interlock concerns with securing the safety of machine parts and or realizing specific philosophy of logic. Figure 1 shows the different types and subcategories of interlock. The machine or equipment interlock can be classified into three types which are mechanical, electrical, and logical interlock types. And from their titles, the mechanical interlock can be physically satisfied by making mechanical connections between equipment to let or prevent them from running. An electrical interlock can be achieved by using electrical devices like relys’ coils, sensors, and switches. The first one which is relays’ coils is the most interesting electrical interlock technique as they can be utilized in creating a dependency between equipment so we can design flexibly dependence between two motors, for example, to not running simultaneously meaning one of two running scenarios. The last type is the logical interlock which is the most important here in this tutorial and I hope you get an astonishing start to master that type because that is the most frequently used in real life in the industry. Do you know why? Because it is done programmatically without the need for mechanical connections and setup or even electrical devices or hardwiring. Also, it is very flexible as you can change it when there is a need to change the logic at any time.

    Fig.1: interlock types

    Figure 2 shows the very example of a safety interlock to protect the operator from entering the zone of robot work to save him from the movable parts. Is that a mechanical or electrical interlock? Or maybe logical? What do you think? Well! Let’s move forward in the tutorial and come back to this question to see if you know the answer or not.

    Fig. 2: the safety interlock

    The non-safe interlock is designed for protecting equipment and lock specific processes from execution. The machinery interlock is classified into three main categories which are mechanical, electrical, and logic interlock. In mechanical interlock, a set of mechanical setups is designed to prevent equipment or operation from running at some operating conditions. Figure 3 shows a schematic of a mechanical interlock for a setup that makes the motor spin either forward or reverse direction and prevent enabling both at the same time. The dotted line represents the mechanical interlock between the two contactors for reverse and forward contactors for guaranteeing to enable only one of them at any given time.

    Fig. 3 mechanical interlock example

    Figure 4 shows the case of missing the mechanical interlock between the two contactors. It shows the possibility of activating bother of them at a given time. In that case, you can see the damaging effects on the motor and the short circuit possibility on the power lines.

    Fig. 4: fault condition due to missing interlock

    Another example of mechanical interlock is car steering interlock as shown in fig. 5. The steering wheel is interlocked mechanically and unlocked by inserting the key.

    Fig. 5: car steering mechanical interlock

    The mechanical interlock was commonly used in the past and my be exist nowadays but very rarely. On the other hand, the electrical interlock is the most commonly used in control systems currently. Similarly, the idea of electrical interlock can be achieved by preventing the flow of current between two devices at the same time. Typically two contactors or relays are used for achieving such electrical interlock. One of these contractors will be normally open and the other will be in a normally closed configuration as in Fig. 6. It is very clear that for energizing the lamp, CR2 will be energized when CR1 is de-energized.

    Fig. 6: electrical interlock example 1

    Another example of electrical interlock which is very common is the thermal overload shown in Fig 7. It shows two contactors are used in electrical interlock configuration. The main contractor is in a normally open configuration while the thermal overload contactor is in a normally closed configuration. When there the temperature is getting high to a specific value the thermal overload turns over from normally closed to normally open to disconnect the load.

    Fig. 7: electrical interlock example 2

    Now, let's move to the logical interlock which is our target in this tutorial. Logical interlock is applying the same concept of interlock programmatically. In this type, there is no mechanical or electrical physical connection for achieving interlock. Instead, programming is used to perform the interlock. This logical interlock saves the effort of commissioning including mechanical or electrical connections. In addition, it realizes reliability and flexibility.

    Logical interlock in ladder logic programming

    Figure 8 shows one example of logic interlock. You can notice the left part of the figure shows there are no mechanical or electrical hardwiring or connections between pumps 1 and 2. However, pump 2 is interlocked with pump 1 logically as shown in the most left part that shows the ladder logic code. To have pump 2 running, pump 1 should run first by the level switch. As shown on the right part of the figure below, when the level of the liquid reaches above the level switch, the switch is turned on and energized pump 1 which activates pump 2.

    Fig. 8: logic interlock example 1

    Figure 9 shows another logic interlock example in which a timer of type on delay is used to interlock equipment. As shown on the left the ladder logic code and on the right, an image shows the scenario of the logic with astonishing visualization. It shows that, when the operator presses the start pushbutton and keep pressing on it for the preset time value which is 3 second, the timer contact turns on and the coil of the contactor is energized. Now let us go to the lab and open our simulator to run those examples to validate their logic and verify their proper operations.

    Fig. 9: logic interlock example 2

    Logical interlock using ladder logic

    Let’s get to experimental work, now open your simulator, the first example as shown in fig. 10, there are two pumps. And we need to run one pump at every given time. So, no one of them will work when the other does. The ladder logic code shown in Fig.1, uses the contact of each pump’s coil to lock the other pump. For instance, if the first pump is running, that will open the path to prevent energizing the second pump’s coil when it is requested to run. Similarly, the first pump’s coil is hindered from running while the second pump is running. It looks smart but let us test and see if the logic we designed matches the real-time environment or there is an issue to solve!

    Fig. 10: The first example ladder logic program

    Simulation example 1

    Well! Now we have started our simulation. Figure 11 shows the initial case when no pumps are requested to run. So you can see each pump is all set to run once being requested.

    Fig. 11: the initial case when no pumps were requested

    Figure 12 shows the case when we requested the first pump to run. Because the stop button is not raised and the second pump is not running; The first pump goes running as shown in figure 12. So the question is that what is going to happen when requesting pump 2 to run?! Let’s see

    Fig. 12: starting the first pump

    Fig. 13 shows the case when we request pump 2 to run by hitting its start push button “start-pump2”. As expected, the second pump does not run for the interlock condition we designed for by putting a contact of the first pump’s coil as a condition to run the other pump. So let’s remove the hindering condition of interlock by stopping pump 1 and trying to run pump 2 and see.

    Fig. 13: requesting one pump to run when the other is running

    Figure 14 shows what happens when we remove the interlock condition. By hitting the stop push button of the first pump “stop-pump1”, the first pump has stopped. Consequently, the second pump went running once the interlock conditions has been removed. So now simulation verifies our design and proves our code of interlock is working great. Well done!

    Fig. 14: remove the interlock condition by stopping the first pump

    Interlock ladder logic example 2

    As we aforementioned section earlier, the interlock could be done by sensors state or reading, running and stopping statuses of other equipment, or logical devices like timers or counters as well. Timers and counters can be used as an interlocking technique for creating a running condition based on some delay or specific counting. Figure 15 shows one example of a timer-based interlock in which the pump won’t run by hitting the start button until the operator holds the start push-button pressed for 3 seconds then the pump goes running.

    Fig. 15: timer-based interlock ladder logic example

    Figure 16 shows the simulation of the second example. My friends, please notice, despite the start pushbutton having been hit by the operator; the pump does not start because it waits for the timer to count 3 seconds, and then it can run.

    Fig. 16: pump wait timer to start

    Now after 3 seconds of holding start push-button pressed, fig. 17 shows the pump goes running because the interlock condition is no longer there. I am very happy you would get that!

    Fig. 17: pump start running after 3 seconds

    What’s next?

    My friends, before talking about what we are going to practice next time; I just want to express my appreciation that you patiently follow up till this point and hope your experience moves forward and gets more and more every lesson. Next time we will navigate the mathematical functions and how to perform mathematical computations in your ladder logic programming. my friends I really can’t wait to see you very soon to practice mathematics in ladder logic programming.

    Water Level Indicator using Arduino

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

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

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

    Software to install

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

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

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

    Components Required

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

    Components details

    Arduino UNO

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

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

    Water Level Sensor

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

    LEDs

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

    Project overview

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

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

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

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

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

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

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

    Circuit diagram

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

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

    Arduino code of water level indicator

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

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

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

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

    Void Setup()

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

    Void loop()

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

    Results and working

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

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

    Conclusion

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

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

     

    Introduction to the MATLAB Datatypes

    Hello friends. In this lecture, we are going to have a look at the different kinds of MATLAB data types.

    As we have already seen in previous lectures, MATLAB stands for MATrix LABoratory and allows us to store numbers in the form of matrices.

    Elements of a matrix are entered row-wise, and consecutive row elements can be separated by a space or a comma, while the rows themselves are separated by semicolons. The entire matrix is supposed to be inside square brackets.

    Note: round brackets are used for input of an argument to a function.

    A = [1,2,3; 4,5,6; 7,8,9];

    An individual element of a matrix can also be called using ‘indexing’ or ‘subscripting’. For example, A(1,2) refers to the element in the first row and second column.

    A larger matrix can also be cropped into a smaller matrix, as we can see in the example below.

    A scalar is just a special case of a matrix and its element size is 1x1. Square brackets are not needed to create a scalar variable. Also, a vector is a special case of a matrix with a single row or column. Square brackets without an element inside them create a null vector. We see examples of this in the code below:

    • u = [1 2 3]; %Produces a row vector
    • v = [1;2;3]; %Produces a column vector
    • X = []; %Produces a null vector

    Elements of a matrix can be all kinds of numeric datatypes, whether they are floating-point, integers, or imaginary numbers, as we will see in the next section. They can even be symbolic.

    DataTypes of MATLAB

    Every variable that is stored in the workspace of MATLAB has a datatype. It can be an in-built or default datatype or users can build their own datatypes depending on the purpose of the code.

    You can always find a datatype in MATLAB by using the 'class’ function.

    Numeric datatypes:

    Double:

    • This datatype takes 64 bits to store a number. This essentially represents a floating-point number, i.e., a decimal number with double precision, and can be positive or negative. You can use the function ‘double’ to declare the datatype when creating a variable, but double is the default datatype in MATLAB and whenever you call a command such as the one shown below, the number is stored as a double.
    • These variables can store values varying from between -1.79769 x 10308 and -2.22507 x 10-308 for the negative numbers and the range for positive numbers is between 2.22507 x 10-308 and 1.79769 x 10308 In situations where such large values of numbers are not needed, single-precision floating-point variable can be used.

    Single:

    1. When storing smaller numbers, it is better to use the single-precision floating-point numbers which vary between-3.4x10^38 and 3.4x10^38. This stores a variable in only 32 bits and helps to speed up the code. We use the function single in order to create this kind of variable.

    Integers:

    • MATLAB supports four types of signed integers and four types of unsigned integer datatypes, given by, int8, int16, int32, and in64 for the signed integers, and uint8, uint16, uint32 and uint64 for the unsigned integers. The number refers to the number of bits required to stored these integers and the range of allowed numbers is decided accordingly.

    Complex numbers:

    • You can create a complex number by using the ‘complex’ function or using the default symbol ‘i’ for the imaginary part of the complex variable. We can also extract the real and imaginary parts of the complex number using the ‘real’ and ‘imag’ functions on the complex number.

    Infinity and Nan:

    • Any number larger than the range given above is represented in MATLAB by the value ‘Inf’. Such a number can result when we divide by zero, which leads to results too large to represent as floating-point values and they end up being outside of the ranges discussed above. We can check if a variable is an infinity or not by using the function ‘isinf’ on it. Some numbers that can’t be represented by a real number such as the result of calculating ‘0/0’ or ‘inf/inf’ are called NaN, i.e., “Not a Number”. We can check if a variable is NaN or not by using the function ‘isnan’ on it.

    Logical:

    • These are variables that only have values of 0 and 1, and are the result of a comparison operation. An example of a result of comparing two matrices that gives a logical matrix as an output is shown below:

    Representation

    We can represent the output of a double in a shorter format which is easy to read or in a longer format which will help with learning about the accuracy of those double variables, using the commands below:
    • format short
    • format long

    Conversion of numeric datatypes:

    We can convert between double or single-precision numbers, as well as from floating-point to integers or vice versa using the functions described above which we use while declaring the numeric data type.

    Operations on numeric datatypes:

    Following is a list of operations on the numeric datatypes.

    • abs: to determine absolute and positive value of a signed or complex number.
    • Fix: round-off a floating point number towards 0. For example, fix([-2.1, 2.9]) = [-2, 2]
    • floor: round-off a floating point number towards –Inf. For example, floor([-2.1, 2.9]) = [-3, 2]
    • ceil: round-off a floating-point number towards +Inf. For example, ceil([-2.1, 2.9]) = [-2, 3] round: round-off a floating-point number towards the nearest integer. For example, round([-2.1, 2.9]) = [-2, 3]
    • Rem: Remainder after division of first argument by second argument. For example, rem(10,3)=1
    • Sign: signum function returns the sign of a number.

    Other datatypes:

    Characters/strings:

    • The character or string array is used to store text data in MATLAB.

    Single quotes are used to declare a character array. For example,

    A = ‘Hello World’ is a character vector.

    However, double quotes are used to declare a string. String is different from a character because individual parts of a character array can be accessed using indexing but the same is not true for strings.

    You can carry out the exercise shown below to understand this subtle difference.

    The various operations that can be performed on character array include:

    Cell matrix:

    • Just like matrices, a cell array is an indexed data container with each element known as a cell and can contain any type of data, including other cells and arrays which can be numeric or non-numeric types. Cells can be declared with curly braces, { } to let MATLAB know the input is a cell array. Individual cells inside a cell array can be called using round parentheses whereas contents at a location can be accessed by curly braces again, as shown in the example below:

    The function ‘cell2mat’ takes a cell as an argument and outputs a matrix. However, for this, all the elements of a cell array must be the same data type. This is what distinguishes Cell arrays from Matrices.

    Tables:

    • A table is a convenient data structure to write column-based or tabular datasets that can be stored in a text or spreadsheet file, or plotted easily as well. Tables let you access individual columns with variable names. Each variable can be a different datatype. The only restriction for different columns is for them to have the same number of rows. You can load the inbuilt tabular dataset inside MATLAB as shown below.

    Structures:

    • Structures are the most generic datatype in MATLAB which consist of indexed elements and each index can store a different datatype or in fact, a structure itself. Such structures are known as nested structures and the various branches of a nested structure can be accessed using the dot notation.

    Non-numeric datatypes also include function handles, symbolic variables and anonymous functions but they are a topic worth a separate lecture for discussion and will come up in the upcoming lectures.

    In further chapters, we will look at some of the applications of MATLAB in Linear algebra, look at different kinds of matrices inside MATLAB that are commonly used in a linear algebra class, and also work with input and output of data and functions using ‘m’ files as well as ‘mat’ files. We will also read about saving and loading operations, for input and output of data from MATLAB, and we will look further at making GUI in MATLAB, plotting linear, polar, 2D and 3D graphs with data sets.

    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