LCD Library for Proteus V2.0

Hi learners! I hope you are doing great. Today, I am going to share the second version(V2.0) of the LCD library for Proteus. We have already shared the LCD V1.0 Library on our blog. Along with appreciation, we also get some complaints/suggestions about that library. So, we have designed a better version of the LCD library by keeping the suggestions in mind.

Version 2.0 has error-free working, better pinout prints, and is identical to the real-world LCD. We have also removed our website link from the LCD. This library includes two alphanumeric LCDs in it i.e. LCD 16x2 and LCD 20x4.

If you don't have any experience with the LCD, no need to worry as we will guide you from scratch. Before installing the LCD, let's first have a look at its brief introduction:

Where To Buy?
No.ComponentsDistributorLink To Buy
1Battery 12VAmazonBuy Now
2ResistorAmazonBuy Now
3LCD 16x2AmazonBuy Now
4LCD 20x4AmazonBuy Now
5PIR SensorAmazonBuy Now
6Arduino UnoAmazonBuy Now

What is Liquid Crystal Display?

  • A liquid crystal display or LCD is a flat board of liquid crystals that are sandwiched between polarizers. When the electric field is applied to it, this material rotates according to the polarization and allows the light to pass through it. As a result, the display is shown on the LCD board.
  • A simple 16x2 LCD is shown in the below figure:
  • The LCD is used in electrical/electronic projects to display sensors' data, statuses, alerts, notifications etc.
  • We can interface this LCD with any microcontroller i.e. Arduino, PIC, Atmel, Raspberry Pi, STM32 etc.
  • Some of the advantages are low power consumption, durability, and long life.

Let's have a look at the pinout of LCD:

LCD Pinout

Both of these LCDs(16x2 and 20x4) have similar pinouts and a simple basic circuit needs to be designed in order to operate them. There are a total of 16 pins present in LCD used for different purposes. The below table has the complete description of LCD Pinout:

Serial

Pin

Functionality

Description

1

VSS

Ground

This pin is connected to the ground terminal of the circuit. 

2

VDD

Power Supply

It is connected to the positive voltage(+5V) and is responsible for the power supply to all pins. 

3

VEE

Voltage Emitter

It is used to control the contrast of LCD. it applies the negative voltage and thus controls the electric field of the LCD. 

4

RS

Register Select

It selects the LCD register. LCD has two registers: an instruction register and a data register. 

5

RW

Read or write

The read-and-write operation is done through this pin. if set to HIGH then LCD is in reading mode and LOW means it is writing the data. 

6

E

Enable

Enables the working of LCD. If HIGH then allow the display and if LOW then disable it.

7-14

D0-D7

Data bits (Pins to deal with the data)

Data is sent to the LCD in a parallel manner. These pins send this data and out of these, D0 is the least significant and D7 is the most significant.

LCD Library For Proteus

The installation of the LCD V2.0 is simple. The first step is to download the library files. I believe you have Proteus installed. So, click the below button to download the Proteus Library zip file.

LCD Library for Proteus V2.0

Adding Proteus Library Files

  • Once downloaded, go to the file location and extract content from the zip file.
  • Open the folder named "Proteus Library Files" and here you will find two library files in it, named:
  • LCDLibraryTEPV2.0.IDX
  • LCDLibraryTEPV2.0.LIB
  • Simply copy these files in the Library folder of Proteus software. Go to your C drive>Program Files>LabCentre Electronics>Proteus Professional> Library.
  • If you are having any difficulty installing the library, you should a look at How to install a new Library in Proteus.

The zip file also contains the project, where we simply connected both the LCDs with Arduino, so that you could check their working. Moreover, code is also present in the file.

LCD V2.0 in Proteus

Once the Library is installed, you need to open your Proteus software. If it's already open, you have to restart it. Now follow the instructions.

  • Go to the pick library by clicking on the “P” button.
  • In the dialogue box, type "LCD TEP" and you will get the below results:

I have installed both versions therefore, I am getting four options. I will choose the LCD 20X4 V2.0 and LCD 16X2 V2.0.

  • Click on the components and simply place them on the working sheet of Proteus, it will appear as shown below:

  • I hope you guys will enjoy this new look without the site's link.

Now, let's design an LCD simulation in Proteus:

LCD Simulation in Proteus

Now, let's design a simple LCD simulation, where we will interface it with an Arduino UNO board. We will display our website's link on the LCD. So, let's design the circuit:

Interfacing LCD with Arduino

Go to the pick library and select the following components:

  1. LCD 20X4
  2. LCD 16X2
  3. Arduino
  4. POT-HG
  • Place the Arduino and other components in the working area, as shown in the below image:
  • Go to Terminal mode and select the Power & Ground terminal for both LCDs.
  • In order to design a neat circuit, I have connected the “Default” terminal with each pin, instead of wires.
  • The complete circuit diagram is shown in the below figure:

Now let's design the Arduino code to display data on these LCDs:

Arduino Code for LCD Simulation

Now, open your Arduino software, I hope you have it installed. Paste the below code in it, I have also added this code in the zip file.

#include

// initialize the library with the numbers of the interface pins

LiquidCrystal lcd(13, 12, 11, 10, 9, 8);

void setup() {

  // set up the LCD's number of columns and rows:

  lcd.begin(16, 2);

  // Print a message to the LCD.

  lcd.setCursor(1,0);

  lcd.print("www.TheEngineering");

  lcd.setCursor(4,1);

  lcd.print("Projects.com");

}

void loop() {

}

Add HEX File in Proteus

The next step is to get the Hex File from Arduino IDE and add in the Proteus. For this, follow these steps:

  • Verify the Arduino Code by clicking the "Verify" button and the output pane will give the location to the hex file, as shown in the below figure:
  • In the proteus software, double-click on the Arduino board to open its Properties Panel.
  • Paste the HEX file in the program file section and press OK.

LCD Simulation Results

  • Now, the LCD simulation is ready to run.
  • You can see in the code, we have printed the TEP link on the LCD screen.
  • Once you play the circuit, the LCDs will display the message, as shown in the below figure:

If you have followed all the steps, I am sure your project will run successfully. I hope it was helpful to you. You must practice it more and try to make different projects. So, that was all for today, will meet you guys in the next tutorial. Take care!!!

Raspberry Pi 2 Library for Proteus

Hello friends, I hope you all are having fun. In today's tutorial, I am going to share a new Proteus library for Raspberry Pi 2. We have already shared the Proteus Libraries of other Raspberry Pi modules i.e. Raspberry Pi 4, 3, Pico etc. and we discussed that these Pi modules won't be able to read the Python code. We have just designed the external appearance of these modules and you can use these Pi modules for circuit designing and project presentations.

We have also added the Arduino firmware in these boards, which is just to provide a bit of interaction with these boards. We have given these boards an unofficial title "Arduino Pi".

So, let's have a look at How to simulate Raspberry Pi in Proteus:

Where To Buy?
No.ComponentsDistributorLink To Buy
1Battery 12VAmazonBuy Now
2LEDsAmazonBuy Now
3ResistorAmazonBuy Now
4LCD 16x2AmazonBuy Now
5LCD 20x4AmazonBuy Now
6PIR SensorAmazonBuy Now

Raspberry Pi 2 Library for Proteus

  • First of all, we need to download the Proteus Library zip file of Raspberry Pi 2, by clicking the below button:

Raspberry Pi 2 Library for Proteus

Adding Proteus Library Files

  • Extract files from the Proteus Library zip file and open the folder named "Proteus Library Files".
  • Here you will find two library files, named:
    • RaspberryPi2TEP.IDX
    • RaspberryPi2TEP.LIB
  • We need to place these files in the Library folder of the Proteus software, normally at C > Program Files > Labcenter Electronics > Proteus 8 > Library.

Note: For a better understanding, you should read How to Add a New Library File in Proteus.

Raspberry Pi 2 in Proteus

  • We have successfully added the library files in the last step. So, now is the time to open your Proteus software.
  • Open the Components search box by clicking the "P" button in Proteus and here make a search for Raspberry Pi 2.
  • If you have added the library correctly, you will get the below result:

  • Add it to your project by double-clicking on it.
  • Place the Raspberry Pi 2 modules in your Proteus workspace, as shown in the below figure:

Note: Its design is quite similar to that of Raspberry Pi 3, although we added the name to differentiate between the two.

Raspberry Pi 2 Simulation in Proteus

As mentioned above, this Pi board won't be able to read the Python code. So, we have added the Arduino firmware in it to make it a bit more interactive. So, let's blink an LED with this Raspberry Pi 2 module in Proteus:

LED with Raspberry Pi 2

  • Before working on the code, let's first design the circuit diagram and as you can see in the below figure, I have connected an LED along with a resistor to Pin # 13 of the Pi board:

  • In the properties panel of LED, change the Model Type of LED from analog to digital.

Code for Raspberry Pi 2

  • As it has Arduino firmware, so we need to get its hex file.
  • So, open Arduino IDE and from Examples, open the LED blink code.
  • Compile the code and get its hex file, as shown in the below figure:

Add Hex File in Proteus

  • Open the Properties PAnel of Raspberry Pi 2 and here you will find an option "Program File".
  • Paste the Hex File location in its text box, as shown in the below figure:

  • Click Ok to close the Properties PAnel and now its time to run the Raspberry Pi 2 simulation:

Raspberry Pi 2 Simulation Results

  • Click the Play Button in Proteus to run the simulation and if everything goes fine, the LED will start blinking, as shown in the below figure:

So, that was all for today. I hope you have enjoyed these Raspberry Pi simulated modules. IF have any questions, please ask in the comments. Thanks for reading.

Sending SMS & Call with GSM Module and Raspberry Pi 4

Greetings, and welcome to another tutorial in our series on the raspberry pi 4 Python programming. The previous guide covered the basics of transmitting data over the radio using the nrf24l01 chip in Pi 4. We also learned about interfacing Arduino and raspberry pi 4 and sending radio signals between the two devices. However, this tutorial will walk you through building a Raspberry Pi-based mobile phone with a microphone and speaker for making and receiving calls and reading text messages (SMS). This Project also serves as a proper GSM Module for the Raspberry Pi interface, with all the necessary Code to run the most fundamental features of any modern smartphone. First, we will understand what gsm is, its architecture and how it works, then we will learn how to program it in our pi 4; therefore, let us begin.

Where To Buy?
No.ComponentsDistributorLink To Buy
1Jumper WiresAmazonBuy Now
2LCD 16x2AmazonBuy Now
3Raspberry Pi 4AmazonBuy Now

Components:

  • Raspberry Pi 4

  • GSM Module

  • 16x2 LCD

  • 4 *4 Keypad

  • 10k pot

  • Breadboard

  • Connecting jumper wire

  • Power supply

  • Speaker

  • Microphone

  • SIM Card

  • Loudspeaker

Structure and Uses of the Global System for Mobile Communications

The acronym "GSM" refers to the "global system for mobile communication" and is the name of a type of mobile communication modem (GSM). Bell Labs was responsible for conceptualizing GSM in the 1970s. It's one of the most common forms of mobile communication around the globe. The 850MegaHertz, 900MegaHertz, 1800 Megahertz, and 1900 Megahertz frequency bands are utilized by GSM networks, which are part of an open and digital mobile network used to carry voice and data services.

Using the telecommunications method of multiple time division access (TDMA), GSM technology was created as a digital system. For transmission, a GSM converts analog signals to digital ones, compresses them further and delivers them through a channel sharing bandwidth with two data streams from separate clients. The data rates transported by the digital system range from 64 kilobytes per second to 120 Megabytes per second.

In a GSM network, macro, micro, and umbrella cells coexist. The implementation context determines the specifics of each cell. The macro, micro, and umbrella cell sizes are in use in a GSM network. Each cell may have a different range of coverage depending on the setting.

Time-division multiple access (TDMA) works by giving each user a specific amount of time to transmit on the same frequency. It's flexible, supporting data rates from 64kbps to 120Mbps and allowing for clear voice communications.

Structure of GSM-Based Technologies

The following are the primary components of the GSM architecture.

  • Connectivity and Switching Infrastructure (NSS)

  • All three of these components—the Base Station (BS), the Mobile Station (MS), and the Operations and Maintenance Subsystem (OSS)—are necessary for proper communication (OSS)

Network Switching Subsystem (NSS)

Each component of the GSM system design contributes to what is collectively called the core system/network. In this case, the mobile network system is primarily controlled and interfaced with via a data network consisting of several different components. Listed below are some of the most crucial elements of the underlying network.

Mobile Switching Centre (MSC)

One of the essential parts of a GSM network is its core network, where the Mobile Switching Center (MSC) resides. This MSC performs the same functions as a common switching node in an ISDN or PSTN. Still, it provides additional features to accommodate mobile users' requirements, such as authentication, registration, inter-MSC handovers, call localization, and routing.

