Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views60 pages

Eee 444 (F)

The Lab Manual for EEE 444 at Green University of Bangladesh outlines experiments involving Arduino, including LED operations, distance measurement, and motion detection. It provides general instructions, safety regulations, and detailed procedures for each experiment, emphasizing the importance of proper circuit construction and code uploading. The manual also highlights common errors and troubleshooting tips related to Arduino usage.

Uploaded by

MD Miraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views60 pages

Eee 444 (F)

The Lab Manual for EEE 444 at Green University of Bangladesh outlines experiments involving Arduino, including LED operations, distance measurement, and motion detection. It provides general instructions, safety regulations, and detailed procedures for each experiment, emphasizing the importance of proper circuit construction and code uploading. The manual also highlights common errors and troubleshooting tips related to Arduino usage.

Uploaded by

MD Miraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Lab Manual

EEE 444
Integrated Design Project II

Department of Electrical and Electronic Engineering

Green University of Bangladesh


Table of Contents
Table of Contents ........................................................................................................................................ ii
General Instructions .................................................................................................................................iii
Laboratory Regulations and Safety Rules .......................................................................................... viii
Experiment 1 Arduino-controlled LED Blinking and Fading Operations ......................................... 9
Experiment 2 Ultrasonic Distance Measurement using Arduino ..................................................... 14
Experiment 3 Real-time Motion Detection using PIR Sensor ............................................................ 18
Experiment 4 Data Visualization using 16x2 LCD with Arduino ..................................................... 22
Experiment 5 Digital Counter Implementation using Seven Segment Display .............................. 28
Experiment 6 Speed and Rotation Control of DC Motors using L298 Motor Driver ..................... 32
Experiment 7 Input-based Servo Position Control using Arduino ................................................... 40
Experiment 8 Data Entry System using 4x4 Membrane Keypad ...................................................... 45
Experiment 9 Proximity Door Access Control System ....................................................................... 49
Experiment 10 Implementation of an Arduino-based Calculator ..................................................... 55

Department of EEE, GUB ii | P a g e


General Instructions

Introduction
There are 2.5 hours allocated to a laboratory session in Integrated Design Project II. It is a
necessary part of the course where the attendance is compulsory. Here are some guidelines to
help the students perform the experiments and submit appropriate reports.

i. Students will read all the instructions carefully and carry them all out.
ii. Students will ask for a demonstration if s/he is unsure of anything.
iii. Student will record actual results and comment on them if the results are unexpected.
iv. Students will write full and suitable conclusions for each experiment.
v. If any student has any doubt about the safety of any procedure, s/he will contact the
demonstrator beforehand.

Arduino Uno
The Arduino Uno is a versatile and widely-used microcontroller board designed around the
ATmega328P microcontroller. It is an excellent choice for both beginners and experienced
developers in the field of electronics and embedded systems due to its user-friendly interface and
extensive community support.

Key Features of Arduino Uno


• Microcontroller: ATmega328P
• Digital I/O Pins: There are 14 digital pins, 6 of which are PWM (Pulse Width Modulation)
pins. These pins can generate PWM signals suitable for various control applications like
motor speed control, LED fading, etc.
• Analog Pins: Arduino Uno has 6 analog pins. These pins are input pins and can not be
used as output pins. The analog pins are used to receive analog signals from other
circuitry/elements.
• Clock Speed: Arduino Uno has an in-build liquid crystal that generates 16 MHz clock
pulse.
• Power Supply: There are three options to power up the Arduino Uno. The board can
operate on an external supply from 6 to 20 volts. The power supply options are;
o USB Port
o DC Power Jack
o Vin Pin
• ICSP Header: In-Circuit Serial Programming header enables programming the
microcontroller without removing it from the board.
• Reset Button: The reset button, if pressed, initiates the system again from the beginning.

Department of EEE, GUB iii | P a g e


Arduino Usage
The Arduino Uno is an open-source user-friendly platform. It provides a user the flexibility to
program with great ease. Projects starting from beginner level to complex levels can be
implemented using Arduino. Additionally, the Arduino developers have provided ample
resources of projects and examples to guide a user to his desired project. The resources can be
easily accessed at https://www.arduino.cc/.

Figure 1 Arduino Uno Construction

The concise board specifications are provided in Table 1.

Table 1 Arduino Uno Specification

Microcontroller ATmega328P
Operating Voltage 5V
Input Voltage (Recommended) 7 – 12 V
Input Voltage (Limit) 6 – 20 V
Digital I/O Pins 14 (of which 6 provide PWM output)
Analog Input Pins 6
DC Current Per I/O Pin 20 mA
DC Current for 3.3V Pin 50 mA
Flash Memory 32 kB (ATmega328P) of which 0.5 kB used by
bootloader
SRAM 2 kB (ATmega328P)
EEPROM 1 kB (ATmega328P)
Clock Speed 16 MHz

Department of EEE, GUB iv | P a g e


Arduino IDE
The Arduino works in synchronization with an Integrated Development Environment, called
Arduino IDE. This software is well-designed to allow users program efficiently. Arduino IDE
holds the capabilities of code completion, compilation, testing, and debugging.

Figure 2 Arduino IDE Interface

Circuit Construction
Throughout these experiments we will be using Arduino Uno and basic components to construct
circuits. The steps for wiring a circuit should be completed in the following order described
below;

1. Turn off the power supply of Arduino before building the circuit.
2. Make sure to connect regulated supply voltage to the Vin and GND pins of the Arduino
if you are not using the USB cable or DC power jack.
3. Use different grounds for Arduino Uno and the other circuitry.
4. Never detach the ATmega328P IC from the board!!!

Code Uploading
1. Connect the Arduino Uno to the computer via the provided USB cable. Do not use external
cables for code uploading.
2. Open Arduino IDE. Create a new sketch and save it in an appropriate folder.
3. Write down your code. Make sure the code has no typos and syntax errors.

Department of EEE, GUB v|Page


4. Go to “Select Board and Port” option and select Arduino Uno as the board and select the
port that has Arduino Uno written beside it.
5. Verify the code and compile.
6. Upload the code to the Arduino Uno.
7. Detach the USB cable if the Arduino is powered from external source.
8. Connect the other circuitry to the Arduino Uno.
9. Show the circuit to lab assistant/course teacher before powering on the circuit.

Figure 3 Sample Construction of Arduino Circuit

Common Causes of Errors


While experimenting, several issues may come up. Some of the most common errors encountered
during experimentation are described below;

1. Power Supply Issues: The circuit might not turn on or not working properly. There can
be two possible reasons;
a. Insufficient Supply: If the Arduino is not receiving enough power, the circuit
might not work properly. This can happen if the power supply is weak or too
many peripherals are connected.
b. Incorrect Voltage: Supplying incorrect voltage to the Arduino can cause damage
to the board as well as to the circuit.
2. Faulty Connections: Arduino circuits are constructed using jumper wires most often. The
faulty connections can take place due to loosen wires, incorrect wiring, faulty connection
leads, etc.
3. Incorrect Pin Configuration: Incorrect pin assignments in the code can lead to unexpected
results. For example, setting a pin as an output when it should be an input. Again,
exceeding the current limits of the pin (usually 40 mA per pin) can cause damage to the
board.

Department of EEE, GUB vi | P a g e