In addition, it gives users an advantage in connecting their mobile phone networks to the PSTN (public switched telephone network) for making and receiving landline calls. To facilitate mobile-to-mobile calls across different networks, interfaces to all other switched telephone networks ( PSTN center servers are given.

Home Location Register (HLR)

Every subscriber's administrative details, including their last known location, are stored in this HLR database. This manner, calls can be routed over the GSM network to the appropriate mobile switch base station. If a call comes in when an operator has their phone turned on, the network can determine which base transmitter station the call is coming from and link it to the correct phone.

When the phone is turned on but not being used, it nevertheless registers to ensure the HLR system is aware of its current location. Each network has a single HLR, which may be physically split across several data centers for practical reasons.

Visitor Location Register (VLR)

To facilitate the VLR's desired services for the individual subscriber, it incorporates data from the HLR network. It is possible to run the visitor coordinates register independently, but it is most commonly implemented as a core component of the MSC. Because of this, getting access is more manageable, and it takes less time overall.

Equipment Identity Register (EIR)

The Equipment Identity Register (EIR) is the part of the network infrastructure in charge of deciding whether or not certain pieces of mobile equipment are allowed access. The International Mobile Equipment Identification (IMEI) numbers uniquely identify each mobile technology work.

This IMEI number is permanently embedded within the mobile device and checked by the network after registration. Depending on the data in the EIR, the mobile phone may be given one of three possible network access states: allowed, banned, or monitored.

Authentication Centre (AuC)

When users insert their SIM card into their phone, the secret key is stored in a secure file known as the AUC (authentication center). The AUC sees the extensive application as a radio channel coding and verification standard.

Gateway Mobile Switching Centre (GMSC)

In the absence of location information for the mobile station (MS), a call placed by a ME terminates with the GMSC (Gateway Mobile Switching Centre). Using the Mobile Subscriber Identifier Service Data Number (MSISDN) and the HLR, the GMSC can locate the specific MSC that has been visited and connect the call to the appropriate location. It's unclear what the "MSC" part of GMSC stands for, as the gateway procedure does not require relating to an MSC.

SMS Gateway (SMS-G)

Both SMS-Gateways are referred to collectively as the SMS gateway in the GSM specifications. The messages passing via these gateways are directed in various ways.

Sending a short message to mobile equipment (ME) requires the usage of the Short Messaging Service Gateway Switching Center. Short messages sent over a mobile network are routed through the  SMS Inter-Working Switching Center. While the SMS-primary GMSC's function concerns the GMSC, the SMS-IWMSC serves as a constant endpoint for access to the Short Message Service Centre.

These were the primary nodes in the GSM system's infrastructure. While they frequently shared physical space, the entire middle network would sometimes be broadcast throughout the country. In the event of a failure, it will provide a degree of leeway.

Base Station Subsystem (BSS)

The connection point between the mobile node and the broader network infrastructure. The radio transceivers and protocol management for mobile devices are housed in the Base Transceiver Station. In addition, a Base Station Controller manages the Base Transceiver and serves as a bridge between mobile devices and the mobile switching hub.

The network subsystem handles connectivity between the network and the mobile stations. The Phone Service Switch Centre is the backbone of the Network Subsystem, allowing users to connect to other networks (ISDN, PSTN, etc.). The GSM system's ability to route calls and allow for roaming depends on two additional components, the Home Location Record and the guest Location Record.

In addition, it stores the Equipment Identity Register, which keeps track of all the mobile devices and their associated IMEI numbers. The acronym IMEI refers to the unique identifier for mobile devices worldwide.

In the second generation of GSM network design, the mobile devices communicate with the BSS, or Base Station Subsystem. These components comprise this subsystem, and each will be examined.

Base Transceiver Station (BTS)

As part of a GSM network, the radio Tx, Rx, and their associated antennas make up the base Transceiver Station, which is used for transmitting, receiving, and communicating directly through mobiles. The base station is the central component of each cell, and it communicates with mobile devices using an interface known as the Um interface and related protocols.

Base Station Controller (BSC)

The base station controller (BSC) is employed for the following step back into GSM technology. This controller is typically co-located within one of the base transceiver stations it controls. This controller handles radio resource management, including channel allocation and handover between base station groups. Over the Abis interface, it communicates with the BTSs.

The acceptable radio technology is used by the GSM network's subsystems component in the ground station to ensure that multiple operators can utilize the system at the same time. Each base station can support many operators because each channel can support up to eight users.

The network provider strategically places these to ensure comprehensive coverage. A base station, sometimes known as a "cell," can surround this space. Signals can't be prevented from bleeding into neighbouring cells, and the channels used in one don't transfer to the next.

Mobile Station

Mobile phones include a transceiver, a display, and a CPU, all of which are network-connected and operated using a SIM card. In a GSM mobile transmission medium, the operator monitors and controls the mobile station or mobile equipment, which are most commonly represented by cell phones. Their size has shrunk significantly while their functionality has skyrocketed. The benefit of a much longer interval between charges is still another advantage. Phone hardware and the subscriber identity module (SIM) are two of many components.

A mobile device's hardware consists of its primary components, such as the housing, screen, battery, and electronics used to generate the signal and process the signal receiver before transmission. The IMEI is a unique number assigned to each mobile device. This feature can be permanently programmed into a phone throughout its manufacturing process. During the registration process, the network accesses this database to see if the device has been flagged as stolen.

A user's identity on the network is stored in the information contained in their SIMcard. It also includes other data, such as the IMSI number. With this IMSI stored in the Sim, the phone user could easily switch phones by swapping SIM cards. As a result, if switching to a new mobile phone were simple and didn't require a unique phone number, more people would do it, generating more revenue for network operators and contributing to GSM's overall economic triumph.

Operation and Support Subsystem (OSS)

The OSS is an integral aspect of any functional GSM network. The NSS and BSC parts are linked here. The GSM network and BSS traffic load are the primary areas of focus for this OSS. It is worth noting that some preservation responsibilities are relocated to the base station controller to lower the maintenance expense of the system when the amount of BS increases through the consumer population growth.

The 2G GSM network architecture is predicated on a rational functioning method. This approach is remarkably straightforward compared to today's mobile network architectures, which rely on software-defined units to facilitate highly adaptable operations. However, the 2G GSM architecture will show how the necessary voice and essential operational functions are organized. 

Specifications of a GSM Module

The following are some of the functions provided by the GSM module.

  • Enhanced spectrum efficiency

  • Features including "international roaming," "integrated services digital network" (ISDN) compatibility, and "support for future services" are also included.

  • High-quality voice communications; encrypted phone conversations;

  • Features like a programmable alarm clock, high-quality voice communication, a fixed calling number, a real-time clock, and the ability to send and receive SMS messages are all standard on modern smartphones (SMS)

As a result of its rigorous security measures, the GSM system is currently the safest available for use in the telecommunications industry. Call privacy and subscriber anonymity for GSM users are only protected during transmission, but this is still a massive step toward attaining end-to-end security.

GSM Modem

In either its mobile phone or modem form, a Global System for Mobile Communications (GSM) modem enables two computers or processors to connect across a network. A SIM card is needed to run a GSM modem, and it can only be used within the coverage area the network provider has paid for. It has serial, USB, and Bluetooth connectivity options for linking to a personal computer.

Any regular GSM cell phone can double as a GSM modem if you have a suitable cable and driver installed on your PC. It would be best if you used a GSM modem instead of a GSM cell phone. The GSM modem is helpful in many devices, including POS terminals, inventory management systems, surveillance cameras, weather stations, and GPRS-mode remote data loggers.

GSM Module Operation

Below is a circuit showing how to connect a GSM modem to the MC using the level-shifting IC Max232. When a numeric command is received by short message service (SMS) from any mobile device, the SIM card-mounted GSM modem transfers that information to the MC via serial connection. The GSM modem is programmed to respond to the order "STOP" by producing an MC output, the point which is utilized to deactivate the ignition switch.

If the input is driven low, the GSM modem will send a predetermined message (in this case, "ALERT") to the user. A 162 LCD screen displays the entirety of the procedure.

In-depth working Explanation of raspberry pi 4

We have utilized a GSM module and a Raspberry Pi 4 to manage the entire system and interface its many parts in this Project. You can input data of any kind, including phone numbers, text messages, and phone calls, read and respond to text messages, and more, using a 4x4 alphanumeric keypad. The SIM900A GSM module connects mobile phones to wireless networks for making and receiving calls and sending and receiving text messages. We've integrated a microphone, a loudspeaker for making and receiving voice calls, and a 16 * 2 liquid crystal displays information like menu options and alarms.

With alphanumeric input, you can use the same keyboard to type in both numbers and letters. For the Code we used to allow alphabets in addition to numbers in this method, scroll down to the "Code in Code" section.

It's simple to put this plan into action. The alphanumeric keypad is used for all functions. Below you'll find a link to the complete Code and a demonstration video. This section will elaborate on the four aspects of the listed projects.

The Pi 4 Mobile Phone Four Main Attributes

Make Call

The Pi 4 phone we built requires us to press the letter "C" and provide the cellphone number we wish to call. We'll use an alphanumeric keyboard to enter the number. Once the correct number has been entered, we must hit "C" again. The AT command is now processed by pi 4 to connect the call to a specified number.

ATDxxxxxxxxxx; <Enter>     where xxxxxxxxx is entered Mobile Number.

Receive Call

Answering a phone call is simple. When a call comes into the SIM number stored in the GSM Module of your system, the LCD will display the message "Incoming..." along with the caller's number. All that's left to do is hit the 'A' key to answer the call. Pi 4 will send the following command to the GSM Module when the "A" button is pressed:

ATA <enter>

Transmit SMS

Pressing "D" on our Raspberry Pi phone allows us to send a text message. To whom (or what) should we address the SMS message that the system has just requested? Once the number has been entered, pressing "D" again will prompt the LCD to request a message. To send an SMS, enter the message using the keypad as you would with any other mobile device, and then hit the 'D' key again. Raspberry Pi can send SMS with the following command:

AT+CMGF=1 <enter>

AT+CMGS=”xxxxxxxxxx” <enter>     where: xxxxxxxxxx is entered mobile number

Receive and Read SMS

Even this component is easy to use. Here, the SIM card is used to receive SMS messages from the GSM. The Raspberry Pi also keeps a close eye on the UART SMS signal. New notes are shown by the LCD displaying the text "New message," and reading them is as simple as pressing the "B" key. This is an SMS Received signal:

+CMTI: "SM," 6  Where 6 is the message location where it is stored in the SIM card.

When the RPi detects the 'SMS received' signal, it will get the SMS storage location and instruct the Global system for mobile to read the message. Moreover, the LCD will flash the words "New Message" in a prominent location.

AT+CMGR=<SMS stored location><enter>

The GSM now delivers the saved message to the Raspberry Pi, and the Pi, having extracted the primary SMS, shows it on the LCD. When it comes to MIC and Speaker, there is no secret code.

Detailed Circuit Layout and Explanation

The GPIO pins of the Raspberry Pi are wired to the RS, EN, D4, D5, D6, and D7 pins of the 16 * 2 liquid crystal display. A direct connection is made between the GSM module's Rx and Tx pins and the Raspberry Pi's Tx and Rx pins. Connectors R1, R2, R3, and R4 of a 4 * 4 keypad are connected to GPIOs 12, 16, 20, and 21, whereas pins C1, C2, C3, and C4 are connected to GPIOs 26, 19, 13, and 6. If you want to boost the audio volume from the GSM Module, you can join the microphone directly to the mic+ and mic- pins and the loudspeaker to the sp+ and sp- pins. The loudspeaker can be connected directly to the GSM module without using the Audio Amplifier circuit.

Explanation of the Code

This Pi 4 mobile phone's programming interface may be challenging to novices—the programming language of choice for this Project is Python.

Here, we define the keypad() function to be used with a basic numeric keypad. We've also added a def alpha keypad(): for typing alphabets so that you may use the same keypad for both purposes. To make it compatible with the Arduino keypad library, we've given this keypad a wide range of new capabilities. This keypad only takes 10 presses to enter a whole string of text or a numeric value.

For example, if we push key 2 (abc2) once, the LCD will display the letter 'a.' If we press it again, the letter 'b' will take its place, and if we hit it three more times, the letter 'c' will appear in the same spot. After holding down a key for a short time, the LCD pointer will advance to the following available location. We can now proceed to the next character or number. Any other keys can be processed in the same way.

def keypad():

   for j in range(4):

     gpio.setup(COL[j], gpio.OUT)

     gpio.output(COL[j], 0)

     ch=0

     for i in range(4):

       if gpio.input(ROW[i])==0:

         ch=MATRIX[i][j]

         return ch

         while (gpio.input(ROW[i]) == 0):

           pass

     gpio.output(COL[j],1)

def alphaKeypad():

    lcdclear()

    setCursor(x,y)

    lcdcmd(0x0f)

    msg=""

    while 1:

        key=0

        count=0

        key=keypad()

        if key == '1':

            ind=0

            maxInd=6

            Key='1'

            getChar(Key, ind, maxInd)

            .... .....

            ..... .....

To begin, we have declared the pins for the liquid crystal display, the keypad, and other components, as well as included the necessary libraries in this python script:

import RPi.GPIO as gpio

import serial

import time


msg=""

alpha="1!@.,:?ABC2DEF3GHI4JKL5MNO6PQRS7TUV8WXYZ90 *#"

x=0

y=0


MATRIX = [

            ['1','2','3','A'],

            ['4','5','6','B'],

            ['7','8','9','C'],

            ['*','0','#','D']

         ]

ROW = [21,20,16,12]

COL = [26,19,13,6]

... .....

..... .....

The pins need to be pointed in the proper direction.

gpio.setwarnings(False)

gpio.setmode(gpio.BCM)

gpio.setup(RS, gpio.OUT)

gpio.setup(EN, gpio.OUT)

gpio.setup(D4, gpio.OUT)

gpio.setup(D5, gpio.OUT)

gpio.setup(D6, gpio.OUT)

gpio.setup(D7, gpio.OUT)

gpio.setup(led, gpio.OUT)

gpio.setup(buz, gpio.OUT)

gpio.setup(m11, gpio.OUT)

gpio.setup(m12, gpio.OUT)

gpio.setup(button, gpio.IN)

gpio.output(led , 0)

gpio.output(buz , 0)

gpio.output(m11 , 0)

gpio.output(m12 , 0)

To begin Serial communication, follow the steps below.

Serial = serial.Serial("/dev/ttyS0", baudrate=9600, timeout=2)

We must now create a liquid crystal display driving function. The def lcdcmd(ch): and def lcdwrite(ch): functions are used to deliver commands and data to the LCD, respectively. The liquid crystal display may also be cleared with def lcdclear(), the cursor position can be set with def setCursor(x,y), and a string can be sent to the liquid crystal display with def lcdprint(Str).

def lcdcmd(ch): 

  gpio.output(RS, 0)

  gpio.output(D4, 0)

  gpio.output(D5, 0)

  gpio.output(D6, 0)

  gpio.output(D7, 0)

  if ch&0x10==0x10:

    gpio.output(D4, 1)

    .... .....

    ..... ....

def lcdwrite(ch): 

  gpio.output(RS, 1)

  gpio.output(D4, 0)

  gpio.output(D5, 0)

  gpio.output(D6, 0)

  gpio.output(D7, 0)

  if ch&0x10==0x10:

    gpio.output(D4, 1)

  if ch&0x20==0x20:

    gpio.output(D5, 1)

    .... .....

    ..... ....

def lcdclear():

  lcdcmd(0x01)

 

def lcdprint(Str):

  l=0;

  l=len(Str)

  for i in range(l):

    lcdwrite(ord(Str[i]))

def setCursor(x,y):

    if y == 0:

        n=128+x

    elif y == 1:

        n=192+x

    lcdcmd(n)

Next, we'll need to code some features for interacting with text messages, phone calls, and incoming calls.

The call is placed using the function def call():. Also, the LCD can display the receiving message and number via the function def receiveCall(data):. Finally, the call is answered with def attendCall():.

The message is composed and sent using the alphaKeypad() method, accessed via the def sendSMS(): function. The SMS is received, and its location is retrieved using the def receive SMS(data) function. And finally, the LCD gets updated with the message thanks to def readSMS(index:).

All of the operations mentioned above are included in the Code that follows.

import RPi.GPIO as gpio

import serial

import time

msg=""

#     0      7   11  15  19  23  27   32  36   414244   ROLL45

alpha="1!@.,:?ABC2DEF3GHI4JKL5MNO6PQRS7TUV8WXYZ90 *#"

x=0

y=0

MATRIX = [

            ['1','2','3','A'],

            ['4','5','6','B'],

            ['7','8','9','C'],

            ['*','0','#','D']

         ]

ROW = [21,20,16,12]

COL = [26,19,13,6]

moNum=['0','0','0','0','0','0','0','0','0','0']

m11=17

m12=27

led=5

buz=26

button=19

RS =18

EN =23

D4 =24

D5 =25

D6 =8

D7 =7

HIGH=1

LOW=0

gpio.setwarnings(False)

gpio.setmode(gpio.BCM)

gpio.setup(RS, gpio.OUT)

gpio.setup(EN, gpio.OUT)

gpio.setup(D4, gpio.OUT)

gpio.setup(D5, gpio.OUT)

gpio.setup(D6, gpio.OUT)

gpio.setup(D7, gpio.OUT)

gpio.setup(led, gpio.OUT)

gpio.setup(buz, gpio.OUT)

gpio.setup(m11, gpio.OUT)

gpio.setup(m12, gpio.OUT)

gpio.setup(button, gpio.IN)

gpio.output(led , 0)

gpio.output(buz , 0)

gpio.output(m11 , 0)

gpio.output(m12 , 0)

for j in range(4):

    gpio.setup(COL[j], gpio.OUT)

    gpio.setup(COL[j],1)

for i in range (4):

    gpio.setup(ROW[i],gpio.IN,pull_up_down=gpio.PUD_UP)

Serial = serial.Serial("/dev/ttyS0", baudrate=9600, timeout=2)

 

data=""

def begin():

  lcdcmd(0x33) 

  lcdcmd(0x32) 

  lcdcmd(0x06)

  lcdcmd(0x0C) 

  lcdcmd(0x28) 

  lcdcmd(0x01) 

  time.sleep(0.0005)

def lcdcmd(ch): 

  gpio.output(RS, 0)

  gpio.output(D4, 0)

  gpio.output(D5, 0)

  gpio.output(D6, 0)

  gpio.output(D7, 0)

  if ch&0x10==0x10:

    gpio.output(D4, 1)

  if ch&0x20==0x20:

    gpio.output(D5, 1)

  if ch&0x40==0x40:

    gpio.output(D6, 1)

  if ch&0x80==0x80:

    gpio.output(D7, 1)

  gpio.output(EN, 1)

  time.sleep(0.005)

  gpio.output(EN, 0)

  # Low bits

  gpio.output(D4, 0)

  gpio.output(D5, 0)

  gpio.output(D6, 0)

  gpio.output(D7, 0)

  if ch&0x01==0x01:

    gpio.output(D4, 1)

  if ch&0x02==0x02:

    gpio.output(D5, 1)

  if ch&0x04==0x04:

    gpio.output(D6, 1)

  if ch&0x08==0x08:

    gpio.output(D7, 1)

  gpio.output(EN, 1)

  time.sleep(0.005)

  gpio.output(EN, 0)

def lcdwrite(ch): 

  gpio.output(RS, 1)

  gpio.output(D4, 0)

  gpio.output(D5, 0)

  gpio.output(D6, 0)

  gpio.output(D7, 0)

  if ch&0x10==0x10:

    gpio.output(D4, 1)

  if ch&0x20==0x20:

    gpio.output(D5, 1)

  if ch&0x40==0x40:

    gpio.output(D6, 1)

  if ch&0x80==0x80:

    gpio.output(D7, 1)

  gpio.output(EN, 1)

  time.sleep(0.005)

  gpio.output(EN, 0)

  # Low bits

  gpio.output(D4, 0)

  gpio.output(D5, 0)

  gpio.output(D6, 0)

  gpio.output(D7, 0)

  if ch&0x01==0x01:

    gpio.output(D4, 1)

  if ch&0x02==0x02:

    gpio.output(D5, 1)

  if ch&0x04==0x04:

    gpio.output(D6, 1)

  if ch&0x08==0x08:

    gpio.output(D7, 1)

  gpio.output(EN, 1)

  time.sleep(0.005)

  gpio.output(EN, 0)

def lcdclear():

  lcdcmd(0x01)

def lcdprint(Str):

  l=0;

  l=len(Str)

  for i in range(l):

    lcdwrite(ord(Str[i]))

def setCursor(x,y):

    if y == 0:

        n=128+x

    elif y == 1:

        n=192+x

    lcdcmd(n)

def keypad():

   for j in range(4):

     gpio.setup(COL[j], gpio.OUT)

     gpio.output(COL[j], 0)

     ch=0

     for i in range(4):

       if gpio.input(ROW[i])==0:

         ch=MATRIX[i][j]

         #lcdwrite(ord(ch))

        # print "Key Pressed:",ch

        # time.sleep(2)

         return ch

         while (gpio.input(ROW[i]) == 0):

           pass

     gpio.output(COL[j],1)

    # callNum[n]=ch

def serialEvent():

    data = Serial.read(20)

    #if data != '\0':

    print data

    data=""

def gsmInit():

    lcdclear()

    lcdprint("Finding Module");

    time.sleep(1)

    while 1:

        data=""

        Serial.write("AT\r");

        data=Serial.read(10)

        print data

        r=data.find("OK")

        if r>=0:

            break

        time.sleep(0.5)

    while 1:

        data=""

        Serial.write("AT+CLIP=1\r");

        data=Serial.read(10)

        print data

        r=data.find("OK")

        if r>=0:

            break

        time.sleep(0.5)

    lcdclear()

    lcdprint("Finding Network")

    time.sleep(1)

    while 1:

        data=""

        Serial.flush()

        Serial.write("AT+CPIN?\r");

        data=Serial.read(30)

        print data

        r=data.find("READY")

        if r>=0:

            break

        time.sleep(0.5)

    lcdclear()

    lcdprint("Finding Operator")

    time.sleep(1)

    while 1:

        data=""

        Serial.flush()

        Serial.read(20)

        Serial.write("AT+COPS?\r");

        data=Serial.read(40)

        #print data

        r=data.find("+COPS:")

        if r>=0:

            l1=data.find(",\"")+2

            l2=data.find("\"\r")

            operator=data[l1:l2]

            lcdclear()

            lcdprint(operator)

            time.sleep(3)

            print operator

            break;

        time.sleep(0.5)

    Serial.write("AT+CMGF=1\r");

    time.sleep(0.5)

   # Serial.write("AT+CNMI=2,2,0,0,0\r");

   # time.sleep(0.5)

    Serial.write("AT+CSMP=17,167,0,0\r");

    time.sleep(0.5)

def receiveCall(data):

        inNumber=""

        r=data.find("+CLIP:")

        if r>0:

            inNumber=""

            inNumber=data[r+8:r+21]

            lcdclear()

            lcdprint("incoming")

            setCursor(0,1)

            lcdprint(inNumber)

            time.sleep(1)

            return 1

def receive SMS(data):

    print data

    r=data.find("\",")

    print r

    if r>0:

        if data[r+4] == "\r":

            smsNum=data[r+2:r+4]

        elif data[r+3] == "\r":

            smsNum=data[r+2]

        elif data[r+5] == "\r":

            smsNum=data[r+2:r+5]

        else:

            print "else"

        print smsNum

        if r>0:

            lcdclear()

            lcdprint("SMS Received")

            setCursor(0,1)

            lcdprint("Press Button B")

            print "AT+CMGR="+smsNum+"\r"

            time.sleep(2)

            return str(smsNum)

    else:

        return 0

def attendCall():

    print "Attend call"

    Serial.write("ATA\r")

    data=""

    data=Serial.read(10)

    l=data.find("OK")

    if l>=0:

        lcdclear()

        lcdprint("Call attended")

        time.sleep(2)

        flag=-1;

        while flag<0:

            data=Serial.read(12);

            print data

            flag=data.find("NO CARRIER")

            #flag=data.find("BUSY")

            print flag

        lcdclear()

        lcdprint("Call Ended")

        time.sleep(1)

        lcdclear()

def readSMS(index):

                print index

                Serial.write("AT+CMGR="+index+"\r")

                data=""

                data=Serial.read(200)

                print data

                r=data.find("OK")

                if r>=0:

                    r1=data.find("\"\r\n")

                    msg=""

                    msg=data[r1+3:r-4]

                    lcdclear()

                    lcdprint(msg)

                    print msg

                    time.sleep(5)

                    lcdclear();

                    smsFlag=0

                    print "Receive SMS"

def getChar(Key, ind, maxInd):

            ch=0

            ch=ind

            lcdcmd(0x0e)

           Char=''

            count=0

 

            global msg

            global x

            global y

            while count<20:

                key=keypad()

                print key

                if key== Key:

                    setCursor(x,y)

                    Char=alpha[ch]

                    lcdwrite(ord(Char))

                    ch=ch+1

                    if ch>maxInd:

                        ch=ind

                    count=0

                count=count+1

                time.sleep(0.1)

            msg+=Char

            x=x+1

            if x>15:

                x=0

                y=1

            lcdcmd(0x0f)

 

def alphaKeypad():

    lcdclear()

    setCursor(x,y)

    lcdcmd(0x0f)

    msg=""

    while 1:

        key=0

        count=0

        key=keypad()

        if key == '1':

            ind=0

            maxInd=6

            Key='1'

            getChar(Key, ind, maxInd)

        elif key == '2':

            ind=7

            maxInd=10

            Key='2'

            getChar(Key, ind, maxInd)

        elif key == '3':

            ind=11

            maxInd=14

            Key='3'

            getChar(Key, ind, maxInd)

        elif key == '4':

            ind=15

            maxInd=18

            Key='4'

            getChar(Key, ind, maxInd)

        elif key == '5':

            ind=19

            maxInd=22

            Key='5'

            getChar(Key, ind, maxInd)

        elif key == '6':

            ind=23

            maxInd=26

            Key='6'

            getChar(Key, ind, maxInd)

        elif key == '7':

            ind=27

            maxInd=31

            Key='7'

            getChar(Key, ind, maxInd)

        elif key == '8':

            ind=32

            maxInd=35

            Key='8'

            getChar(Key, ind, maxInd)

        elif key == '9':

            ind=36

            maxInd=40

            Key='9'

            getChar(Key, ind, maxInd)

        elif key == '0':

            ind=41

            maxInd=42

            Key='0'

            getChar(Key, ind, maxInd)

        elif key == '*':

            ind=43

            maxInd=43

            Key='*'

            getChar(Key, ind, maxInd)

        elif key == '#':

            ind=44

            maxInd=44

            Key='#'

            getChar(Key, ind, maxInd)

        elif key== 'D':

            return

def sendSMS():

    print"Sending sms"

    lcdclear()

    lcdprint("Enter Number:")

    setCursor(0,1)

    time.sleep(2)

    moNum=""

    while 1:

        key=0;

        key=keypad()

        #print key

        if key>0:

            if key == 'A'  or key== 'B' or key== 'C':

                print key

                return

            elif key == 'D':

                print key

                print moNum

                Serial.write("AT+CMGF=1\r")

                time.sleep(1)

                Serial.write("AT+CMGS=\"+91"+moNum+"\"\r")

                time.sleep(2)

                data=""

                data=Serial.read(60)

                print data

                alphaKeypad()

                print msg

                lcdclear()

                lcdprint("Sending.....")

                Serial.write(msg)

                time.sleep(1)

                Serial.write("\x1A")

                while 1:

                    data=""

                    data=Serial.read(40)

                    print data

                    l=data.find("+CMGS:")

                   if l>=0:

                        lcdclear()

                        lcdprint("SMS Sent.")

                        time.sleep(2)

                        return;

                    l=data.find("Error")

                    if l>=0:

                        lcdclear()

                        lcdprint("Error")

                        time.sleep(1)

                        return

            else:

                print key

                moNum+=key

                lcdwrite(ord(key))

                time.sleep(0.5)

def call():

    print "Call"

    n=0

    moNum=""

    lcdclear()

    lcdprint("Enter Number:")

    setCursor(0,1)

    time.sleep(2)

    while 1:

        key=0;

        key=keypad()

        #print key

        if key>0:

            if key == 'A'  or key== 'B' or key== 'D':

                print key

                return

            elif key == 'C':

                print key

                print moNum

                Serial.write("ATD+91"+moNum+";\r")

                data=""

                time.sleep(2)

                data=Serial.read(30)

                l=data.find("OK")

                if l>=0:

                    lcdclear()

                    lcdprint("Calling.....")

                   setCursor(0,1)

                    lcdprint("+91"+moNum)

                    time.sleep(30)

                    lcdclear()

                    return

                #l=data.find("Error")

                #if l>=0:

                else:

                    lcdclear()

                    lcdprint("Error")

                    time.sleep(1)

                    return

            else:

                print key

                moNum+=key

                lcdwrite(ord(key))

                n=n+1

                time.sleep(0.5)

begin()

lcdcmd(0x01)

lcdprint("  Mobile Phone  ")

lcdcmd(0xc0)

lcdprint("    Using RPI     ")

time.sleep(3)

lcdcmd(0x01)

lcdprint("Circuit Digest")

lcdcmd(0xc0)

lcdprint("Welcomes you")

time.sleep(3)

gsmInit()

smsFlag=0

index=""

while 1:

    key=0

    key=keypad()

    print key

    if key == 'A':

      attendCall()

    elif key == 'B':

      readSMS(index)

      smsFlag=0

    elif key == 'C':

      call()

    elif key == 'D':

      sendSMS()

    data=""

    Serial.flush()

    data=Serial.read(150)

    print data

    l=data.find("RING")

    if l>=0:

      callstr=data

      receiveCall(data)

    l=data.find("\"SM\"")

    if l>=0:

      smsstr=data

      smsIndex=""

      (smsIndex)=receiveSMS(smsstr)

      print smsIndex

      if smsIndex>0:

          smsFlag=1

          index=smsIndex

    if smsFlag == 1:

        lcdclear()

        lcdprint("New Message")

        time.sleep(1)

    setCursor(0,0)

    lcdprint("C--> Call <--A");

    setCursor(0,1);

    lcdprint("D--> SMS  <--B")

GSM Technology Applications

Here are some examples of how GSM technology can be put to use.

  1. Automation and Safety via Smart GSM Technology

Nowadays, we can't live without our GSM mobile terminal. The Mobile phone terminal is essentially an extension of ourselves, allowing us to connect with the world in the same way our wallet/purse, keys, or watch does. Many people like not having to worry about being unavailable or who they can call at any given moment.

It's clear from the name that this Project relies on the SMS transmission capabilities of GSM networks. The ability to send and receive text messages is widely utilized to provide access to equipment and facilitate home security breach management. There are two proposed subsystems in the system. Controlling appliances in one's house from afar is made possible by the appliance control subsystem, while the security alert subsystem provides automatic security monitoring.

The system can send consumers instructions via SMS from a designated phone number to adjust the home appliance's state as needed. An automatic SMS can be generated by the system upon detection of an intrusion, warning the user of a potential threat to their data.

The advent of GSM technology will make global, instantaneous, and universal communication possible. GSM's functional architecture employs intelligent networking principles as the first step toward a genuinely personal communication system with sufficient standards to ensure interoperability.

  1. Medical Uses for GSM-Based Systems

Here are two examples of similar situations to think about.

  • The patient has sustained a life-threatening injury or illness and requires emergency medical attention. A mobile phone is the only thing he (or his companion) has.

  • After being released from the hospital, the patient plans to rest at home but is reminded that he must return for routine exams. A mobile phone and perhaps some health monitoring or other medical sensor gadgets may be in his possession.

The only way to solve either problem is via a mobile communication system. In other words, the above scenarios are easily manageable with today's communication technology because all that needs to be done is send the patient's information across a network and have it processed at the receiving end, which may be a hospital or the doctor's office.

In the first scenario, the doctor keeps tabs on the patient's information and returns the instructions to him so he can take whatever precautions before getting to the hospital. In the second scenario, the doctor keeps tabs on the patient's test results and, if necessary, proceeds with treatment.

Telemedicine services are the driving force behind this entire operation. The telemedicine system has three different applications.

  • Video conferencing lets patients in one location have face-to-face contact with their doctors and nurses, speeding up the healing process.

  • With the help of sensors that constantly report on a patient's condition and direct medical staff on how to proceed with treatment.

  • By sending the gathered health information for further review and analysis.

A wireless method of communication is used for the three options mentioned above. When providing healthcare, it is necessary to have many data retrieval mechanisms in place. These can be online medical databases or hosts with equipment that aid recovery and health monitoring. Broadband networks, medium-throughput media, and narrowband GSM access are all viable possibilities.

There are several benefits to using GSM technology in a telemedicine setup.

  • Cost savings and widespread availability of GSM receivers (including cell phones and modems)

  • It can transfer data quickly.

  1. Typical Telemedical Infrastructure

The four components that make up a standard telemedicine system are as follows:

  1. The Patient Unit: It takes data from the patient, either in its original analog form or after being converted to digital format, and then manages the data stream before sending it. It is made up of several different types of medical sensors, such as those used to track heart rate, blood pressure, body temperature, spirometry, etc., each of which generates an electrical signal that is sent to a processor or controller for analysis before being transmitted over a wireless network.

  2. Communication Network: As such, it is employed for both data transmission and security. Networks, mobile stations, and base stations are all components of the Global System for Mobile Communication (GSM) system. The mobile station, also known as the mobile phone or primary mobile access point, is the device responsible for connecting mobile devices to the global system for mobile communications (GSM) network.

  3. Receiving/Server Side: This is a healthcare system with a GSM modem installed to receive, decode, and forward signals to the presenting device.

  4. Presentation Unit: This is the brains of the operation. This processor saves the data in a standard format for later retrieval and analysis by doctors and from which they can send text messages to the client side if necessary.

To demonstrate the fundamentals of telemedicine, a rudimentary model will suffice. It has a sender and a receiver, both of which are separate components. The sensor input is transmitted by the transmitter and received by the receiver unit for processing.

See below for a simplified telemedicine system to track a patient's heart rate and apply the results as needed.

The data collected by the heartbeat detector (a light-emitting device whose light is modified as it flows through human blood) is transformed into electrical pulses at the transmitter unit. When the Microcontroller picks up on these pulses, it calculates the heart rate and communicates that information and other data collected to the medical team via a Gsm network. An IC called a Max 232 connects the Microcontroller to the GSM modem.

The GSM modem at the receiving end grabs the information and passes it to the Microcontroller. The Microcontroller then performs an analysis using the input from the Personal computer and displays the outcome on the LCD. Medical professionals can keep tabs on the patient and begin the necessary treatment after reviewing the results on the screen.

Medical Applications of Global Systems for Mobile Communication

The following are some real-world applications for GSM technology.

  1. AT&T Health GlowCaps

These plain pill bottles serve as a gentle prompt to the patient to take their prescribed medications. It uses GSM technology to contact the patient on their mobile phone at the specified pill-taking time, at which point the cap will light up, the buzzer will sound, and the patient will be reminded to take their medication. Each time a bottle is uncorked, it is documented.

  1. Ultrasound technology

With the help of a portable ultrasound transducer that connects to a smartphone, it is possible to send ultrasound images captured with a handheld device to a distant location using a global system for mobile communications (GSM).

  1. A Continuous Glucose Monitor (CGM)

The patient's blood sugar levels can be tracked and reported to the doctor. A sensor is implanted under the skin and monitors blood glucose levels, sending the data to a receiver (a mobile phone) at regular intervals.

Conclusion

As part of this guide, we analyzed GSM's architecture and learned how it operates in practice. We wrote a Python program to turn our Raspberry Pi 4 into a fully functional mobile phone. No technical difficulties were encountered as we watched text and phone calls travel between the raspberry pi and our mobile phone. You should feel confident in your ability to apply the ideas and understand the circuits of GSM now. One way to up the difficulty level of this Project is to try to make a live video call using the raspberry pi 4 mobile. Next, we'll look at connecting the pcf8591 ADC/DAC analog-digital converter module to a Raspberry Pi.

RF Communication with nRF24L01 and Raspberry Pi 4

Where To Buy?
No.ComponentsDistributorLink To Buy
1BreadboardAmazonBuy Now
2Jumper WiresAmazonBuy Now
3LCD 16x2AmazonBuy Now
4nRF24L01AmazonBuy Now
5Arduino UnoAmazonBuy Now
6Raspberry Pi 4AmazonBuy Now

Introduction

We're glad you could join us for another lesson in our series on programming for the Raspberry Pi 4. The previous chapter covered how to interface the USB barcode scanner with raspberry pi 4. We looked at different types of barcodes and what each stripe represents as well as the different types of barcode scanners available today. We also built a python program for the intelligent shopping cart and now our familiarity with barcodes and scanners and how they function has significantly increased. The benefits and drawbacks of its use were also discussed, but what we're interested in for this article is the transmission of radio frequency signals using the nrf24l01 Module in a raspberry pi 4.

Components

  • nRF24L01 RF module

  • Raspberry pi 4

  • Arduino Uno

  • Jumper wires

  • Power supply

  • 16x2 liquid crystal display

Wireless communication systems, such as ESPS266 WiFi modules, are widely used in the design process. Further, the media chosen is determined by the function it will serve. It's no secret that the nRF24L01 is a widely used wireless channel for local area network communication. These modules have a band rate of 250Kbps to 2Mbps and transmit on the 2.4GHz (ISM band), which is permitted in many states and suitable for usage in industrial and healthcare settings. There is also the claim that these modules can communicate at a distance of up to 100 meters with the correct antennae.

This tutorial demonstrates how to set up wireless communication between an Arduino UNO and a Raspberry Pi by utilizing the nRF24L01 - 2.4GHz RF Transceiver module. Raspberry Pi will broadcast data via nRF24L01, and Arduino Board will receive the data and display it on a 16x2 LCD. In addition to its built-in WiFi and Bluetooth Low Energy (BLE) capabilities, the nRF24L01 is also capable of wireless communication via BLE.

Both parts of the tutorial are equally important. In the first, we'll see how to connect the nRF24L01 to an Arduino so that it can function as a receiver, and in the second, we'll do the same thing with a Raspberry Pi can send out signals.

The meaning of "wireless radio frequency."

There are many different types of electromagnetic waves. Still, the ones utilized for radar signals and communications fall into roughly 3 kHz to 300 GHz range, known as "radio frequencies."

The term "radio frequency" is more commonly used to refer to electrical than mechanical oscillations. There are, however, examples of mechanical RF systems. Although radio frequency (RF) refers to an oscillation rate, the term "radio frequency" (RF) is sometimes used interchangeably with "radio" to describe the practice of communicating without the need for wires.

Numerous wireless technologies rely on RF fields, including cordless and cell phones, radio and television broadcasting stations, satellite telecommunication networks, Bluetooth communication modules and WiFi, and two-way radios.

External communications include various products like garage doors and microwave ovens, which use radio frequencies. The infrared frequencies of various wireless devices, like TV remote controllers, computer mice, and some wireless computer keyboards, have shorter electromagnetic wavelengths.

So, How Exactly Does Radio Frequency Operate?

The frequency of radio transmission is expressed in hertz (Hz) units, which stand for the count of cycles per second. Radio waves can travel from one thousand hertz (kHz) to several gigahertz (GHz). Microwaves, a form of radio wave, operate at much higher frequencies. Because of this, we can't see radio frequencies (RFs).

The wavelength' of a radio wave is proportional to the square root of the frequency 'f.' The relationship between frequency and wavelength can be expressed in megahertz and meters, respectively.

s = 300/f

At higher frequencies, electromagnetic radiation is manifested as infrared (IR), ultraviolet (UV), visible (Visible), X-ray (XR), and gamma-ray (GJ).

Traits of Radio Frequency

The following are some of the defining features of RF:

  • Low energy consumption

  • It has an excellent operational range (three to thirty meters), a data rate of up to two megabits per second, the ability to pass through walls, and can transmit in any direction.

The nRF24L01 Radio Frequency (RF) Module

Due to their half-duplex design, the nRF24L01 modules can only send or receive data but not do both. The Module's data transmission and reception are handled by the generic Nordic semi-conductor nRF24L01 IC. The IC uses the simple serial peripheral interface (SPI) protocol for communication, making it compatible with virtually all microcontrollers. Arduino makes things much simpler because there are numerous library resources available. The following table depicts the pin configurations of a typical nRF24L01 module.

The Module is battery efficient, as its operating voltage ranges from 1.9V to 3.6V, and it draws minimal current (only 12mA) during regular operation. Most pins can be connected directly with 5V chipsets like Arduino, even though the voltage rating is 3.3V. Each Module also includes 6 Pipelines, which is a huge time saver. Simply put, each Module can exchange information with up to six others. Therefore, the Module can be used for IoT applications requiring the creation of star or mesh networks. With an extensive network address of 125 unique IDs, we may use 125 such components in a contained space without worrying about them interfering with one another.

Mechanics of Operation

Given that the Module supports 125 separate channels, creating a network containing 125 fully available modems at a single location is theoretically possible. Each device can simultaneously interface with up to six others on the same channel.

Transmission with this Module only uses about 12mA of power, less than a single display LED screen. The Module requires a voltage of 1.9V to 3.6V to function. Still, the other pins are 5V logic compatible, allowing us to connect it directly to an Arduino without needing logic-level converters.

Three of these terminals are used for SPI communication and must be hooked up to the SPI pins on the Arduino; however, the SPI pins on different Arduino boards are labelled differently. Connecting the CSN and CE pins to any input pin on the Arduino board toggles between standby and active modes and transmit and command modes for the Module. The last connector is an interrupt pin, which is optional.

Variations in Modules

The NRF24L01 modules can be found in a wide range of versions. The model with a built-in antenna is the clear frontrunner. This reduces the transmission range of the Module to around 100 meters but allows for a smaller module size.

In the second variant, an SMA connector replaces the onboard antenna, allowing us to use a duck transmitter for enhanced signal strength.

The third variant displayed here also features the duck antenna with an RFX2401C microprocessor with an integrated Power Amplifier and Low-Noise Amplifier). This can increase the NRF24L01's transmission range in open areas by 1000.