4. Defective Components: Usage of faulty peripherals might lead to malfunction of the
circuits. Also, different types of shields are available to work with Arduino. Incompatible
shield or modules can damage the board.
5. Software Problems: Misconfiguration of the Arduino IDE can cause errors in uploading
codes to the Arduino. The possible reasons can be as follows;
a. Faulty Installation: The Arduino IDE should be installed properly for proper
functioning. Additionally, the software must be downloaded from the root site of
Arduino (https://www.arduino.cc/en/software). The latest version of the software
should be downloaded.
b. Inconsistent Library: Depending on the circuit, additional library might be
needed. In that case, the library should be installed to the Arduino IDE.
Inconsistency in adding the library might lead to malfunctioning.
c. Coding Errors: Errors in code, typos, syntax can cause errors.
d. Board and Port: This is the most common error occurred during experiment. The
board name and the port must be selected before uploading the code to Arduino.
6. USB Connection Issue: The code is uploaded to Arduino using USB cable. If the cable is
faulty, the communication might not establish. Besides, if the drivers of the computer are
not properly configured, the computer might not recognize Arduino.
7. Memory Overload: The Arduino has limited specification of its RAM and EEPROM.
Overloading these can cause program to crash and behave unpredictably. Hence, proper
Arduino board must be selected depending on the length and size of the program.
8. Bootloader Problem: Bootloader is the first piece of code to be loaded and run when the
system initiates. It provides an interface for the user to load an operating system and
applications. If the bootloader is faulty, the Arduino will not work and will not allow new
sketch to upload to the board. In such cases, the bootloader should be fixed using another
external Arduino or other boards.
9. Interference and Noise: Electrical noise in the empty pins or electromagnetic interference
might lead to problems in circuits.

Department of EEE, GUB vii | P a g e


Laboratory Regulations and Safety Rules

The following regulations and safety rules must be followed in all concerned laboratory locations;

1. It is the duty of all concerned who use any electrical laboratory to take all reasonable steps
to safeguard the HEALTH and SAFETY of themselves and all other users and visitors.
2. Be sure that all equipment is properly working before using them for laboratory exercises.
Any defective equipment must be reported immediately to the lab instructors or lab
technical staff.
3. Students are allowed to use only the equipment provided in the experiment manual.
4. Power supply terminals connected to any circuit are only energized in the presence of the
instructor or laboratory staff.
5. Students should keep a safe distance from the circuit breakers, electric circuits, or any
moving parts during the experiment.
6. Avoid any part of your body from being connected to the energized circuit and ground.
7. Switch off the equipment and disconnect the power supplies from the circuit before
leaving the laboratory.
8. Observe cleanliness and proper laboratory housekeeping of the equipment and other
related accessories.
9. Wear proper clothes and safety gloves or goggles required in working areas that involve
fabrications of printed circuit boards, chemical process control systems, antenna
communication equipment, and laser facility laboratories.
10. Double-check your circuit connections specifically in handling electrical power machines,
AC motors, and generators before switching “ON” the power supply.
11. Make sure that the last connection to be made in your circuit is the power supply and the
first thing to be disconnected is also the power supply.
12. Equipment should not be removed, or transferred to any location without permission
from the laboratory staff.
13. Software installation in any computer laboratory is not allowed without permission from
the laboratory staff.
14. Computer games are strictly prohibited in the computer laboratory.
15. Students are not allowed to use any equipment without proper orientation and actual
hands-on equipment operation.
16. Smoking and drinking are strictly prohibited in the laboratory.
17. All these rules and regulations are necessary precautions in the Electrical Laboratory to
safeguard the students, laboratory staff, the equipment, and other laboratory users.

Department of EEE, GUB viii | P a g e


Experiment 1
Arduino-controlled LED Blinking and Fading Operations

1.1 Objectives
1. To familiarize with Arduino IDE
2. To understand Arduino I/O interfacing using Arduino coding

1.2 Learning Outcomes


After completion of this experiment, the students will be able to

1. Have a basic understanding of the Arduino IDE and the setup procedure of
Arduino Uno with the IDE
2. Understand the structure of the Arduino code
3. Know the operations of digital and analog I/O pins of Arduino and their
interfacing with LEDs, resistors, and potentiometers.
4. Write codes to blink LED arrays, fade LED brightness

1.3 Theory
Arduino is an open-source development board with integrated circuit components. The
brain of Arduino is a microcontroller. For Arduino Uno, it is the ATmega328P
microcontroller. The board provides the necessary circuit setup for the microcontroller
and creates provisions for the user to access the input and output pins of the
microcontroller and control them using simple codes. Arduino Uno has 14 digital pins
and 6 analog pins.

The simplest interfacing with these pins can be done using LEDs. LEDs are semiconductor
devices that emit light upon providing appropriate voltage at their anode and cathode
terminals. The anode of the LED is connected to one of the digital pins of the Arduino
Uno. Depending on the state of that particular digital pin, the LED will turn on or off. The
pin state, timing, and other controls are established through code uploaded to the Arduino
microcontroller using Arduino IDE.

The fading operation provides control over the brightness of the LED. Depending on the
input voltage supplied to the LED terminals, the brightness of the LED varies. The typical
output voltage of the digital pins is 5V. However, to apply a varying voltage at the LED
terminal, a PWM wave is generated at the digital pins (only pins 3, 5, 6, 9, 10, 11). The duty
cycle of the PWM is controlled by a potentiometer connected to one of the analog pins of
the Arduino. With the varying duty cycle, the average voltage of the PWM is reduced or
increased as per Equation 1.1, where 𝐷 is the duty cycle. This average voltage appears at
the digital pin and in terms controls the brightness of the LED.

Department of EEE, GUB 9|Page


𝑉𝑎𝑣𝑔 = 𝑉𝑚𝑎𝑥 × 𝐷 (1.1)

1.4 Required Equipment


1. Arduino Uno (1 Pcs)
2. 220Ω resistors (1 Pcs)
3. LED (1 Pcs)
4. 1 kΩ potentiometer (1 Pcs)
5. Breadboard
6. Jumper wires

1.5 Circuit Diagram

Figure 1.1 LED Blinking Circuit

Figure 1.2 LED Fading Circuit

Department of EEE, GUB 10 | P a g e


1.6 Arduino Codes
(a) Code for LED blinking

const int ledPin = 11; // Define the pin where the LED is connected
void setup()
{
pinMode(ledPin, OUTPUT); // Initialize the LED pin as an output
}

void loop()
{
digitalWrite(ledPin, HIGH); // Turn the LED on
delay(1000); // Wait for 1000 milliseconds (1 second)
digitalWrite(ledPin, LOW); // Turn the LED off
delay(1000); // Wait for 1000 milliseconds (1 second)
}

(b) Code for LED fading without potentiometer

int led = 11; // the PWM pin the LED is attached to


int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
void setup()
{
pinMode(led, OUTPUT); // declare pin 9 to be an output:
}

void loop()
{
analogWrite(led, brightness); // set the brightness of pin 9
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness <= 0 || brightness >= 255)
{ fadeAmount = -fadeAmount; } // wait for 30 milliseconds to see the dimming effect
delay(3000);
}

(c) Code for LED fading using potentiometer

// Define pin numbers


const int ledPin = 9; // Pin connected to the LED
const int potPin = A0; // Pin connected to the potentiometer

Department of EEE, GUB 11 | P a g e


// Variable to hold potentiometer value
int potValue = 0; // The value read from the potentiometer
int ledBrightness = 0; // The brightness of the LED

void setup() {
pinMode(ledPin, OUTPUT); // Initialize the LED pin as an output
}

void loop() {
// Read the potentiometer value (0 to 1023)
potValue = analogRead(potPin);
// Map the potentiometer value to a range suitable for PWM (0 to 255)
ledBrightness = map(potValue, 0, 1023, 0, 255);
// Set the LED brightness using PWM
analogWrite(ledPin, ledBrightness);
// Small delay to make the response smoother
delay(10);
}

1.7 Procedure
1. Place the LED on the breadboard.
2. Connect a 220 Ω resistor to the anode terminal of the LED (the longer lead).
3. Connect the other terminal of the resistor to the digital pin 11 of the Arduino Uno
via a jumper wire.
4. Connect the cathode terminal of the LED (the shorter lead) to the ground pin of
the Arduino Uno.
5. Cross-check the circuit with the one in Figure 1.1.
6. Connect the Arduino Uno to the computer using the USB cable.
7. Open the Arduino IDE and create a new sketch. Write the Code (a).
8. Select Arduino Uno as the board.
9. Save, compile, and upload the code to the Arduino Uno. Check the output.
10. Now do the same for Code (b) and check the output.
11. For the LED fading using a potentiometer, repeat steps 1-4, however, connect the
LED to digital pin 9 (PWM pin) of the Arduino Uno.
12. Place a 1 kΩ potentiometer on the breadboard. Connect the first and third pins of
the potentiometer to the 5V and GND pins of the Arduino Uno.
13. Connect the middle pin of the potentiometer to the A0 pin of the Arduino Uno.
Cross-check the circuit with the one in Figure 1.2.
14. Upload the Code (b) to Arduino Uno and check the output for different values of
the potentiometer.

Department of EEE, GUB 12 | P a g e


1.8 Lab Tasks
1. Write code for an LED-chaser circuit. The number of LEDs is five.

1.9 Report Tasks


1. Write a program to blink an LED with variable delay. The delay will increase from
200 ms to 2000 ms with an increment of 200 ms. Afterwards, the delay will decrease
with the same step size.
2. Write a program to blink four LEDs (Red, Green, Blue, and Yellow) sequentially.
3. Write a program to blink four LEDs (Red, Green, Blue, and Yellow). Among these,
the Red and Green LEDs will fade in and fade out while the other LEDs will blink
instantaneously.

1.10 Report Questions


1. What is the purpose of the digital pins on an Arduino board, and how are they
typically labeled?
2. Are there any limitations or constraints to keep in mind when using analogRead()
on an Arduino board?
3. What is the function of the pinMode() function in Arduino, and why is it important
when working with digital pins?
4. What is the maximum and minimum voltage range for both digital and analog
pins on most Arduino boards?
5. What is the difference between digital pins and analog pins on an Arduino board?

Department of EEE, GUB 13 | P a g e


Experiment 2
Ultrasonic Distance Measurement using Arduino

2.1 Objectives
1. To understand the internal working principle of ultrasound sonar sensor
2. To interact with sensor modules using Arduino interfacing pins

2.2 Learning Outcomes


After completion of this experiment, the students will be able to

1. Explain the principle of ultrasonic distance measurement from the concept of


sound wave reflection
2. Measure the distance between a certain object and the sensor
3. Use ‘Serial Monitor’ of Arduino IDE for data visualization

2.3 Theory
Ultrasonic sonar sensors, also known as ultrasonic distance sensors or ultrasonic
rangefinders, are electronic devices used for measuring distances or detecting objects
within a certain range. These sensors work on the principle of echolocation, similar to how
bats and dolphins use sound waves to navigate and perceive their environment. The
sensor includes an ultrasonic transmitter that emits high-frequency sound waves
(ultrasonic waves) into the surrounding environment. These sound waves are inaudible
to the human ear, typically in the ultrasonic range (around 40 kHz or higher). It also
contains a receiver that is capable of detecting the reflected sound waves (echo) when they
bounce off an object. The time taken for the emitted sound wave to return to the sensor is
used to calculate the distance to the object.

Figure 2.1 Working Principle of Sonar Sensor

Department of EEE, GUB 14 | P a g e


The HC-SR04 module has 4 I/O pins. The VCC and GND pins are the power pins of the
module. The TRIG pin serves as the input to the module and is connected to a digital pin
of Arduino. To initiate the sensor, a calibration pulse of 10µs needs to be sent in this pin.
When the TRIG pin goes LOW, 8 pulses of 40kHz emit from the transmitter, and the
ECHO pin goes HIGH instantly. The pulses, getting reflected from any obstacle are
detected by the receiver and the ECHO pin becomes LOW. If there is no obstacle, the
ECHO pin automatically goes LOW after 38 ms. The HC-SR04 can measure up to 400 cm.

The distance is measured as per Equation 2.1; where 𝑣 is the sound velocity in the medium
and 𝑡 is the duration of the HIGH state of the ECHO pin.

𝑑 = 0.5 × 𝑣 × 𝑡 (2.1)

2.4 Required Equipment


1. Arduino Uno (1 Pcs)
2. HC-SR04 Sonar Sensor Module (1 Pcs)
3. 220Ω resistor (1 Pcs)
4. LED (1 Pcs)
5. Breadboard
6. Jumper wires

2.5 Circuit Diagram


The TRIG and ECHO pins are connected to the digital pins 7 and 6 of Arduino Uno. An
LED is connected to the digital pin 13 via a 220Ω resistor.

Figure 2.2 Circuit Setup for Distance Measurement

Department of EEE, GUB 15 | P a g e


2.6 Arduino Code
const int Trig=7;
const int Echo=6;
const int LED=13;

void setup() {
// put your setup code here, to run once:
pinMode(Trig,OUTPUT);
pinMode(Echo,INPUT);
pinMode(LED,OUTPUT);
Serial.begin(9600); // baud rate
}

void loop() {
// put your main code here, to run repeatedly:
digitalWrite(Trig,LOW);
delayMicroseconds(2); // ensures the TRIG pin is actually LOW
digitalWrite(Trig,HIGH);
delayMicroseconds(10); // creating the 10 microsecond pulse
digitalWrite(Trig,LOW);

long duration, distance; // defining variables


duration=pulseIn(Echo,HIGH);
distance=0.034*duration*0.5; // measuring the distance in cm unit
Serial.print("Distance is: "); // accessing the serial monitor
Serial.println(distance);
delay(100);

if(distance>10)
{
digitalWrite(LED,HIGH);
}
else
{
digitalWrite(LED,LOW);
}
}

2.7 Procedure
1. Place the sonar sensor module on the breadboard.
2. Connect the VCC, GND, TRIG, and ECHO pins of the sensor with the 5V, GND,
digital pin 7, and digital pin 6 of Arduino Uno via jumper wires.

Department of EEE, GUB 16 | P a g e


3. Connect an LED with the digital pin 13 through a resistor of 220Ω.
4. Cross-check the circuit with Figure 2.1
5. Open Arduino IDE and create a new sketch.
6. Write the given code in the sketch.
7. Select ‘Arduino Uno’ as the board.
8. Verify, compile, and upload the code to the Arduino.
9. Open the serial monitor in the Arduino IDE and check the distance.
10. Now place any object in front of the transmitter and check the output
11. Repeat Step 10 for different distances of the object.

2.8 Lab Tasks


1. A sonar sensor is placed at the entrance of a garage in a way that every vehicle
passes the sensor while entering the garage. Modify the given code to count the
number of vehicles that have entered the garage.

2.9 Report Tasks


(a) Write an Arduino program to detect the distance of an object using a sonar sensor
and turn on LED lights based on the following conditions;
i. Distance < 5 cm: 1 red LED
ii. 5 cm < Distance < 10 cm: 2 red LEDs
iii. 10 cm < Distance < 20 cm: 3 red LEDs
iv. A green LED to indicate the object is out of this range but in the detectable
range
v. A blue LED to indicate there are no detectable objects

2. A distance-averaging system has been designed using a sonar sensor. The sensor
takes 20 distance values with an interval of 5s. If the average distance exceeds a
certain value, the system turns on an alarm. Write the code for this system.

2.10 Report Questions


1. What is the range of values returned by the analogRead function, and how is it
related to the resolution of the analog-to-digital converter (ADC) on the Arduino
board?
2. How can you improve the accuracy of readings obtained with analogRead?
3. Discuss situations where you might choose to use pulseIn instead of digitalRead or
analogRead for signal measurement.
4. How can you use the analogRead function to measure the voltage of a sensor that
provides a voltage range beyond the Arduino's reference voltage?
5. Describe real-time constraints and considerations when using pulseIn or digitalRead
in applications that require precise timing, such as robotics or motor control.

Department of EEE, GUB 17 | P a g e


Experiment 3
Real-time Motion Detection using PIR Sensor

3.1 Objectives
1. To understand the internal construction and working principle of PIR motion
sensor
2. To interface the PIR sensor with Arduino Uno for real-time motion sensing

3.2 Learning Outcomes


After the completion of this experiment, the student will be able to

1. Explain the IR-based motion sensing principle


2. Set up a PIR sensor with Arduino Uno to control a system
3. Utilize the concept of ‘Single Trigger’ and ‘Repeating Trigger’ for toggling between
different operating stages of the PIR sensor

3.3 Theory
Passive Infrared Sensor is used to automate systems based on the motion sensed around
them. The name suggests two key operating principles of this sensor. The term ‘Infrared’
indicates that the sensor operates utilizing the IR spectrum and the term ‘Passive’ suggests
that the sensor itself does not produce any IR spectrum. The underlying theory of PIR
sensors is based on the detection of changes in infrared radiation emitted by objects within
the range of the sensor.

Figure 3.1 Working Principle of PIR Sensor

The internal construction of PIR includes two pyroelectric materials that generate a
voltage signal when exposed to changes in IR radiation within its range. Objects emit IR

Department of EEE, GUB 18 | P a g e


in the form of temperature. The PIR sensor detects the temperature differences between
the background and the objects in motion. When an object moves, it momentarily changes
the temperature of the sensor’s view which is detected as an electric signal. The signal is
then further analyzed to trigger an event, in other words, it decides whether the change is
significant enough. A Fresnel lens is placed above the pyroelectric materials. The lens
converges the IR rays from different directions to the front face of the pyroelectric
materials.

Figure 3.2 PIR Sensor Pin Diagram

The PIR sensor has three pins among which two are the power pins and one is the output
pin, D0. Whenever the sensor detects a motion, D0 goes HIGH. There are two
potentiometers for sensitivity and time delay adjustments. The sensitivity controls the
detection range of the sensor (3m ~ 7m) whereas the time delay adjusts the duration of the
HIGH state of the D0 pin after the detection of a movement. It ranges from 3 seconds to 5
minutes.

Figure 3.3 Triggering Operation of PIR Sensor

Department of EEE, GUB 19 | P a g e


The triggering modes are used to control the response type. In single triggering mode, D0
will go HIGH once it detects a motion. After the set delay time, D0 will go LOW. On the
other hand, in repeated triggering mode, D0 will remain HIGH as long as the motion
remains within the range.

3.4 Required Equipment