Circuit Schematic

Integrating nRF24L01 with Arduino

The components in the circuit design for linking nRF24L01 to Arduino are few, and the process is straightforward. SPI will be used to link the nRF24l01, and I2C will connect the 16x2 LCD.

Integrating nRF24L01 on a Raspberry Pi

Because only the SPI adapter is required to link the Raspberry Pi and the nRF24L01, the corresponding circuit schematic is pretty straightforward.

How to Use nRF24l01 with Raspberry Pi to Communicate

Python3 will be used for Raspberry Pi's programming. The Arduino platform is not the only one that can use C/C++. However, if you're programming in Python, you can get a library for nRF24l01 that's already been made. Keep in mind that the library and the python program must be in the same folder for the python program to use it. Create a folder to house your applications and library files after you have downloaded and extracted the library. After the necessary libraries have been installed, you can begin coding immediately. Importing libraries like the GPIO library for communicating with the Raspberry Pi's GPIO pins and the time library for using the Pi's clock and date functions are the first steps in writing any program.

import RPi.GPIO as GPIO 

import time     

import spidev

from lib_nrf24 import NRF24

It would be best if you switched to the "Broadcom SOC channel" for the GPIO setting. Pins are referred to by their "Broadcom SOC channel" numbers, which follow the letters "GPIO" (GPIO01, GPIO02, etc.). The Board Numbers are not these.