1. Arduino Uno (1 Pcs)
2. HC-SR501 PIR Sensor Module (1 Pcs)
3. LED (1 Pcs)
4. 220Ω resistor (1 Pcs)
5. Breadboard
6. Jumper wires

3.5 Circuit Diagram


The D0 pin is connected to digital pin 7 of the Arduino Uno. An LED is connected to
digital pin 13 through a 220Ω resistor.

Figure 3.4 Circuit Setup for PIR Sensor

3.6 Arduino Codes


const int pir=7;
int pir_state;
const int led=13;
void setup() {
pinMode(pir,INPUT);
pinMode(led,OUTPUT);
Serial.begin(9600);
}

void loop() {:
pir_state=digitalRead(pir);
if(pir_state==HIGH)

Department of EEE, GUB 20 | P a g e


{
digitalWrite(led,HIGH);
}
else
{
digitalWrite(led,LOW);
}
Serial.print("State: ");
Serial.println(pir_state);
delay(200);
}

3.7 Procedure
1. Place the PIR sensor module on the breadboard.
2. Connect the VCC, GND, and D0 pins of the sensor with the 5V, GND, and digital
pin 7 of Arduino Uno via jumper wires.
3. Connect an LED with the digital pin 13 through a resistor of 220Ω.
4. Cross-check the circuit with Figure 3.4.
5. Open Arduino IDE and create a new sketch.
6. Write the given code in the sketch.
7. Select ‘Arduino Uno’ as the board.
8. Verify, compile, and upload the code to the Arduino.
9. Move your hand across the sensor module and check the output for single trigger
mode.
10. Move your hand across the sensor module and check the output for repeated
trigger mode.
11. Check the serial monitor of Arduino IDE for both steps 9 and 10.

3.8 Report Tasks


1. The corridors of the annex buildings of Green University of Bangladesh have PIR-
enabled lights installed. However, the range adjustment control of one of the lights
is somehow damaged. Hence, sonar sensors have been used to define a perimeter
around the PIR sensor. Any movement within this perimeter turns on the specific
light. Design the above system and write code for it. Assume the value of the
perimeter.
2. A smart parking system combines a sonar sensor and PIR sensor to effectively
identify the occupancy of parking slots. LEDs are used to indicate the occupancy
status. Write code for the system with your own design considerations.

Department of EEE, GUB 21 | P a g e


Experiment 4
Data Visualization using 16x2 LCD with Arduino

4.1 Objectives
1. Configure 16x2 LCD to receive and display data from Arduino Uno
2. Display custom characters in LCD

4.2 Learning Outcomes


After the completion of the experiment, students will be able to

1. Connect 16x2 LCD with Arduino Uno and configure different modes
2. Transmit data from Arduino Uno to LCD and perform different display operations
3. Access byte levels to display custom characters in LCD

4.3 Theory
Liquid Crystal Display (LCD) is a type of flat panel display that uses liquid crystals in its
primary form of operation typically found in smartphones, televisions, computer
monitors, and instrument panels. A 16x2 LCD has 2 lines with 16-character box in each
line. Again, each character box is made up of a 5x8 (column x row) pixel matrix. The
character boxes are identified by 𝐶𝑖 𝑅𝑗 where 𝐶 represents the column and 𝑖 ranges from 0
to 15. 𝑅 refers to the row and 𝑗 ranges from 0 to 1.

Figure 4.1 Pinouts and Matrix of 16x2 LCD

The LCD unit has 16 pins to interface it with the Arduino Uno among which 8 pins are
used for data transmission and the rest are used to configure the LCD in different modes.
The detailed pin descriptions are provided in Table 4.1.

Department of EEE, GUB 22 | P a g e


Table 4.1 Pin Description of 16x2 LCD

Pin
Pin Pin Name Pin Description Pin Connection
No.
1 VSS/GND Ground Ground of MCU
Supplies power to the LCD
2 VCC/VDD +5V Supply +5V of MCU
Contrast Adjusts the contrast of the
3 VO Rheostat
Control LCD
LOW for Command Register
4 RS Register Select Digital pin of MCU
HIGH for Data Register
LOW for WRITE operation
5 R/W Read/Write Digital pin of MCU
HIGH for READ operation
Enable the READ/WRITE Digital pin of MCU
6 E Enable
operation (always HIGH)
4-bit or 8-bit data transmission
7-14 D0-D7 8-bit Data Pins Digital pins of MCU
between LCD and MCU
15 A Anode Power supply to the backlight +5V supply of MCU
16 C/K Cathode of the LCD Ground of MCU

This experiment will utilize 4-bit data transmission and so D4-D7 will be connected to the
Arduino Uno. Though 4-bit transmission mode is slower than 8-bit mode as data is
transmitted nibble by nibble in a 4-bit system, it reduces the number of connections
required.

To display custom characters in LCD, the byte-level matrices of the LCD need to be
accessed. An array referring to the custom character needs to be incorporated into the
code.

Figure 4.2 Byte-level Access for Custom Characters

Department of EEE, GUB 23 | P a g e


4.4 Required Equipment
1. Arduino Uno (1 Pcs)
2. Hitachi HD44780 LCD/Compatible model (1 Pcs)
3. 1kΩ potentiometer (1 Pcs)
4. Breadboard
5. Jumper wires

4.5 Circuit Diagram


The power pins of the LCD are connected to the power pins of the Arduino Uno. The
contrast control pin of the LCD is connected to the middle pin of the potentiometer. The
rest of the pins are connected as per Table 4.2.

Table 4.2 Connection Details of LCD and Arduino

LCD Pins Arduino Pins


RS Digital pin 11
R/W GND
E 10
D4-D7 Digital pins 5-2
A VCC
C GND

Figure 4.3 Connection Diagram of LCD and Arduino Uno

Department of EEE, GUB 24 | P a g e


4.6 Arduino Codes
(a) Code for displaying ASCII characters

#include<LiquidCrystal.h>
const int RS= 11;
const int E=10;
const int D4=5;
const int D5=4;
const int D6=3;
const int D7=2;
LiquidCrystal lcd(RS,E,D4,D5,D6,D7); // Creates an LCD object. Parameters: (rs, enable, d4,
// d5, d6, d7)

void setup() {
// put your setup code here, to run once:
lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions
(width and height) of the display
}

void loop() {
// put your main code here, to run repeatedly:
lcd.print("Arduino"); // Prints "Arduino" on the LCD
delay(3000);
lcd.setCursor(2,1); // Sets the location at which subsequent text written to the LCD will be
// displayed
lcd.print("LCD Tutorial");
delay(3000); // 3 seconds delay
lcd.clear(); // Clears the display
lcd.blink(); //Displays the blinking LCD cursor
delay(4000);
lcd.setCursor(7,1);
delay(3000);
lcd.noBlink(); // Turns off the blinking LCD cursor
lcd.cursor(); // Displays an underscore (line) at the position to which the next character
//will be written
delay(4000);
lcd.noCursor(); // Hides the LCD cursor
lcd.clear(); // Clears the LCD screen
}

(b) Code for displaying custom characters

#include <LiquidCrystal.h>
// Array of bytes
// B stands for binary formatter and the five numbers are the pixels

Department of EEE, GUB 25 | P a g e


byte heart[8] = {B00000, B01010,B11111, B11111, B01110, B00100, B00000, B00000};
byte smile[8] = {B00000, B00000, B01010, B00000, B10001, B01110, B00000, B00000};
byte lock[8] = {B01110, B10001, B10001, B11111, B11011, B11011, B11111, B00000};
byte character[8] = {B11111, B10101, B11111, B01010, B01110, B11111, B01110, B01110};

const int RS= 11;


const int E=10;
const int D4=5;
const int D5=4;
const int D6=3;
const int D7=2;
// Creates an LCD object. Parameters: (rs, enable, d4, d5, d6, d7)
LiquidCrystal lcd(RS,E,D4,D5,D6,D7);

void setup() {
// Initializes the interface to the LCD screen, and specifies the dimensions of the display
lcd.begin(16,2);
lcd.createChar(0, heart); // Create a custom character
lcd.createChar(1, smile);
lcd.createChar(2, lock);
lcd.createChar(3, character);

// Clears the LCD screen


lcd.clear();

// Print a message to the LCD


lcd.print("Custom Character");
}

void loop() {
// put your main code here, to run repeatedly:
lcd.setCursor(1, 1);
lcd.write(byte(0)); // Display the custom character 0, the heart

lcd.setCursor(5, 1);
lcd.write(byte(1));

lcd.setCursor(9, 1);
lcd.write(byte(2));

lcd.setCursor(13, 1);
lcd.write(byte(3));
}

Department of EEE, GUB 26 | P a g e


4.7 Procedure
1. Place the LCD on the breadboard and connect it to the Arduino Uno and
potentiometer as per Table 4.2. Cross-check the circuit with the one in Figure 4.3.
2. Adjust the contrast of the LCD by rotating the potentiometer knob.
3. Open a new sketch in Arduino IDE and write Code (a).
4. Verify, compile, and upload the code to the Arduino.
5. Power up the circuit and observe the output.
6. Open another new sketch in Arduino IDE and write Code (b).
7. Repeat steps 4 and 5.

4.8 Lab Tasks


1. Write code for the custom character provided by the course instructor during the
lecture.

4.9 Report Tasks


1. Write a code to display the analog data taken from a potentiometer connected to
the Arduino.
2. Write a code to turn on/off an LED using a pushbutton. The status of the LED will
be displayed on the LCD.
3. Write a code to display the data obtained from the sonar sensor.
4. Write a code that will display “GUB EEE Green” in the middle of the first row of a
16x2 LCD. In the second row, there will be scrolling text from right to left. The text
should be “Your nickname–IDP2”.

4.10 Report Questions


1. What are the advantages of using I2C or SPI communication protocols for
connecting an LCD to an Arduino and when might you prefer one over another?
2. What is the purpose of a potentiometer in an LCD setup with Arduino, and how
is it used for fine-tuning the display?
3. What is the difference between a 16x2 and a 20x4 LCD, and how might your
Arduino code need to change when switching between these two types?
4. Make a discussion on the usage of I2C to reduce the number of I/O pins of LCD.
Provide appropriate code snippets to validate your discussion.

Department of EEE, GUB 27 | P a g e


Experiment 5
Digital Counter Implementation using Seven Segment Display

5.1 Objectives
1. To interface a segment display with Arduino Uno without any driver circuit
2. To display numbers on the seven-segment display

5.2 Learning Outcomes


After completion of this experiment, the students will be able to

1. Connect seven-segment displays with Arduino Uno


2. Control the LEDs of the display using codes

5.3 Theory
A seven-segment display is commonly used for displaying numeric data in devices like
digital clocks and calculators. It has seven individual LEDs (labeled ‘a’ to ‘g’ in Figure 5.1)
along with a dot LED, ‘dp’. The LEDs can be accessed through individual pins. By
controlling the voltage states at these pins, numbers 0 to 9 can be displayed. Additionally,
some alphabets can be displayed. Depending on the shorted terminals of the LEDs, two
types of displays are available;

a. Common Cathode (CC): Here all the cathode terminals of the LEDs are
shorted and only one pin is available.
b. Common Anode (CA): Here all the anode terminals of the LEDs are shorted
and only one pin is available.

Figure 5.1 Seven Segment Display Variants (CA and CC)

Department of EEE, GUB 28 | P a g e


5.4 Required Equipment
1. Arduino Uno (1 Pcs)
2. Seven Segment Display (CA) (1 Pcs)
3. 220Ω resistors (7 Pcs)
4. Breadboards
5. Jumper wires

5.5 Circuit Diagram


A common anode seven-segment display is connected to the Arduino through 220Ω
resistors. The ‘dp’ is not connected.

Figure 5.2 Digital Counter Setup

5.6 Arduino Codes


// Pin connections for 7-segment display
int segA = 6;
int segB = 7;
int segC = 8;
int segD = 2;
int segE = 3;
int segF = 5;
int segG = 4;

Department of EEE, GUB 29 | P a g e


int digits[10][7] = {
{LOW, LOW, LOW, LOW, LOW, LOW, HIGH}, // 0
{HIGH, LOW, LOW, HIGH, HIGH, HIGH, HIGH}, // 1
{LOW, LOW, HIGH, LOW, LOW, HIGH, LOW}, // 2
{LOW, LOW, LOW, LOW, HIGH, HIGH, LOW}, // 3
{HIGH, LOW, LOW, HIGH, HIGH, LOW, LOW}, // 4
{LOW, HIGH, LOW, LOW, HIGH, LOW, LOW}, // 5
{LOW, HIGH, LOW, LOW, LOW, LOW, LOW}, // 6
{LOW, LOW, LOW, HIGH, HIGH, HIGH, HIGH}, // 7
{LOW, LOW, LOW, LOW, LOW, LOW, LOW}, // 8
{LOW, LOW, LOW, LOW, HIGH, LOW, LOW} // 9
};