GPIO.setmode(GPIO.BCM)

After that, we'll assign a permanent address for the pipe. To send data to Arduino, you'll need to use this address. There will be a hexadecimal representation of the address.

pipes = [[0xE0, 0xE0, 0xF1, 0xF1, 0xE0], [0xF1, 0xF1, 0xF0, 0xF0, 0xE0]]

Start the radio with the CE pin (GPIO08) and the CSN pin (GPIO25).

radio.begin(0, 25)

Change the power levels to minimal, the channel address to 76, the data rate to 1 Mbps, and the payload size to 32 bits.

radio.setPayloadSize(32)  

radio.setChannel(0x76) 

radio.setDataRate(NRF24.BR_1MBPS)    

radio.setPALevel(NRF24.PA_MIN)

Start the data writing process by opening the pipes and displaying some nRF24l01 basics.

radio.openWritingPipe(pipes[0])     

radio.printDetails()

Get your message ready to send as a string. Arduino UNO will receive this message.

sendMessage = list("Hi..Arduino UNO")  

while len(sendMessage) < 32:    

    sendMessage.append(0)

Send the string's first character to the stereo and continue doing so until the radio is ready to receive it. In addition, a debug statement detailing the time and date the message was delivered should be printed.

While True:

    start = time.time()      

    radio.write(sendMessage)   

    print("Sent the message: {}".format(sendMessage))  