void setup() {
// Set all pins for the 7-segment display as output
pinMode(segA, OUTPUT);
pinMode(segB, OUTPUT);
pinMode(segC, OUTPUT);
pinMode(segD, OUTPUT);
pinMode(segE, OUTPUT);
pinMode(segF, OUTPUT);
pinMode(segG, OUTPUT);

void loop() {
for (int i = 0; i <= 9; i++) {
displayNumber(i);
delay(1000); // Delay for 1 second before changing number
}
}

void displayNumber(int num) {


int* segments = digits[num];
digitalWrite(segA, segments[0]);
digitalWrite(segB, segments[1]);
digitalWrite(segC, segments[2]);
digitalWrite(segD, segments[3]);
digitalWrite(segE, segments[4]);
digitalWrite(segF, segments[5]);
digitalWrite(segG, segments[6]);
}

Department of EEE, GUB 30 | P a g e


5.7 Procedure
1. Place the seven-segment display on the breadboard.
2. Connect 220Ω resistor to each of the LED pins
3. Connect the Vcc pin to the power source through a 220Ω resistor.
4. Open a new sketch in Arduino IDE and write the given code.
5. Verify, compile, and upload the code to Arduino.
6. Power up the circuit and observe the output.

5.8 Lab Tasks


1. Modify the given code for CC display.
2. Modify the given code so that after displaying 9, it decreases to 0 with step size 1.

5.9 Report Tasks


1. Write a code for a simple stopwatch that can count from 00 to 99 using two seven-
segment displays.
2. A potentiometer is connected to an Arduino Uno. The system converts the values
obtained from the potentiometer within the range of 0 to 9. The number is
displayed on a seven-segment display. Write code for the system. You can choose
between CC and CA.
3. Write code for blinking a specific number in the seven-segment display. The
blinking should be stopped once a push button attached to the Arduino is pressed.
The blinking should start if the pushbutton is pressed again.
4. Prepare a list of alphabets that can be displayed using a seven-segment display.
Include the LED status table for each of them.

Department of EEE, GUB 31 | P a g e


Experiment 6
Speed and Rotation Control of DC Motors using L298 Motor
Driver

6.1 Objectives
1. To control DC motor’s speed and direction of rotation using L298 Dual H-bridge
Motor Driver

6.2 Learning Outcomes


After completion of this experiment, students will be able to

1. Explain the concept of H-bridge circuit


2. Interface L298 motor controller with Arduino Uno
3. Control DC motor’s speed using the principle of PWM

6.3 Theory
Controlling of motors refers to controlling the speed of the motor as well as controlling
the direction of rotation of the motor. The direction of rotation of DC motors can simply
be achieved by swapping the input voltage polarity of the motor whereas the speed can
be controlled by altering the input voltage. Numerous applications require continuous
controlling of these parameters which might be tedious and complex if done manually. A
motor driver can provide the flexibility to control both the speed and direction
simultaneously.

The L298 Dual H-bridge motor driver is a single-board module having L298 IC integrated.
The motor driver has two in-built H-bridges to control the direction of rotation of motors.
With two H-bridges, two motors can be controlled simultaneously. For speed control, the
driver utilizes PWM.

Figure 6.1 L298 Dual H-bridge Motor Driver

Department of EEE, GUB 32 | P a g e


(a) H-bridge Construction and Direction Control: In general, an H-bridge is a simple
circuit containing four switching elements with the load at the center in an H-like
configuration. The switching elements (Q1 … Q4) are usually bipolar or FET
transistors; IGBTs are used for high-voltage applications. The diodes (D1 … D4)
are called catch/freewheeling diodes and are usually of Schottky type.

Figure 6.2 Simplified Diagram of H-bridge

Depending on the ON and OFF state of the switches, different modes of the bridge
are configured. The configuration table relating the modes of the H-bridge and
motor condition is provided in Table 6.1.

Table 6.1 State Table for H-bridge Controller

Fast Stop Fast Stop Free Run Invalid Invalid


Switch Forward Reverse
(1) (2) Stop (1) (2)
Q1 ON OFF ON OFF OFF ON OFF
Q2 OFF ON OFF ON OFF ON OFF
Q3 OFF ON ON OFF OFF OFF ON
Q4 ON OFF OFF ON OFF OFF ON

The number of states and complexities can be reduced easily. If a setup is done in
such a way that Q2 remains OFF when Q1 is ON and Q3 remains OFF when Q4 is
ON and vice-versa, then the H-bridge can be controlled using only two switches.

Table 6.2 Reduced State Table of the H-bridge Controller

Switch Forward Reverse Fast Stop (1) Fast Stop (2)


Q1 ON OFF ON OFF
Q2 OFF ON OF ON
Q3 OFF ON ON OFF
Q4 ON OFF OFF ON

Department of EEE, GUB 33 | P a g e


Figure 6.3 Current flow for different states of H-bridge

(b) Speed Control using PWM: By altering the duty cycle of the PWM signal, the
average voltage value of the signal can be varied. The PWM pins of the Arduino
Uno can be connected to the L298 driver to vary the speed of the motors.

Figure 6.4 PWM Duty Cycle and Average Voltage

Department of EEE, GUB 34 | P a g e


The motor driver has 13 pins to communicate with the surrounding circuitry shown in
Figure 6.5.

Figure 6.5 Pinouts of the L298 Motor Driver

The detailed pin descriptions are provided in Table 6.3. All the pins are broadly
categorized into four distinct sections; Output pins, Power pins, Speed control pins, and
Direction control pins.

Table 6.3 Pin Descriptions of L298 Motor Driver

Pin Pin Status Description Connected To


OUT1
Connection of Motor A
OUT2
Output pins 5-12 V DC motors
OUT3
Connection of Motor B
OUT4
Supply of the H-bridge
+12V External power supply
and controller IC
Ground of external
GND Ground of the module
power supply
5V output if the 5V-
Power pins enable jumper is
Power supply for the connected;
+5V logic circuitry of the 5V input for the logic
module. circuitry if the 5V-
enable jumper is
disconnected
ENA Enables motor A
Speed control pins PWM pins of Arduino
ENB Enables motor B
IN1 Control the rotation
IN2 Direction control direction of motor A
Digital pins of Arduino
IN3 pins Control the rotation
IN4 direction of motor B

Department of EEE, GUB 35 | P a g e


6.4 Required Equipment
1. Arduino Uno (1 Pcs)
2. L298 Dual H-bridge Motor Controller (1 Pcs)
3. 5V~12V DC motors (2 Pcs)
4. DC power supply (1 Pcs)
5. Jumper wires

6.5 Circuit Diagram


Two DC motors are connected to the motor controller. The control pins of the motor
controller are connected to Arduino as per Table 6.4.

Table 6.4 Connection Details of L298 and Arduino

L298 Pins Arduino Pins


IN1 Digital Pin 7
IN2 Digital Pin 6
IN3 Digital Pin 5
IN4 Digital Pin 4
ENA Digital Pin 9 (PWM pin)
ENB Digital Pin 3 (PWM pin)

Figure 6.6 Dual DC Motor Control Setup

Department of EEE, GUB 36 | P a g e


6.6 Arduino Codes
(a) Code for controlling rotation direction

const int In1 = 7;


const int In2 = 6;
const int In3 = 5;
const int In4 = 4;
const int EnA = 9;
const int EnB = 3;

void setup() {
// put your setup code here, to run once:
pinMode(In1, OUTPUT);
pinMode(In2, OUTPUT);
pinMode(In3, OUTPUT);
pinMode(In4, OUTPUT);
pinMode(EnA, OUTPUT);
pinMode(EnB, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
//Both motor forward
digitalWrite(In1, HIGH);
digitalWrite(In2, LOW);
digitalWrite(In3, HIGH);
digitalWrite(In4, LOW);
digitalWrite(EnA, HIGH);
digitalWrite(EnB, HIGH);
delay(2000);

//Free run stop for both motors


digitalWrite(EnA, LOW);
digitalWrite(EnB, LOW);
delay(2000);

//Both motor reverse


digitalWrite(In1, LOW);
digitalWrite(In2, HIGH);
digitalWrite(In3, LOW);
digitalWrite(In4, HIGH);
digitalWrite(EnA, HIGH);
digitalWrite(EnB, HIGH);
delay (2000);
}

Department of EEE, GUB 37 | P a g e


(b) Code for speed control

const int In1 = 7;


const int In2 = 6;
const int In3 = 5;
const int In4 = 4;
const int EnA = 9;
const int EnB = 3;

void setup() {
// put your setup code here, to run once:
pinMode(In1, OUTPUT);
pinMode(In2, OUTPUT);
pinMode(In3, OUTPUT);
pinMode(In4, OUTPUT);
pinMode(EnA, OUTPUT);
pinMode(EnB, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
//Both motor forward
digitalWrite(In1, HIGH);
digitalWrite(In2, LOW);
digitalWrite(In3, HIGH);
digitalWrite(In4, LOW);
analogWrite(EnA, 150);
analogWrite(EnA, 230);
delay(2000);
}

6.7 Procedure
1. Construct the circuit as per section 6.5.
2. Remove the jumper heads that connect the ENA and ENB to the HIGH state pins.
3. Create a new sketch in Arduino IDE and write the code in the sketch.
4. Select ‘Arduino Uno’ as the board.
5. Verify, compile, and upload the code (a) in the Arduino.
6. Detach the USB connection as the Arduino is being powered up from the L298.
7. Connect a 12V power supply to the power jack of the motor controller.
8. Power up the circuit and observe the rotation direction of both of the motors.
9. Now, upload the code (b) in Arduino.
10. Change the duty cycle and observe the change in speed of the motors.

Department of EEE, GUB 38 | P a g e


6.8 Lab Tasks
1. Modify the given code to change the motor speed by a potentiometer.

6.9 Report Tasks


1. Write Arduino code to turn the motors in directions opposing each other and also
for fast stopping the motors.
2. Two DC motors are being controlled in a way so that they model the second and
minute indicators of a clock. Prepare an Arduino code for this.
3. Suppose, you have an RC car that is controlled by sending commands from
Arduino. You need three bits to send various commands from the Arduino. The
command bit combinations are given below. Now, write down an Arduino code
for this purpose.
i. 000 – Forward
ii. 001 – Reverse
iii. 010 – Hard brake
iv. 011 – Free-run stop
v. 100 – Turn right
vi. 101 – Turn left
vii. 110 – Turn hard right
viii. 111 – Turn hard left

6.10 Report Questions


1. Identify and explain the roles of the following pins on the L298N motor driver:
IN1, IN2, ENA, ENB OUT1, and OUT2. How do these pins work together to
control the motor's direction and speed?
2. Explain the function of the L298N motor driver and describe how it enables
bidirectional control of a DC motor. What is the purpose of the H-Bridge
configuration in this context?
3. How can you modify the Arduino code to change the direction of the DC motor?
Provide a code snippet that demonstrates how to set the motor to rotate in the
forward direction and then reverse direction.

Department of EEE, GUB 39 | P a g e


Experiment 7
Input-based Servo Position Control using Arduino

7.1 Objectives
1. To control servo motor in a multi-component system using Arduino
2. To set up servo configuration for required specifications

7.2 Learning Outcomes


After completion of this experiment, students will be able to

1. Understand the internal construction and operating principle of a closed-loop


servo motor
2. Interface servo motor with Arduino Uno
3. Control servo rotation angles using a potentiometer

7.3 Theory
A servo motor is a type of motion control motor, often used in robotics, automation, and
RC systems. In contrast to DC motors, servo motors do not rotate 360 degrees
continuously. The direction of rotation of a servo motor can be precisely controlled. A
closed loop servo motor can rotate between 0° to 180° whereas the open loop servo motors
can rotate between 0° to 360°.

Figure 7.1 Servo Motors; SG90 (left) and MG995 (right)

The SG-90 servo motor has a torque of 2.5 kg.cm which refers to the capacity of the rotor
to exert a force equivalent to 2.5 kg at a distance of 1cm from its axis. The internal
construction of the motor includes a DC motor, a motor controller, a gear train, and a
potentiometer. This assembly converts the high-speed low-torque output of the DC motor
to low-speed high-torque with precise control.

Department of EEE, GUB 40 | P a g e


Figure 7.2 SG90 Internal Construction

The microcontroller sends out PWM signals to the servo, and then the embedded board
in the servo receives the signals through the signal pin and controls the motor inside to
rotate. As a result, the motor drives the gear system and then motivates the shaft after
deceleration. The shaft and potentiometer of the servo are connected together. When the
shaft rotates, it drives the potentiometer, so the potentiometer outputs a voltage signal to
the embedded board. Then the board determines the direction and speed of rotation based
on the current position, so it can stop exactly at the right position as defined and hold
there.

Figure 7.3 Servo Motor Operation

The angle of rotation can be inputted by an external potentiometer. Depending on the


value read from the potentiometer, the microcontroller sets up the angle.

7.4 Required Equipment


1. Arduino Uno (1 Pcs)
2. SG90 Servo Motor (1 Pcs)
3. 1kΩ potentiometer (1 Pcs)
4. Oscilloscope (1 Pcs)

Department of EEE, GUB 41 | P a g e


5. Breadboard
6. Jumper wires

7.5 Circuit Diagram

Figure 7.4 Circuit Setup for Servo Motor Position Control

7.6 Arduino Codes


(a) Code for servo rotation without external input

#include <Servo.h>
int servoPin = 9; // Declare the Servo pin
Servo Servo1; // Create a servo object
void setup()
{
Servo1.attach(servoPin); // Attach the servo to the used pin number
}
void loop(){
// Make servo go to 0 degrees
Servo1.write(0);
delay(1000);
// Make servo go to 90 degrees
Servo1.write(90);
delay(1000);
// Make servo go to 180 degrees
Servo1.write(180);
delay(1000);
}

Department of EEE, GUB 42 | P a g e


(b) Code for servo rotation with external input

#include<Servo.h>
Servo myservo;
int potpin=A0;
int val;

void setup() {
// put your setup code here, to run once:
myservo.attach(9);
}

void loop() {
// put your main code here, to run repeatedly:
val=analogRead(potpin);
val=map(val,0,1023,0,180);
myservo.write(val);
delay(15);
}

7.7 Procedure
1. Place the potentiometer on the breadboard.
2. Connect the power pins of the potentiometer to the power pins of the Arduino.
Connect the middle pin of the potentiometer to pin A0 of Arduino.
3. Connect the red, brown, and orange wire of the servo motor to the 5V, GND, and
digital pin 9 of the Arduino, respectively.
4. Cross-check the circuit with Figure 7.4.
5. Open Arduino IDE and create e new sketch and write code (a).
6. Verify, compile, and upload the code to Arduino and observe the output.
7. Connect the oscilloscope probe to the digital pin 9 of the Arduino and observe the
waveshape.
8. Now, upload code (b) to the Arduino.
9. Rotate the knob of the potentiometer and observe the effect on the rotation.

7.8 Lab Tasks


1. Write a program to rotate the servo motor between 0° and 180° continuously.
2. Modify code (b) to show the value of analogRead(), and rotation degree in the serial
monitor.

Department of EEE, GUB 43 | P a g e


7.9 Report Tasks
1. A system has three servo motors; Servo1, Servo2, and Servo3 connected to an
Arduino Uno. Among them, Servo1 and Servo2 are controlled by two
potentiometers. Servo3 is not controlled by any potentiometer, however, the angle
of this motor is the average of the rotation angles of Servo1 and Servo2 for any
instance. Write a program for this system. The rotation angles for the three servos
should be displayed on the serial monitor.
2. In an autonomous obstacle avoidance robot, the servo motor and two DC motors
are controlled using the feedback from a sonar sensor in the following manner;
i. If the distance is < 10 cm, the DC motors will slow down and the servo
motor will rotate 180°.
ii. If the distance is > 10 cm, the DC motors will move forward and the servo
motor will stand still.

7.10 Report Questions


1. Write a short note on the speed control technique of the servo motor. Write a code
that allows the provision of manual speed control.
2. Explain the advantage of creating a servo object in code to control the servo.

Department of EEE, GUB 44 | P a g e


Experiment 8
Data Entry System using 4x4 Membrane Keypad

8.1 Objectives
1. To interface 4x4 membrane keypad with Arduino Uno
2. To receive data from the keypad and control other processes

8.2 Learning Outcomes


After completion of this experiment, students will be able to

1. Explain the operational principle of a 4x4 membrane keypad and its interfacing
with Arduino
2. Read and visualize data received from the keypad
3. Control outputs based on the received data

8.3 Theory
A membrane keypad is a matrix arrangement of buttons used as an input device. A 4x4
keypad has 4 rows and 4 columns resulting in 16 distinct buttons. The buttons are
organized in a telephonic manner. The keypad utilizes the multiplexing principle to
reduce the number of I/O pins. Hence, all the buttons in a row are shorted and the same
is true for all the buttons in a column. This results in four terminals for four rows and four
terminals for four columns. When the button is pressed, one of the rows is connected to
one of the columns, allowing current to flow between them. When the key ‘4’ is pressed,
for instance, column 1 and row 2 are connected.

Figure 8.1 A 4x4 Membrane Keypad Circuitry

Department of EEE, GUB 45 | P a g e


8.4 Required Equipment
1. Arduino Uno (1 Pcs)
2. 4x4 Membrane keypad (1 Pcs)
3. LEDs (1 Pcs)
4. 220Ω Resistors (2 Pcs)
5. Breadboard
6. Jumper wires

8.5 Circuit Diagram

Figure 8.2 Circuit Setup for Data Entry System

8.6 Arduino Codes


#include <Keypad.h>

const byte ROWS = 4; //four rows


const byte COLS = 4; //four columns
const int red = 12;
const int green = 13;

char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}

Department of EEE, GUB 46 | P a g e


};

byte rowPins[ROWS] = {9, 8, 7, 6}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {5, 4, 3, 2}; //connect to the column pinouts of the keypad
//Create an object of keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup(){
pinMode(red, OUTPUT);
pinMode(green, OUTPUT);
Serial.begin(9600);
}

void loop(){
char key = keypad.getKey();// Read the key

// Print if key pressed


if (key){
Serial.print("Key Pressed : ");
Serial.println(key);
int num = key -'0';
if(num>=6)
{
digitalWrite(red, HIGH);
digitalWrite(green, LOW);
}
else
{
digitalWrite(green, HIGH);
digitalWrite(red, LOW);
}

}
}

8.7 Procedure
1. Connect the R1, R2, R3, R4, C1, C2, C3, and C4 of the keypad to the digital pins 9,
8, 7, 6, 5, 4, 3, and 2 of Arduino, respectively.
2. Connect a red LED and a green LED via 220Ω resistors to digital pins 12 and 13,
respectively.
3. Open Arduino IDE and go to Sketch > Include Library > Manage Libraries and search
for ‘keypad’.

Department of EEE, GUB 47 | P a g e


4. Install the keypad by Mark Stanley and Alexander Brevig.
5. Write the code in the sketch.
6. Verify, compile, and upload the code to Arduino.
7. Press different buttons and check the outputs.

8.8 Lab Tasks


1. Modify the program so that all the buttons represent alphabets. The program will
return the lowercase letter of the pressed button.

8.9 Report Tasks


1. Make a program to visualize the data in an LCD rather than the serial monitor.
2. Program the Arduino in a way that it can take multiple inputs and show them as
a whole. (i.e. if a user presses the numbers 4, 3, 7, 9, and 0 one after another, it
should display 43790)
3. Design a 4-digit password-protected system. The password will be given through
the keypad. On matching, the system will display “Password Matched”. It should
display “Failed!!!” otherwise.

8.10 Report Questions


1. Write a short note explaining how the microcontroller detects the pressing of a
particular key.
2. Prepare a list of the functions available in the keypad library. Write short
descriptions of each.

Department of EEE, GUB 48 | P a g e


Experiment 9
Proximity Door Access Control System

9.1 Objectives
1. To design a system combining different components that adhere to certain design
specifications
2. To optimize the design for minimum complexity

9.2 Learning Outcomes


After completing this experiment, students will be able to

1. Combine different components (i.e. servo motor, LCD, sonar sensor, etc.) to design
a proximity door access control system
2. Establish appropriate data interchange between different components of the
system

9.3 Theory
A proximity door access control system utilizes an ultrasonic sensor for distance
measurement to detect the presence of an individual near the door. This system, built
using Arduino, enables automatic door opening when a person approaches within a
specified range, enhancing convenience and accessibility.

Figure 9.1 Mechanism of the System

The ultrasonic sensor creates a specified range for the detection area. If anyone is within
this detection area, the system gets triggered by the sensor and activates the servo motors
attached to the door. The motors will rotate at a specified angle to make the door wide
open. An LCD connected to the system will display the door status and the distance. The
system has the following design considerations;

Department of EEE, GUB 49 | P a g e


a. The detection area should be within 50 cm of the door.
b. The servo motors will be rotating in the same directions in proper synchronization.
c. The program must include the provision to control the maximum degree of
rotation of the motors.

9.4 Required Equipment


1. Arduino Uno (1 Pcs)
2. HC-SR04 Sonar Sensor Module (1 Pcs)
3. 16x2 LCD (1 Pcs)
4. SG-90 Micro Servo (2 Pcs)
5. 1kΩ potentiometer (1 Pcs)
6. 220Ω resistor (1 Pcs)
7. Breadboard
8. Jumper wires

9.5 Circuit Diagram


Following are the connections for the mentioned system;