send

    radio.start listening()


A timed-out error message should be printed if the thread is finished and the conduit is closed.

while not radio.available(0):

        time.sleep(1/100)

        If time.time() - start > 2:

            print("Timed out.")  # print error message if radio disconnected or not functioning anymore

            break

If you want to send another message, turn off the radio and disconnect from the connection for three seconds.

radio.stopListening()     # close radio

    time.sleep(3)  # give a delay of 3 seconds

If you know the fundamentals of Python, you can easily comprehend the Raspberry program. You will find a fully functional Python program at the end of this tutorial.

Putting the Python Code for the Raspberry Pi to Work

If you follow the steps below, running the software will be a breeze.

  • You should keep the Python source code and library files together.

    • My Sender program file is nrfsend.py, and all the related files are in the same directory.

      • Access Raspberry Pi's command prompt. Use the cd command to get to the directory containing the python script.

        • Navigate to the directory, type "sudo python3 your program.py," and hit enter to run the program. In less than a minute, you'll likely see nRf24's essentials laid out, and the broadcaster will begin broadcasting its bulletins at three-second intervals. Once the send is complete, the debug message will appear.

        The Arduino UNO will now display the same code as the receiver.

        The nRF24l01 and Arduino UNO: Message Reception Programming

        The Arduino UNO can be programmed in a manner not dissimilar to that of the Raspberry Pi. Our procedures will be very similar; however, we'll use a different language for programming and other processes. The procedure will incorporate the nRF24l01 readout. Download the nRF24l01 Arduino library from GitHub. To get started, make sure all required libraries are installed. We're using a 16x2 I2C LCD, so we need to include the Wire.h library; the nRF24l01 communicates via SPI, so we also need the SPI library.

        #include<SPI.h>                   

        #include <Wire.h>

        Don't forget to add the RF24 and LCD libraries so you may use them.

        #include<RF24.h>                  

        #include <LiquidCrystal_I2C.h>

        Put the LCD's I2C address—27 in this case, as it's a 16x2 display—into the appropriate function.

        LiquidCrystal_I2C lcd(0x27, 16, 2);

        Pin 9 serves as the RF24's Common Emitter, and pin 10 serves as its Common Source Negative.

        RF24 radio(9, 10) ;  

        Turn the radio on and tune in to channel 76. In addition, open the pipe for reading by setting the address to that of the Raspberry Pi.

        radio.begin();        

          radio.setPALevel(RF24_PA_MAX) ;   

          radio.setChannel(0x76) ;            

          const uint64_t pipe = 0xE0E0F1F1E0LL ;    

          radio.openReadingPipe(1, pipe) ;

        Start the I2C data transfer and initialize the LCD screen.

        Wire.begin();                 

          lcd.begin();                    

          lcd.home();                       

          lcd.print("Ready to Receive");

        Turn on the radio's receiver and enter a message length of 32.

        radio.startListening() ;        

          char receivedMessage[32] = {0}

        The message will be read and saved immediately if a radio is connected. Display the message on the screen and send it to the serial monitor till the following message is received. Put the radio on hold while you tune in, then try again later. Right this way, in ten microseconds.

        if (radio.available()) {       

            radio.read(receivedMessage, sizeof(receivedMessage));        

            Serial.println(receivedMessage) ;    

            Serial.println("Turning off the radio.") ;   

            radio.stopListening() ;   

            String stringMessage(receivedMessage) ;     

            lcd.clear();    

            delay(1000);    

            lcd.print(stringMessage);   

          }

        Copy and paste the code below into your server and allow time for the response to arrive.

        NRF Transmitter Side Code (Raspberry Pi)

        import RPi.GPIO as GPIO  # import gpio

        import time      #import time library

        import spidev

        from lib_nrf24 import NRF24   #import NRF24 library

        GPIO.setmode(GPIO.BCM)       # set the gpio mode

          # set the pipe address. This address should be entered on the receiver to

        pipes = [[0xE0, 0xE0, 0xF1, 0xF1, 0xE0], [0xF1, 0xF1, 0xF0, 0xF0, 0xE0]]

        radio = NRF24(GPIO, spidev.SpiDev())   # use the gpio pins

        radio.begin(0, 25)   # start the radio and set the ce,csn pin ce= GPIO08, csn= GPIO25

        radio.setPayloadSize(32)  #set the payload size as 32 bytes

        radio.setChannel(0x76) # set the channel as 76 hex

        radio.setDataRate(NRF24.BR_1MBPS)    # set radio data rate

        radio.setPALevel(NRF24.PA_MIN)  # set PA level

        radio.setAutoAck(True)       # set acknowledgement as true 

        radio.enableDynamicPayloads()

        radio.enableAckPayload()

        radio.openWritingPipe(pipes[0])     # open the defined pipe for writing

        radio.printDetails()      # print basic detals of radio

        sendMessage = list("Hi..Arduino UNO")  #the message to be sent

        while len(sendMessage) < 32:    

            sendMessage.append(0)

        While True:

            start = time.time()      #start the time for checking delivery time

            radio.write(sendMessage)   # just write the message to radio

            print("Sent the message: {}".format(sendMessage))  # print a message after succesfull send

            radio.startListening()        # Start listening the radio

            while not radio.available(0):

                time.sleep(1/100)

                if time.time() - start > 2:

                    print("Timed out.")  # print error message if the radio disconnected or not functioning anymore

                    break

            radio.stopListening()     # close radio

            time.sleep(3)  # give delay of 3 seconds

        NRF Receiver Side Code (Arduino):

        #include<SPI.h>                   // spi library for connecting nrf

        #include <Wire.h>                             // i2c libary fro 16x2 lcd display

        #include<RF24.h>                  // nrf library

        #include <LiquidCrystal_I2C.h>     // 16x2 lcd display library

        LiquidCrystal_I2C lcd(0x27, 16, 2);         // i2c address is 0x27

        RF24 radio(9, 10) ;  // ce, csn pins    

        void setup(void) {

          while (!Serial) ;

          Serial.begin(9600) ;     // start serial monitor baud rate

          Serial.println("Starting.. Setting Up.. Radio on..") ; // debug message

          radio.begin();        // start radio at ce csn pin 9 and 10

          radio.setPALevel(RF24_PA_MAX) ;   // set power level

          radio.setChannel(0x76) ;            // set chanel at 76

          const uint64_t pipe = 0xE0E0F1F1E0LL ;    // pipe address same as sender i.e. raspberry pi

          radio.openReadingPipe(1, pipe) ;        // start reading pipe 

          radio.enableDynamicPayloads() ;

          radio.powerUp() ;          

          Wire.begin();                 //start i2c address

          lcd.begin();                    // start lcd 

          lcd.home();                       

          lcd.print("Ready to Receive");  // print starting message on lcd 

          delay(2000);

          lcd.clear();

        }

        void loop(void) {

          radio.startListening() ;        // start listening forever

          char receivedMessage[32] = {0} ;   // set incmng message for 32 bytes

          if (radio.available()) {       // check if message is coming

            radio.read(receivedMessage, sizeof(receivedMessage));    // read the message and save

            Serial.println(receivedMessage) ;    // print message on serial monitor 

            Serial.println("Turning off the radio.") ;   // print message on serial monitor

            radio.stopListening() ;   // stop listening radio

            String stringMessage(receivedMessage) ;     // change char to string

            lcd.clear();    // clear screen for new message

            delay(1000);    // delay of 1 second 

            lcd.print(stringMessage);   // print received mesage

          }

          delay(10);

        }

        Features That Have the Most Impact on RF Module Efficiency

        The RF module's performance will be affected by the same factors as any other RF component. For instance, a transmitter's output power can be increased to extend the range of a transmission. However, this will cause a greater consumption of electricity by the transmitters (TX) device, reducing the useful life of battery-operated gadgets. Increasing the system's transmit power also makes it more vulnerable to interference from a second RF source.

        Similarly, boosting the receiver's sensitivity increases the usable communication range but increases the risk of an error brought on by interference from other RF equipment. Matching antennas on both ends of a communication link can potentially boost the overall system's performance.

        Finally, the regarded remote distance of any given system is typically measured in an open-air line-of-sight outline without any interference; nevertheless, problems such as floors, walls, and dense structures will frequently grasp the radio wave signals; thus, the actual operational distance will typically be less than specified.

        Uses for Radio Frequency Communication

        The most common uses of radio frequency communication are in the areas of wireless data and voice transfer, home automation, and remote control, as well as in the industrial and commercial sectors.

        RF-controlled switches can be used in home automation applications as an alternative to traditional switches. An RF remote allows one to operate lights and other electronics without leaving their current location. Those with mobility issues will benefit the most from this app. RF communication is helpful in industrial settings for directing autonomous robots and motorized vehicles. These robot vehicles are often employed in hazardous tasks humans cannot undertake. A data transmission unit is required to direct the motion of the robotic vehicles.

        Multiple factors make radio frequency (RF) transmission preferable to infrared (IR) (infrared). The more extended range of RF signals makes them ideal for long-distance communications. Unlike radio frequency (RF), which can go across obstacles, infrared (IR) generally requires a clear path from transmitter to receiver. The reliability of RF transmission is far greater than that of infrared remote communications. While radio frequency (RF) communications require other IR-emitting devices that can disrupt a precise frequency range, infrared (IR) communications.

        Problems with Radio Frequency

        These are some of RF's drawbacks.

        • Preschoolers, expectant mothers, the elderly, those with pacemakers, little birds, flora, wildlife, insects, etc., are all negatively impacted by unregulated RF radiation.

        • More lightning has been seen in nearby cellular towers that use radio frequency than in other areas.

        • Some fruit crops in the vicinity of RF towers are also negatively impacted.

        • Because RF waves are accessible in both line-of-sight (LOS) and non-LOS zones of the transmitter, hackers can easily break into the system and decode sensitive personal or government data.

        • This problem can be avoided by employing highly protected methods like AES, WEP, WPA, etc., while transmitting data over radio frequency waves. Spread spectrum and frequency hopping modulation methods can also be applied to RF signals to prevent such eavesdropping.


        Conclusion

        This concludes the comprehensive instruction on wireless communication between a Raspberry Pi and an Arduino UNO via nRf24l01 modules. The 16 * 2 liquid crystal display will show the message. Pipe addresses are crucial on the Arduino UNO and the Raspberry Pi 4. In the following tutorial, we will learn how to Call and Text using Raspberry Pi and GSM Module in pi 4.

        Smart Attendance System using RFID with Raspberry Pi 4

        Greetings! This is the complete project of our Raspberry Pi 4 tutorials. In our previous tutorial, we learned to set up our raspberry pi as a virtual private network server. In this tutorial, we will design a smart attendance system using an RFID card reader, which we will use to sign in students in attendance in a class.

        First, we will design a database for our website, then we will design the RFID circuit for scanning the student cards and displaying present students on the webpage, and finally, we will design the website that we will use to display the attendees of a class.

        Where To Buy?
        No.ComponentsDistributorLink To Buy
        1BreadboardAmazonBuy Now
        2Jumper WiresAmazonBuy Now
        3LCD 16x2AmazonBuy Now
        4LCD 16x2AmazonBuy Now
        5Raspberry Pi 4AmazonBuy Now

        Components

        • RFID card kit
        • Breadboard
        • Jumper wires
        • Raspberry pi 4
        • I2C LCD screen

        Design a database in MySQL server

        Additionally, the Database server offers a DBMS that can be queried and connected to and can integrate with a wide range of platforms. High-volume production environments are no problem for this software. The server's connection, speed, and encryption make it a good choice for accessing the database.

        There are clients and servers for MySQL. This system contains a SQL server with many threads that support a wide range of back ends, utility programs, and application programming interfaces.

        We'll walk through the process of installing MySQL on the RPi in this part. The RFID kit's database resides on this server, and we'll utilize it to store the system's signed users.

        There are a few steps before we can begin installing MySQL on a Raspberry Pi. There are two ways to accomplish this.

        sudo apt update

        sudo apt upgrade

        Installing the server software is the next step.

        Here's how to get MySQL running on the RPi using the command below:

        sudo apt install MariaDB-server

        Having installed MySQL on the Raspberry Pi, we'll need to protect it by creating a passcode for the "root" account.

        If you don't specify a password for your MySQL server, you can access it without authentication.

        Using this command, you may begin safeguarding MySQL.

        sudo mysql_secure_installation

        Follow the on-screen instructions to set a passcode for the root account and safeguard your MySQL database.

        To ensure a more secured installation, select "Y" for all yes/no questions.

        Remove elements that make it easy for anyone to access the database.

        We may need that password to access the server and set up the database and user for applications like PHPMyAdmin.

        For now, you can use this command if you wish to access the Rpi's MySQL server and begin making database modifications.

        sudo MySQL –u root -p

        To access MySQL, you'll need to enter the root user's password, which you created in Step 3.

        Note: Typing text will not appear while typing, as it does in typical Linux password prompts.

        Create, edit, and remove databases with MYSQL commands now available. Additionally, you can create, edit, and delete users from inside this interface and provide them access to various databases.

        After typing "quit;" into MySQL's user interface, you can exit the command line by pressing the ESC key.

        Pressing CTRL + D will also exit the MYSQL command line.

        You may proceed to the next step now that you've successfully installed MySQL. In the next few sections, we'll discuss how to get the most out of our database.

        Creating database and user

        The command prompt program MySQL must be restarted before we can proceed with creating a username and database on the RPi.

        The MySQL command prompt can be accessed by typing the following command. After creating the "root" user, you will be asked for the password.

        To get things started, run the command to create a MySQL database.

        The code to create a database is "CREATE DATABASE", and then the name we like to give it.

        This database would be referred to as "rfidcardsdb" in this example.

        To get started, we'll need to create a MySQL user. The command below can be used to create this new user.

        "rfidreader" and "password" will be the username and password for this example. Take care to change these when making your own.

        create user “rfidreader" @localhost identified by "password."

        We can now offer the user full access to the database after it has been built.

        Thanks to this command, " "rfidreader" will now have access to all tables in our "rfidcardsdb" database.

        grant all on rfidcardsdb.* to "rfidreader" identified by "password."

        We have to flush the permission table to complete our database and user set up one last time. You cannot grant access to the database without flushing your privilege table.

        The command below can be used to accomplish this.

        Now we have our database configured, and now the next step is to set up our RFID circuit and begin authenticating users. Enter the “Exit” command to close the database configuration process.

        The RFID card circuit

        An RFID reader reads the tag's data when a Rfid card is attached to a certain object. An RFID tag communicates with a reader via radio waves.

        In theory, RFID is comparable to bar codes in that it uses radio frequency identification. While a reader's line of sight to the RFID tag is preferable, it is not required to be directly scanned by the reader. You can't read an RFID tag that is more than three feet away from the reader. To quickly scan a large number of objects, the RFID tech is used, and this makes it possible to identify a specific product rapidly and effortlessly, even if it is sandwiched between several other things.

        HOW RFID CARD READERS AND WRITERS WORK

        There are major parts to Cards and tags: an IC that holds the unique identifier value and a copper wire that serves as the antenna:

        Another coil of copper wire can be found inside the RFID card reader. When current passes through this coil, it generates a magnetic field. The magnetic flux from the reader creates a current within the wire coil whenever the card is swiped near the reader. This amount of current can power the inbuilt IC of the Card. The reader then reads the card's unique identifying number. For further processing, the card reader transmits the card's unique identification number to the controller or CPU, such as the Raspberry Pi.

        RFID card reader circuit

        Connect the reader to the Raspberry the following way:

        use the code spi bcm2835 to see if it is displayed in the terminal.

        lsmod | grep spi

        SPI must be enabled in the setup for spi bcm2835 to appear (see above). Make sure that RPi is running the most recent software.

        Make use of the python module.

        sudo apt-get install python

        The RFID RC522 can be interacted with using the Library SPI Py, found on your RPi.

        cd ~

        git clone https://github.com/lthiery/SPI-Py.git

        cd ~/SPI-Py

        sudo python setup.py install

        cd ~

        git clone https://github.com/pimylifeup/MFRC522-python.git

        To test if the system is functioning correctly, let's write a small program:

        cd ~/

        sudo nano test.py

        now copy the following the code into the editor

        import RPi.GPIO as GPIO

        import sys

        sys.path.append('/home/pi/MFRC522-python')

        from mfrc522 import SimpleMFRC522

        reader = SimpleMFRC522()

        print("Hold a tag near the reader")

        try:

        id, text = reader.read()

        print(id)

        print(text)

        finally:

        GPIO.cleanup()

        Register card

        Here we will write a short python code to register users whenever they swipe a new card on the RFID card reader. First, create a file named addcard.py.

        copy the following code.

        import pymysql

        import cv2

        from mfrc522 import SimpleMFRC522

        import RPi.GPIO as GPIO

        import drivers

        display = drivers.Lcd()

        display.lcd_display_string('Scan your', 1)

        display.lcd_display_string('card', 2)

        reader = SimpleMFRC522()

        reader = SimpleMFRC522()

        id, text = reader.read()

        display = drivers.Lcd()

        display.lcd_display_string('Type your name', 1)

        display.lcd_display_string('in the terminal', 2)

        user_id = input("user name?")

        # put serial_no uppercase just in case

        serial_no = '{}'.format(id)

        # open an sql session

        sql_con = pymysql.connect(host='localhost', user='rfidreader', passwd='password', db='rfidcardsdb')

        sqlcursor = sql_con.cursor()

        # first thing is to check if the card exist

        sql_request = 'SELECT card_id,user_id,serial_no,valid FROM cardtbl WHERE serial_no = "' + serial_no + '"'

        count = sqlcursor.execute(sql_request)

        if count > 0:

        print("Error! RFID card {} already in database".format(serial_no))

        display = drivers.Lcd()

        display.lcd_display_string('The card is', 1)

        display.lcd_display_string('already registered', 2)

        T = sqlcursor.fetchone()

        print(T)

        else:

        sql_insert = 'INSERT INTO cardtbl (serial_no,user_id,valid) ' + \

        'values("{}","{}","1")'.format(serial_no, user_id)

        count = sqlcursor.execute(sql_insert)

        if count > 0:

        sql_con.commit()

        # let's check it just in case

        count = sqlcursor.execute(sql_request)

        if count > 0:

        print("RFID card {} inserted to database".format(serial_no))

        T = sqlcursor.fetchone()

        print(T)

        display = drivers.Lcd()

        display.lcd_display_string('Congratulations', 1)

        display.lcd_display_string('You are registered', 2)

        GPIO.cleanup()

        The program starts by asking the user to scan the card.

        Then it connects to the database using the pymysql.connect function.

        If we enter our name successfully, the program inserts our details in the database, and a congratulations message is displayed to show that we are registered.

        Creating the main system

        Using the LCD command library, you can:

        1. Install git

        sudo apt install git

        1. Download and install the repo on your Raspberry Pi.

        cd /home/pi/

        git clone https://github.com/the-raspberry-pi-guy/lcd.git

        cd lcd/

        1. Then begin installation with the following

        sudo ./install.sh

        After installation is complete, try running one of the program files

        cd /home/pi/lcd/

        Next, we will install the mfrc522 library, which the RFID card reader uses. This will enable us to read the card number for authentication. We will use:

        Pip install mfrc522

        Next, we will import the RPI.GPIO library enables us to utilize the raspberry pi pins to power the RFID card and the LCD screen.

        Import RPi.GPIO

        We will also import the drivers for our LCD screen. The LCD screen used here is the I2C 16 * 2 LCD.

        Import drivers

        Then we will import DateTime for logging the time the user has swiped the card into the system.

        Import DateTime

        In order to read the card using the rfid card, we will use the following code:

        reader = SimpleMFRC522()

        display = drivers.Lcd()

        display.lcd_display_string('Hello Please', 1)

        display.lcd_display_string('Scan Your ID', 2)

        try:

        id, text = reader.read()

        print(id)

        display.lcd_clear()

        finally:

        GPIO.cleanup()

        The LCD is divided into two rows, 1 and 2. To display text in the first row, we use:

        Display.lcd_display_string(“string”,1)

        And 2 to display in the second row.

        After scanning the card, we will connect to the database we created earlier and search whether the scanned card is in the database or not.

        If the query is successful, we can display if the card is in the database; if not, we can proceed, then the user needs to register the card.

        If the user is registered, the system saves the logs, the username and the time the card was swapped in a text file located in the/var/www/html root directory of the apache server.

        Note that you will need to be a superuser to create the data.txt file in the apache root directory. For this, we will use the following command in the Html folder:

        Sudo touch data.txt

        Then we will have to change the access privileges of this data.txt file to use the program to write the log data. For this, we will use the following code:

        Sudo chmod 777 –R data.txt

        The next step will be to display this data on a webpage to simulate an online attendance register. The code for the RFID card can be found below.

        #! /usr/bin/env python

        # Import necessary libraries for communication and display use

        import RPi.GPIO as GPIO

        from mfrc522 import SimpleMFRC522

        import pymysql

        import drivers

        import os

        import numpy as np

        import datetime

        # read the card using the rfid card

        reader = SimpleMFRC522()

        display = drivers.Lcd()

        display.lcd_display_string('Hello Please', 1)

        display.lcd_display_string('Scan Your ID', 2)

        try:

        id, text = reader.read()

        print(id)

        display.lcd_clear()

        # Load the driver and set it to "display"

        # If you use something from the driver library use the "display." prefix first

        try:

        sql_con = pymysql.connect(host='localhost', user='rfidreader', passwd='password', db='rfidcardsdb')

        sqlcursor = sql_con.cursor()

        # first thing is to check if the card exist

        cardnumber = '{}'.format(id)

        sql_request = 'SELECT user_id FROM cardtbl WHERE serial_no = "' + cardnumber + '"'

        now = datetime.datetime.now()

        print("Current date and time: ")

        print(str(now))

        count = sqlcursor.execute(sql_request)

        if count > 0:

        print("already in database")

        T = sqlcursor.fetchone()

        print(T)

        for i in T:

        print(i)

        file = open("/var/www/html/data.txt","a")

        file.write(i +" Logged at "+ str(now) + "\n")

        file.close()

        display.lcd_display_string(i, 1)

        display.lcd_display_string('Logged In', 2)

        else:

        display.lcd_clear()

        display.lcd_display_string(“Please register”, 1)

        display.lcd_display_string(cardnumber,2)

        except KeyboardInterrupt:

        # If there is a KeyboardInterrupt (when you press ctrl+c), exit the program and cleanup

        print("Cleaning up!")

        display.lcd_clear()

        finally:

        GPIO.cleanup()

        Building the website

        Now we are going to design a simple website with Html that we are going to display the information of the attending students of a class, and to do this, we will have to install a local server in our raspberry pi.

        Installing Apache Web Server

        Web, database, and mail servers all run on various server software. Each of these programs can access and utilize files located on a physical server.

        A web server's main responsibility is to provide internet users access to various websites. It serves as a bridge between a server and a client machine to accomplish this. Each time a user makes a request, it retrieves data from the server and posts it to the web.

        A web server's largest issue is to simultaneously serve many web users, each of whom requests a separate page.

        For internet users, convert them to Html pages and offer them in the browser. Whenever you hear the term "webserver," consider the device in charge of ensuring successful communication in a network of computers.

        How Does Apache Work?

        Among its responsibilities is establishing a link between a server and a client's web browser (such as Chrome to send and receive data (client-server structure). As a result, the Apache software can be used on any platform, from Microsoft to Unix.

        Visitors to your website, such as those who wish to view your homepage or "About Us" page, request files from your server via their browser, and Apache returns the required files in a response (text, images, etc.).

        Using HTTP, the client and server exchange data with the Apache webserver, ensuring that the connection is safe and stable.

        Because of its open-source foundation, Apache promotes a great deal of customization. As a result, web developers and end-users can customize the source code to fit the needs of their respective websites.

        Additional server-side functionality can be enabled or disabled using Apache's numerous modules. Encryption, password authentication, and other capabilities are all available as Apache modules.

        Step 1

        To begin, use the following code to upgrade the Pi package list.

        sudo apt-get update

        sudo apt-get upgrade

        Step 2

        After that, set up the Apache2 package.

        sudo apt install apache2 -y

        That concludes our discussion. You can get your Raspberry Pi configured with a server in just two easy steps.

        Type the code below to see if the server is up and functioning.

        sudo service apache2 status

        You can now verify that Apache is operating by entering your Raspberry Pi's IP address into an internet browser and seeing a simple page like this.

        Use the following command in the console of your Raspberry Pi to discover your IP.

        hostname-i

        Only your home network and not the internet can access the server. You'll need to configure your router's port forwarding to allow this server to be accessed from any location. Our blog will not be discussing this topic.

        Setting up HTML page for editing.

        The standard web page on the Raspberry Pi, as depicted above, is nothing more than an HTML file. First, we will generate our first Html document and develop a website.

        Step 1

        Let's start by locating the Html document on the Raspbian system. You can do this by typing the following code in the command line.

        cd /var/www/html

        Step 2

        To see a complete listing of the items in this folder, run the following command.

        ls -al

        The root account possesses the index.html file; therefore, you'll see every file in the folder.

        As a result, to make changes to this file, you must first change the file's ownership to your own. The username "pi" is indeed the default for the Raspberry Pi.

        sudo chown pi: index.html

        To view the changes you've made, all you have to do is reload your browser after saving the file.

        Building your first HTML page

        Here, we'll begin to teach you the fundamentals of HTML.

        To begin a new page, edit the index.html file and remove everything inside it using the command below.

        sudo nano index.html

        Alternatively, we can use a code editor to open the index.html file and edit it. We will use VS code editor that you can easily install in raspberry pi using the preferences then recommended software button.

        HTML Tags

        You must first learn about HTML tags, which are a fundamental part of HTML. A web page's content can be formatted in various ways by using tags.

        There are often two tags used for this purpose: the opening and closing tags. The material inside these tags behaves according to what these tags say.

        The p> tag, for example, is used to add paragraphs of text to the website.

        <p>The engineering projects</p>

        Web pages can be made more user-friendly by using buttons, which can be activated anytime a user clicks on them.

        <button>Manual Refresh</button>

        <button>Sort By First Name</button>

        <button>Sort By last Name</button>

        The basic format of an HTML document

        A typical HTML document is organized as follows:

        Let us create the page that we will use in this project.

        <html>

        <head>

        </head>

        <body>

        <div id="pageDiv">

        <p> The engineering projects</p>

        <button type="button" id="refreshNames">Manual Refresh</button><br/>

        <button type="button" id="firstSort">Sort By First Name</button><br/>

        <button type="button" id="lastSort">Sort By Last Name</button>

        <div id="namesFromFile">

        </div>

        </div>

        </body>

        </html>

        <!DOCTYPE html>: HTML documents are identified by this tag. This does not necessitate the use of a closing tag.

        <html>: This tag ensures that the material inside will meet all of the requirements for HTML. There is a /html> tag at the end of this.

        </head>: It contains data about the website, but when you view it in a browser, you won't be able to see anything.

        A metadata tag in the head tag can be used to set default character encoding in your website, for instance. This has a /head> tag at the end of it.

        <head>

        <meta charset="utf-8">

        </head>

        Also, you can have a title tag inside the head tag. This tag sets the title of your web page and has a closing </title> tag.

        <head>

        <meta charset="utf-8">

        <title> My website </title>

        </head>

        <body>: The primary focus of the website page is included within this tag. Everything on a web page is usually contained within body tags once you've opened it. This has a /body> tag at the end of it. Many other tags can be found in this body tag, but we'll focus on the ones you need to get started with your first web page.

        We will go ahead and style our webpage using CSS with the lines of codes below;

        <head>

        <!--

        body {

        width:100%;

        background:#ccc;

        color:#000;

        text-align:left;

        margin:0

        ;padding:10px

        ;font:16px/18pxArial;

        }

        button {

        width:160px;

        margin:0 0 10px;}

        #pageDiv {

        width:160px;

        margin:20px auto;

        padding:20px;

        background:#ddd;

        color:#000;

        }

        #namesFromFile {

        margin:20px 0 0;

        padding:10px;

        background:#fff;

        color:#000;

        border:1px solid #000;

        border-radius:10px;

        }

        -->

        </style>

        </head>

        The style tags is a cascading style sheet syntax that lets developers style the webpages however they prefer.

        Adding images to your web page

        You can add images to your web page by using the <img> tag. It is also a void element and doesn’t have a closing tag. It takes the following format

        <img src="URL of image location">

        For example, let’s add an image of the Seeeduino XIAO

        <p>The Engineering projects</p>

        <img src="https://www.theengineeringprojects.com/wp-content/uploads/2022/04/TEP-Logo.png">

        Reload the browser to see the changes

        How to display the attendance list on the webpage

        This is the last step of this project, and we will implement a program that reads our data.txt file from the apache root directory and display it on the webpage that we designed. Since we already have our webpage up and running, we will use the javascript programming language to implement this function of displaying the log list on the webpage. All changes that we are about to implement will be done in the index.html file; therefore, open it in the visual studio code editor.

        Javascript – What is it?

        JavaScript is a dynamic computer programming language. It is lightweight and most commonly used as a part of web pages, whose implementations allow client-side scripts to interact with the user and make dynamic pages. It is an interpreted programming language with object-oriented capabilities.

        Advantage of javascript

        One of the major strengths of JavaScript is that it does not require expensive development tools. You can start with a simple text editor such as Notepad.

        How to use javascript with this program

        Well, javascript as mentioned earlier is a very easy to use language that simply requires us to put the script tags inside the html tags.

        <script> script program </script>

        <header>

        <script>

        Here goes our javascript program

        </script>

        </header>

        The javascript code first opens the data.txt file, then it reads all the contents form that file. Then it uses the xmlHttpRequest function to display the contents on the webpage. The buttons on the webpage activate different functions in the code.For instance manual refresh activates:

        function refreshNamesFromFile(){

        var namesNode=document.getElementById("namesFromFile");

        while(namesNode.firstChild)

        { namesNode.removeChild(namesNode.firstChild);

        }

        getNameFile();

        }

        This function reads the content of the data.txt

        The sort by buttons activate the sort function to sort the logged users either by first name or last name. The function that gets activated by these buttons is:

        function sortByName(e)

        { var i=0, el, sortEl=[], namesNode=document.getElementById("namesFromFile"), sortMethod, evt, evtSrc, oP;

        evt=e||event;

        evtSrc=evt.target||evt.srcElement;

        sortMethod=(evtSrc.id==="firstSort")?"first":"last";

        while(el=namesNode.getElementsByTagName("P").item(i++)){

        sortEl[i-1]=[el.innerHTML.split(" ")[0],el.innerHTML.split(" ")[1]];

        }

        sortEl.sort(function(a,b){

        var x=a[0].toLowerCase(), y=b[0].toLowerCase(), s=a[1].toLowerCase(), t=b[1].toLowerCase();

        if(sortMethod==="first"){

        return x<y?-1:x>y?1:s<t?-1:s>t?1:0;

        }

        else{

        return s<t?-1:s>t?1:x<y?-1:x>y?1:0;

        }

        });

        while(namesNode.firstChild){

        namesNode.removeChild(namesNode.firstChild);

        }

        for(i=0;i<sortEl.length;i++){

        oP=document.createElement("P");

        namesNode.appendChild(oP).appendChild(document.createTextNode(sortEl[i][0]+" "+sortEl[i][1]));

        namesNode.appendChild(document.createTextNode("\r\n"));

        //insert tests -> for style/format

        if(sortEl[i][0]==="John"){

        oP.style.color="#f00";

        }

        if(sortEl[i][0]==="Sue")

        { oP.style.color="#0c0";

        oP.style.fontWeight="bold";

        }

        }

        }

        Output

        With no logged-in users

        With one logged in user

        With two users logged in

        Sort by the first name

        Sort by last name

        Applications of RFID

        Benefits of Smart Attendance System

        Automated attendance systems are excessively time-consuming and sophisticated in the current environment. It is possible to strengthen company ethics and work culture by using an effective smart attendance management system. Employees will only have to complete the registration process once, and images get saved in the system's database. The automated attendance system uses a computerized real-time image of a person's face to identify them. The database is updated frequently, and its findings are accurate in a user interactive state because each employee's presence is recorded.

        Smart attendance systems have several advantages, including the following:

        Students in elementary, secondary, and postsecondary institutions can utilize this system to keep track of their attendance. It can also keep track of workers' schedules in the workplace. Instead of using a traditional method, it uses RFID tags on ID cards to quickly and securely track each person.

        What are the applications of a smart attendance system?

        Computerized smart attendance can be applied in many areas in our day today activities which include the following:

        1) Real-time tracking – Keeping track of staff attendance using mobile devices and desktops is possible.

        2)Decreased errors – A computerized attendance system can provide reliable information with minimal human intervention, reducing the likelihood of human error and freeing up staff time.

        3) Management of enormous data – It is possible to manage and organize enormous amounts of data precisely in the db.

        4) Improve authentications and security – A smart system has been implemented to protect the privacy and security of the user's data.

        5) Reports – Employee log-ins and log-outs can be tracked, attendance-based compensation calculated, the absent list may be viewed and required actions are taken, and employee personal information can be accessed.

        Conclusion

        This tutorial taught us to build a smart RFID card authentication project from scratch. We also learned how to set up an apache server and design a circuit for the RFID and the LCD screen. To increase your raspberry programming skills, you can proceed to building a more complex system with this code for example implementing face detection that automatically starts the authentication process once the student faces the camera or implement a student log out whenever the student leaves the system. In the following tutorial, we will learn how to build a smart security system using facial recognition.

        Capacitance Measurement using Arduino

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

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

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

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

        Software to install

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

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

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

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

        Capacitance Measurement using Arduino

        Project overview

        In this project, we will use the following components-

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

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

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

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

        Here,

        T (Tau) = Time constant(Seconds)

        R = Resistance (Ohms)

        C= Capacitance (Farads)

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

        Components required

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

        Components details

        1. Arduino UNO

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

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

        2. LCD Module

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

        3. Resistors and Capacitors

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

        Circuit diagram and Working

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

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

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

        Arduino code of Capacitance measurement-

        Downloading and including libraries

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

        Variable declaration

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

        Void setup()

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

        Void loop()

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

        Results and Working

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

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

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

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

        Simple Arduino Calculator

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

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

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

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

        Software to Install :

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

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

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

        Project overview :

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

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

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

        Components required :

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

        Components details:

        1. Arduino UNO

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

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

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

        Circuit diagram and working:

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

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

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

        Let's start connecting them.

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

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

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

        Arduino code for calculator:

        Downloading and including libraries

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

        Code declaration

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

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

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

        Void setup function

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

        Void loop function

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

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

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

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

        Results/Working

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

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

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

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

        Smart 4 Way Traffic Signal Control with Variable Delay

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

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

        Variable 4 Way Traffic Light:

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

        Software to Install:

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

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

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

        Project Overview:

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

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

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

        Components Needed:

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

        Component Details:

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

        Arduino Mega:

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

        Figure 1: Arduino Mega

        LCD:

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

        Figure 2: LCD display

        Ultrasonic Sensor:

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

        Figure 3: Ultrasonic Sensor

        Proteus Simulation of Variable Traffic Lights:

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

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

        Figure 4: List of components

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

        Figure 5: Placement of components

        After placing the components, make the connections as follows:

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

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

        Arduino Code:

        We have divided the Arduino code in 3 segments:

        • Declaration Code
        • Void setup
        • Void loop

        We will look at these sections separately now.

        Declaration Code:

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

        Figure 6: Ultrasonic declaration code

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

        Figure 7: LCD declaration

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

        Figure 8: Traffic light variable declaration

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

        Figure 9: Declaration of pedestrian LEDs

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

        Figure 10: Declaration of variables being used for calculations

        Void Setup:

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

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

        We will first set up ultrasonic pins as follows:

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

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

        Figure 12: Setup of Traffic light Pins as Output

        Now we will setup our pedestrian LEDs.

        Figure 13: Setup of Pedestrian LEDs as Output

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

        Figure 14: Initializing LCD

        Void Loop:

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

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

        Figure 15: Syntax of 1st Ultrasonic Sensor

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

        Figure 16: If Loop for Signal 1

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

        Figure 17: Arduino Code

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

        Figure 18: Arduino Code

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

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

        Figure 19: Arduino Code

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

        Figure 20: Arduino Code

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

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

        Figure 21: Arduino Code

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

        Figure 22: Arduino Code

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

        Figure 23: Arduino Code

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

        Figure 24: Arduino Code

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

        Figure 25: Arduino Code

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

        Figure 26: Arduino Code

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

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

        Figure 27: Arduino Code

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

        Figure 28: Arduino Code

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

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

        Figure 29: Arduino Code

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

        Figure 30: Arduino Code

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

        Figure 31: Arduino Code

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

        Figure 32: Arduino Code

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

        Figure 33: Arduino Code

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

        Figure 34: Arduino Code

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

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

        Figure 35: Arduino Code

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

        Figure 36: Arduino Code

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

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

        Figure 37: Arduino Code

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

        Figure 38: Arduino Code

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

        Figure 39: Arduino Code

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

        Figure 40: Arduino Code

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

        Figure 41: Arduino Code

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

        Figure 42: Arduino Code

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

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

        Figure 43: Arduino Code

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

        Figure 44: Arduino Code

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

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

        Figure 45: Arduino Code

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

        Figure 46: Arduino Code

        Results/Working:

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

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

        Figure 47: Simulation Results

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

        Figure 48: Simulation Results

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

        Figure 49: Simulation Results

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

        Figure 50: Simulation Results

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

        Figure 51: Simulation Results

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

        Figure 52: Simulation Results

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

        Figure 53: Simulation Results

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

        Figure 54: Simulation Results

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

        Figure 55: Simulation Results

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

        Figure 56: Simulation Results

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

        Figure 57: Simulation Results

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

        Figure 58: Simulation Results

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

        Interfacing Temperature & Humidity Sensor with Arduino

        Hello everyone! I hope you all will be absolutely fine and having fun. In the tutorial Interfacing Temperature & Humidity Sensor with Arduino I will tell you that how can you interface temperature and humidity sensor named as DHT11 with Arduino and how can you observe the temperature and humidity level using this sensor. This sensor has usually three pins but some of its types has four pins but only the three pins are of importance for us e.g. VCC, GND and the third pin for reading the data from the sensor. In the tutorial Interfacing Temperature & Humidity Sensor with Arduino, I will make a simple Arduino program which will estimate the level of temperature and humidity continuously and will display the value of both temperature and humidity on the serial monitor. You will see that the sensor will give different readings for the different environments.
        Where To Buy?
        No.ComponentsDistributorLink To Buy
        1LCD 16x2AmazonBuy Now
        2DHT11AmazonBuy Now
        3Arduino UnoAmazonBuy Now

        Temperature & Humidity Sensor with Arduino

        I will tell you the step by step procedure that how can you interface DHT11 sensor with Arduino and how to make a simple program in Arduino software to read the data continuously from the sensor and how to display the obtained data on the serial monitor. You can also display this data on Liquid Crystal Display (LCD) as I have discussed in detail in my previous tutorial DC Motor Direction Control using Arduino, DC Motor Speed Control using Arduino, Stepper Motor Direction Control in Arduino and Stepper Motor Speed Control using Arduino.
        • You can download the complete source code here by clicking on the button below.
        • Download .rar file, extract this file and enjoy the complete simulation code.

        Block Diagram

        • First of all, I would like to explain you the algorithm with the help of a block diagram.
        • It will help in better understanding of an algorithm.
        • The block diagram for interfacing of temperature and humidity sensor with Arduino is given in the figure below.
        • Power supply in necessary to turn the whole system ON.
        • DHT11 is connected with the Arduino UNO.
        • Arduino UNO reads the data from the DHT11 sensor and displays the obtained data on the serial monitor.
        • That data will also be displayed on the LCD.

        Circuit Diagram

        • The complete wiring diagram for this project is shown in the figure below.
        • You can run this project properly, by making the circuit first, identical to the circuit diagram shown in the figure above.
        • The analog pin A3 of the Arduino UNO will help us in reading the data from the sensor.
        • The other two pins of the sensor are connected to the supply of 5V and ground respectively as you can see from the above figure.

        Flow Chart

        • The flow chart will help you to understand the flow of the program while executing.
        • The flow chart for this project is shown in the figure below.
        • The data from the sensor can be estimated on the serial monitor only after opening the serial port
        • Then data will be displayed on the LCD and at end serial port must be closed in order to avoid the exchange of unwanted commands.

        Source Code Description

        • The source code for this project is given below.
        • You have to just copy and paste the code given below in your Arduino software after properly interfacing DHT11 with the Arduino.
        • After uploading the code onto your Arduino board you will be able to observe the humidity and temperature and humidity level on serial monitor.
        #include<dht.h>// DHT11 humidity sensor library
        #include<LiquidCrystal.h> //LCD library
        dht DHT; //Creating sensor object
        #define DHT11_PIN A3 // Sensor is connected to Arduino pin 3
        LiquidCrystal lcd(8, 9, 10, 11, 12, 13);// LCD connected with Arduino on these pins
        void setup()
        {
          Serial.begin(9600); //setting baud rate
          Serial.println("   =====================================================");
          Serial.println("   ||   Welcome to Temperarue and Humidity Detector   ||");
          Serial.println("   =====================================================");
          Serial.println("");
          lcd.begin(20, 4); // initialinzing the LCD order
          lcd.setCursor(4,1); //Setting the cursor on LCD
          lcd.print("Welcome to");//printing on LCD
          lcd.setCursor(2,2);
          lcd.print("Humidity detector");
          delay(2000);//adding delay of 2 secons or 2000 msec
          }
        void loop()//method used to run the code repeatedly
        {
          int chk = DHT.read11(DHT11_PIN); //Reading data from sensor
          Serial.print(" Humidity = ");//prints on the serial monitor
          Serial.print(DHT.humidity);// prints obtained humidity on serial port
          Serial.print(" g/m^3");
        
          lcd.clear();//clears all the data on LCD
          delay(1000);//adding delay of 1 second
          lcd.display(); //starting the display of LCD after clearing
          lcd.setCursor(0,0);
          lcd.print("Humidity=");
          lcd.print(DHT.humidity);
          lcd.print(" g/m^3");
          
          Serial.print("    \tTemperature = ");//prints on the serial monitor
          Serial.print(DHT.temperature, 1);//prints obtained temperature on serial port
          Serial.println(" degrees");
        
          lcd.setCursor(0,1);
          lcd.print("Temperature=");//prints on LCD
          lcd.print(DHT.temperature, 1);//prints the obtained temperature on LCD
          lcd.print(" deg");
        
          lcd.setCursor(1,2);
          lcd.print("www.TheEngineering");
          lcd.setCursor(4,3);
          lcd.print("Projects.com");
        
          delay(2000);//adding the delay of 2 seconds
          }  
        
        • I am going to explain you that how this code is working!
        • First of all I have added the library in the libraries folder at the destination where the Arduino software is installed.
        • I have defined DHT11’s library in the source code then.
        • Then I have defined the library for LCD.
        • I have defined the pin at which DHT11 is attached with the Arduino board.
        • Then I have defined the Arduino pins at which the LCD in interface.
        • Then by opening the serial port I have started to print the level of temperature and humidity on the serial monitor as well as on the 20×4 LCD.
        • At the end, I have added the delay of 2 seconds so that the speed of the data to be printed on the serial monitor can be reduced to some extent in order to observe properly.
        • This was the brief description of the source code.
        That is all from the tutorial Interfacing Temperature & Humidity Sensor with Arduino. I hope you enjoyed this tutorial. If you are facing any problem regarding any of my tutorials, you can ask me freely in the comments without even feeling any kind of hesitation, I will try my level best to solve you issues in a better way, if possible. I will explore Arduino by making further projects and will share them with you as well. So, till then, Take Care :)

        Introduction to LCD 16x2

        Hello friends, I hope you all are doing great. In today’s tutorial, we will have a look at Introduction to 16x2 LCD Module. LCD stands for liquid crystal display it is mostly used in different electronic projects and devices to display different values. LCD uses liquid crystals for the generation of visible images. 16 x 2 liquid crystal display is a basic LCD module used in DIY electronic projects and circuits. In this LCD module, there are two rows every row consists of sixteen numbers.

        With the two rows in this module, there are sixteen columns. The VA dimensions of these modules are (66 x 16) millimeters and the thickness is 13.2 millimeters. Its operating voltage is plus five or plus three volts. In today's post, we will have a look at working, applications, circuits,  features, advantages and disadvantages. So let's get started with Introduction to 16x2 LCD Module.

        Where To Buy?
        No.ComponentsDistributorLink To Buy
        1LCD 16x2AmazonBuy Now

        Introduction to 16x2 LCD Module

        • LCD(liquid crystal display) is normally used in embedded projects due to its low cost, easy access and flexibility to get programmed.
        • Almost every electronic device we daily see like in you mobile, calculator and some other devices.
        • There is a type of liquid display that has sixteen column and two rows so it is known as 16 x 2 LCD modules.
        • LCD also available in different arrangements like (8 x 1), (10 x 2), (16 x 1), but the 16 x 2 liquid crystal is normally used in embedded projects.
        • In this liquid crystal display, there are thirty-two characters and each of them consists of 5 x 8 pixels.
        • So we can say that character consists of forty pixels or dots and total pixels in this liquid crystal display can be fined as (32 x 40) or 1280 pixels.
        • During its interfacing with a microcontroller, it makes sure that liquid crystal display should be directed about the locations of pixels.

        Pinout of 16x2 LCD Module

        • These are the main pinouts of 16 x 2 LCD that are described here with the detailed
        Pin No: Pin Name:                                         Parameters
        Pin#1  Ground This pin is used to connect the ground.
        Pin#2  +5 Volt At this pinout plus five volts are applied to on the LCD.
        Pin#3 VE This pin used to select the contract of the display.
        Pin#4 Register Select This pinout is used to MCU controller connected led to a shift from command to data mode.
        Pin#5 Read and Write It used for reading and wiring of data.
        Pin#6 Enable It linked with the MCU to toggle among zero and one.
        Pin#7 Data Pin 0 The pinouts from zero to seven are data pinouts and these are linked with the MCU for transmission of data. This liquid crystal module can also operate on the four-bit mode by working on o, 1, 2, and 3 pinouts and others are free.  
        Pin#8 Data Pin 1
        Pin#9 Data Pin 2
        Pin#10 Data Pin 3
        Pin#11 Data Pin 4
        Pin#12 Data Pin 5
        Pin#13 Data Pin 6
        Pin#14 Data Pin 7
        Pin#15 LED Positive This pinout is for turn backlight of led into positive.
        Pin#16 LED Negative Backlight liquid crystal display pinout negative terminal.

        Command codes for 16x2 LCD Module

        • These are some commands codes for 16 x2 LCD modules.
        Sr.No Hex Code                                         Parameters
        1  1 This command will remove data displaying on the screen of lcd.
        2  2 It used to move back home.
        3 4 It used to change location of a cursor to left side.
        4 6 It changes the position of cursor to right side.
        5 5 It used for shift display on right.
        6 7 It used for Shift display one  left
        7 8 It used to off the display and cursor will also off.  
        8 0A It used for both display off, a cursor on.
        9 0C It used for display on, cursor also off.
        10 0E By using this command we can on display, the cursor  will be blinking
        11 0F By this command Display will be on, the cursor also blinking.
        12 10 It changes the location of a cursor to left.
        13 14 It set cursor location to right.
        14 18 It changes the location of the complete display to the left side.
        15 1C It changes the location of the complete display to right side.
        16 80 It used to move the cursor to the first line.
        17 C0 It send the cursor to starting of the second line.
        18 38 2 lines and 5×7 matrix.

        Features of 16x2 LCD Module

        • These are some features of 16x2 LCD Module that are described with the detailed.
        • Its functioning voltages are from 4.7 volts to 5.3 volts.
        • It uses one milliampere current for operation.
        • In this liquid crystal display, we can work both alphabets and numbers.
        • On this module, there are rows each has sixteen characters.
        • Every character of this board has 5 x 8 or 40 pixels.
        • It works on both four and eight bits mode.
        • It display screen backlight is two colour green and blue.

        Registers of LCD

        • In this module there are 2 main types of register first one is data register and the second one is command register. The RS pinout is used for the change the register.
        • If we set zero then the register is command and at one data register will work.
        • Now we discuss these two registers with the detailed.
        Command Register
        • The main function of this register is to save instructions shown on display.
        • That help to a clearing of data changes the location of the cursor and display control.
        Data Register
        • This register saves the date to display on the liquid crystal screen. When we send data to liquid crystal display it moves to the data register, processing of that data will initiate.
        • If we set the value of register at one then the data register will start operation.

        So it is the detailed article on the 16x2 LCD Module if you have any question about ask in comments. Thanks for reading.

        Syed Zain Nasir

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

        Share
        Published by
        Syed Zain Nasir