Table 9.1 Connection Diagram of the components

Component Pin Connected To


Vcc Vcc
TRIG Digital Pin 5
Sonar Sensor
ECHO Digital Pin 4
GND GND
Power Vcc
Servo 1 Signal Digital Pin 3
Ground GND
Power Vcc
Servo 2 Signal Digital Pin 2
Ground GND
VDD 5V
VSS GND
Vo Middle pin of the potentiometer
RS Digital pin 7
E Digital pin 8
R/W GND
LCD
D4 Digital pin 9
D5 Digital pin 10
D6 Digital pin 11
D7 Digital pin 12
A 5V via 220Ω resistor
K GND

Department of EEE, GUB 50 | P a g e


Figure 9.2 Circuit Setup for the System

9.6 Arduino Codes


#include <LiquidCrystal.h>
#include <Servo.h>

// LCD pin configuration (RS, E, D4, D5, D6, D7)


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

// Servo objects
Servo door1;
Servo door2;

// Ultrasonic Sensor pins


const int trigPin = 5; // Changed to pin 5
const int echoPin = 4; // Changed to pin 4

// Distance thresholds
const int openThreshold = 50; // Distance (cm) to open doors

// Servo positions

Department of EEE, GUB 51 | P a g e


const int closedPos = 0;
const int openPos = 90;

void setup() {
// LCD setup
lcd.begin(16, 2); // Initialize a 16x2 LCD
lcd.print("System Starting...");

// Ultrasonic sensor setup


pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);

// Servo setup
door1.attach(2); // Connect servo 1 to pin 2
door2.attach(3); // Connect servo 2 to pin 3
door1.write(closedPos);
door2.write(closedPos);

delay(2000);
lcd.clear();
lcd.print("Distance System");
}

void loop() {
int distance = measureDistance();

// Display distance on LCD


lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm ");

// Check the distance to control doors


if (distance <= openThreshold) {
openDoors();
lcd.setCursor(0, 1);
lcd.print("Doors: OPEN ");
} else {
closeDoors();
lcd.setCursor(0, 1);
lcd.print("Doors: CLOSED ");
}

delay(500); // Small delay to avoid flickering


}

Department of EEE, GUB 52 | P a g e


// Function to measure distance using HC-SR04
int measureDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

long duration = pulseIn(echoPin, HIGH);


int distance = duration * 0.034 / 2; // Convert duration to cm
return distance;
}

// Function to open doors


void openDoors() {
door1.write(openPos);
door2.write(openPos);
}

// Function to close doors


void closeDoors() {
door1.write(closedPos);
door2.write(closedPos);
}

9.7 Procedure
1. Construct the circuit as per the connection details provided in section 9.5 and
cross-check the circuit with Figure 9.1.
2. Open Arduino IDE and create a new sketch.
3. Write the given program and verify.
4. Compile the program and upload it to the Arduino.
5. Power up the circuit.
6. Observe the circuit output for different distances.

9.8 Lab Tasks


1. Modify the program so that the servo motors rotate in opposite directions to each
other.

9.9 Report Tasks


1. Design an RFID-based attendance system with the following design criteria;
i. Minimum number of circuit connections (Hint: Explore I2C protocol)

Department of EEE, GUB 53 | P a g e


ii. The attendance system will be time-bounded.

9.10 Report Questions


1. Write short notes on the equipment that you have used in the report task with
appropriate logical reasoning.

Department of EEE, GUB 54 | P a g e


Experiment 10
Implementation of an Arduino-based Calculator

10.1 Objectives
1. To design a system combining different components that adhere to certain design
specifications
2. To optimize the design for minimum complexity

10.2 Learning Outcomes


After completion of this experiment, students will be able to

1. Take single-digit inputs from a keypad and perform mathematical operations on


them
2. Combine different components to make the system interactive

10.3 Theory
A single-digit calculator performs mathematical operations on single digits. That means
both the operands for the operation will be single digits. To implement this system with
Arduino, a keypad arrangement can be used. A user will input the first operand, operator,
second operand, and lastly the ‘enter/equal’ instruction. Each of the steps will be
displayed on an LCD.

In the keypad used in this experiment, ‘A’, ‘B’, ‘C’, ‘D’, ‘*’, and ‘#’ refer to the add, subtract,
multiply, divide, clear, and equal/enter operations, respectively. The significant part of
this program is to convert the ASCII characters to integer numbers and perform the
operations. This system can be designed for multi-digit input by using string or array
operations.

10.4 Required Equipment


1. Arduino Uno (1 Pcs)
2. LCD unit (1 Pcs)
3. 4x4 keypad (1 Pcs)
4. 1 kΩ potentiometer (1 Pcs)
5. 220Ω resistor (1 Pcs)
6. Breadboard
7. Jumper wires

10.5 Circuit Diagram


The connection details are as follows;

Department of EEE, GUB 55 | P a g e


Table 10.1 Connection Details of the Circuit

Component Pin Connected To


LCD VDD 5V
VSS/GND GND
Vo Middle pin of the
potentiometer
RS Digital pin 12
R/W GND
E Digital pin 11
D4 – D7 Digital pin 5 – 2
A 5V
K GND
R1 Digital pin 9
R2 Digital pin 8
R3 Digital pin 7
R4 Digital pin 6
Keypad
C1 Analog pin A3
C2 Analog pin A2
C3 Analog pin A1
C4 Analog pin A0

Figure 10.1 Circuit Setup for the Single-digit Calculator

Department of EEE, GUB 56 | P a g e


10.6 Arduino Codes
#include <LiquidCrystal.h>
#include <Keypad.h>

// Initialize the LCD (RS, E, D4, D5, D6, D7)


LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// Keypad configuration
const byte ROWS = 4; // Four rows
const byte COLS = 4; // Four columns
char keys[ROWS][COLS] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'C', '0', '=', '/'}
};
byte rowPins[ROWS] = {9, 8, 7, 6}; // Connect to the row pinouts of the keypad
byte colPins[COLS] = {A3, A2, A1, A0}; // Connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

// Variables to store input and result


char firstNum = '\0';
char secondNum = '\0';
char operation = '\0';
bool isSecondNum = false;

void setup() {
lcd.begin(16, 2); // Initialize a 16x2 LCD
lcd.setCursor(0, 0);
lcd.print("Calculator Ready");
delay(2000);
lcd.clear();
}

void loop() {
char key = keypad.getKey();

if (key) {
if (key >= '0' && key <= '9') { // If a number is pressed
if (!isSecondNum) {
firstNum = key;
lcd.setCursor(0, 0);
lcd.print("First: ");
lcd.print(firstNum);
} else {

Department of EEE, GUB 57 | P a g e


secondNum = key;
lcd.setCursor(0, 1);
lcd.print("Second: ");
lcd.print(secondNum);
}
} else if (key == '+' || key == '-' || key == '*' || key == '/') {
operation = key;
isSecondNum = true;
lcd.setCursor(0, 1);
lcd.print("Op: ");
lcd.print(operation);
} else if (key == '=') {
if (firstNum != '\0' && secondNum != '\0' && operation != '\0') {
int num1 = firstNum - '0';
int num2 = secondNum - '0';
float result = 0;

switch (operation) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = (float)num1 / num2;
} else {
lcd.clear();
lcd.print("Error: Div by 0");
delay(2000);
resetCalculator();
return;
}
break;
}

lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Result: ");
lcd.print(result);
delay(3000);

Department of EEE, GUB 58 | P a g e


resetCalculator();
}
} else if (key == 'C') { // Clear everything
resetCalculator();
}
}
}

void resetCalculator() {
firstNum = '\0';
secondNum = '\0';
operation = '\0';
isSecondNum = false;
lcd.clear();
lcd.print("Cleared");
delay(1000);
lcd.clear();
}

10.7 Procedure
1. Connect the components as per the connection details given in Table 10.1 and
cross-check the circuit with Figure 10.1.
2. Open Arduino IDE and create a new sketch.
3. Write the given code and verify it.
4. Compile the code and upload it to the Arduino.
5. Press any number on the keypad.
6. Select the mathematical operator.
7. Press another number on the keypad.
8. Press the ‘#’ button that refers to the ‘=’ operation.
9. Observe the output
10. Observe the outputs for summation, subtraction, multiplication, and division.

10.8 Lab Tasks


1. Implement the hardware setup for the system as per the course instructor’s
instructions.

10.9 Report Tasks


1. The current code operates on single digits. Modify the code so that it can accept
multiple digits.

Department of EEE, GUB 59 | P a g e


10.10 Report Questions
1. Based on the study of the system, suggest possible improvements and their
implementations.

Department of EEE, GUB 60 | P a g e

You might also like