0% found this document useful (0 votes)
495 views

LAB MANUAL Biomedical Instrumentation W24

Uploaded by

Tahir Rashid
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)
495 views

LAB MANUAL Biomedical Instrumentation W24

Uploaded by

Tahir Rashid
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/ 212

Biomedical Instrumentation

EES04307

Laboratory Manual

The University Of Lahore


1-Km, Defence Road, Bhupatian Chowk, Off RaiwindRoad,
Lahore
The University of Lahore Department of Technology

Guidelines for Laboratory Procedure

 Before starting a new lab, you must always read the laboratory manual for that

experiment and the instructor will discuss the experiment with you.

 Attachments must be made for laboratory experiment done in the class.

 Make sure that your observation for previous week experiment is evaluated by the

faculty member and your have transferred all the contents to your record before

entering to lab.

 At the beginning of the class, if the faculty or the instructor finds that a student is

not adequately prepared, they will be marked as absent and not be allowed to

perform the experiment.

 Please actively participate in class and don’t hesitate to ask questions.

 Please utilize teaching assistants fully. To encourage you to be prepared and to read

the lab manual before coming to the laboratory, unannounced questions may be

asked at any time during the lab.

 Maintain silence, order and discipline inside the lab. Don’t use cell phones inside

the laboratory.

 Report to the instructor if you find equipment that is out of order or you break

something..
The University of Lahore Department of Technology

Safety Precautions

This is a partial list of basic safety precautions to use when working on a computer:

 Remove your watch and jewelry and secure loose clothing.


 Turn off the power and unplug equipment before performing service.
 Take a note of all the exits in the room, and also take note of the location of fire
extinguishers in the room for the sake of fire safety.
 Try not to type continuously for extremely long periods.
 Look away from the screen once in a while to give your eyes a rest.
 Do not touch any exposed wires or sockets.
 Do not attempt to open any machines, and do not touch the backs of machines when
they are switched on.
 Do not spill water or any other liquid on the machine, in order to maintain electrical
safety.
 Turn off the machine you were using, when you are done using it.
 Do not access external devices without scanning them for computer viruses.
 Ensure that the temperature in the room stays cool, since there are a lot of machines
inside a lab, and these can overheat easily.
 Try not to touch any of the circuit boards and power sockets when something is
connected to them and switched on.
 Always maintain an extra copy of all your important data.
The University of Lahore Department of Technology

Safety Undertaking

I have read all of the above, and I agree to conform to its contents.

Name:

Registration No.:

Student Signature:

Date:

Lab Instructor:
The University of Lahore Department of Technology

Laboratory Work Assessment Rubrics

Laboratory Work Assessment Rubrics

Sr. Performance
No. Indicator Excellent (5) Good (4) Average (3) Fair (2) Poor (1)
1 Theoretical Student knows Student knows most Student knows few Student knows Student has poor
knowledge all the related of the related of the related very little about understanding of the
10% concepts about concepts about the concepts about the the related related concepts
the theoretical theoretical theoretical concepts about the about the theoretical
background of background of the background of the theoretical background of the
the experiment experiment and experiment and background of the experiment and
and rephrase partially rephrase partially rephrase experiment and unable to rephrase
those concepts in those concepts in those concepts in poorly rephrase those concepts in
written and oral written and oral written and oral those concepts in written and oral
assessments assessments assessments written and oral assessments
assessments
2 Application Application runs Application Application Application Application does
Functionality smoothly and compiles with no compiles with compiles and not compile or
10% operation of the warnings. Robust few or no runs without compiles but
application runs operation of the warnings. crashing. Some crashes.
efficiently application, with Consideration attempt at Confusing.
good recovery. given to unusual detecting and Little or no error
conditions with correcting detection or
reasonable errors. correction.
3 Specifications The program The program works The program The program The program is
10% works very and meets some of works and produces correct producing incorrect
efficiently and the specifications. produces the results but does not results.
meets all of the correct results and display them
required displays them correctly.
specifications. correctly. It also
meets most of the
other
specifications.
4 Level of Provide complete Provide complete Provide partially Provide very few Provide no answer to
understanding of and logical and logical answers correct and logical and illogical the questions asked
the learned skill answers based based upon accurate answers based answers to the by examiner.
10% upon accurate technical content to upon minimum questions asked by
technical content the questions asked technical content examiner.
to the questions by examiner with to the questions
asked by few errors asked by examiner
examiner

5 Readability and The code is The code is fairly Most of the code Some parts of the The code is poorly
Reusability exceptionally easy to read. The could be reused in code require organized and very
10% well organized code could be other programs. change before they difficult to read and
and very easy reused as a whole could be reused in not organized for
to follow and or each class could other programs. reusability.
reused be reused.
The University of Lahore Department of Technology
6 Embedded Well-designed Good designed Some attempt to Little attempt to Very poor attempt to
System Design circuits. Code is circuits and Little make circuits. design circuits and design circuits and its
10% highly code duplications Code can be less understanding code
maintainable maintained with of code
significant effort

7 Responsiveness 1. Responds 1. Generally 1. Generally 1. Not much . 1. Non Responsive


to well, quick and Responsive and Responsive and Responsive and and inaccurate all the
Questions/ very accurate all accurate most of the accurate few times. accurate most of times.
Accuracy the time. times. 2. Some eye the times. 2. No eye contact and
10% 2. Effectively 2. Maintains eye contact, speaks 2. Uses eye contact unable to speak
uses eye contact, contact, speaks clearly and ineffectively and 3. Dresses
speaks clearly, clearly with suitable unclearly in fails to speak inappropriately
effectively and volume and pace. different portions. clearly and audibly
confidently using
suitable volume
8 Efficiency The code is The code is fairly Some part of the The code is brute The code is huge and
extremely efficient without code is efficient force and appears to be patched
10% efficient without sacrificing and other part of unnecessarily long together
sacrificing readability and the code is not
readability and understanding understandable and
understanding work properly

9 Delivery The program was The program was The program was The code was The code was
delivered in time delivered in Lab delivered within delivered within a delivered more than 2
10% during lab. before the end time. the due date. day after the due days overdue.
date.

10 Awareness of Student has Student has Student has little Student has little Student has no
Safety sufficient sufficient knowledge of the knowledge of the knowledge of the
Guidelines knowledge of knowledge of the laboratory safety laboratory safety laboratory safety
10% the laboratory laboratory safety SOPs and protocol SOPs and protocol SOPs and protocol
safety SOPs and SOPs and protocol and is Partially and is non- and is non-compliant
protocol and is and is Partially compliant to the compliant to the to the guidelines
fully compliant compliant to the guidelines guidelines
to the guidelines guidelines
The University of Lahore Department of Technology

Lab’s Course Learning Outcomes


Course Title : Biomedical Instrumentation
Course Code : EES04307
Instructor : Mian Usman Zahid
Designation : Lecturer
E-mail : [email protected]

Students will be able to:

CLO4: Imitate Electronics circuit with microcontroller interface. (P3, PLO5)

Mapping of Course Learning Outcomes (CLO) to Program Learning Outcomes (PLO) /Graduate Attributes

Course CLOs/ PLO PLO PLO


PLO1 PLO2 PLO3 PLO4 PLO5 PLO6 PLO7 PLO8 PLO9
Code PLOs 10 11 12
X
EES04307 CLO 4

PLO1: Engineering Knowledge PLO8: Ethics


PLO2: Problem Analysis PLO9: Individual and Team Work
PLO3: Design/Development of Solutions PLO10: Communication
PLO4: Investigation PLO11: Project Management
PLO5: Modern Tool Usage PLO12: Lifelong Learning
PLO6: The Engineer and Society
PLO7: Environment and Sustainability
The University of Lahore Department of Technology

List of Experiments

Experiment Title
No.
1 Introduction to Arduino Uno and its programming
2 Interfacing of push button with an LED using Microcontroller
3 Use of Serial Monitor and Serial plotter in Arduino Uno Microcontroller
4 Seven Segment display interfacing with Microcontroller
5 Interfacing LCD with microcontroller
6 Keypad interfacing with Microcontroller
7 Pulse Width Modulation and its interfacing
8 Controlling a stepper and servo motor using Microcontroller
9 Temperature Sensor interfacing with microcontroller
10 Ultrasonic Sensor interfacing with microcontroller
11 IR sensor and PIR sensor interfacing with microcontroller
12 “Line Follower Robot” Open Ended LAB (OEL)
13 To Control DC motor using Bluetooth interfacing with microcontroller
14 Relay interfacing with microcontroller
Semester Project
The University of Lahore Department of Technology

EVALUATION LOG

Obtained Marks Checked date Checked by


LAB No.
CLO 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14

Project
Experiment No. 1
Introduction to Arduino Uno and its programming

Introduction
This lab describes the Arduino basic theory and software description that are commonly
used in embedded system. In this lab, we have to learn the basic steps in the software
which is used for programming in Arduino.
Objectives
 Understand the basic theory of microcontroller (Arduino)
 Understand the basic hardware description of Arduino
 Understand the software which is used for programming in Arduino

Outcomes
By the end of this experiment, student will have basic understanding the Arduino
features and its programming.

Theory Overview

Arduino is open-source electronics prototyping platform based on flexible, easy-to-use


hardware and software. It's intended for artists, designers, hobbyists and anyone interested
in creating interactive objects or environments. The Arduino is an open source
microcontroller platform that you use for sensing both digital and analog input signals
and for sending digital and analog output signals to control devices. That definition is
quite a mouthful. Before we delve into programming the Arduino, let’s take some time to
look at what it’s all about

 Arduino Hardware
The Arduino board is where your code is executed. The board can only control and
respond to electricity, so specific components are attached to it to enable it to
interact with the real world. These components can be sensors, which can be
convert some aspect of the physical world to electricity so that the board can sense
it or actuators, which get electricity from the board convert it in to something that
changes the world.
Figure 4.1 Arduino Board Description

Figure 4.2 Arduino Board Description

Examining the Arduino Uno


At the time of this writing, the Arduino Uno R3 is the current main board in the Arduino family.
It’s the most commonly used unit for interacting with projects that require a simple
microcontroller. The Uno R3 unit provides the following:
 14 digital I/O interfaces
 6 analog input interfaces
 6 PWM interfaces
 1 I2C controller interface
 1 SPI controller interface
 1 UART serial interface, connected to a USB interface

We need to be familiar with the Arduino pins, so these pins are discussed as follows
Each of the 14 digital pins on the Uno can be used as an input or output using pinMode(),
digitalWrite(), and digitalRead() functions. They operate at 5 volts. Each pin can
provide or receive a maximum of 40 mA and has an internal pull-up resistor (disconnected
by default) of 20-50 K ohms. In addition, some pins have specialized functions:

 Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data.
These pins are connected to the corresponding pins of the ATmega8U2 USB-to- TTL
Serial chip.
 External Interrupts: 2 and 3. These pins can be configured to trigger an interrupt on a
low value, a rising or falling edge, or a change in value.
 PWM: 3, 5, 6, 9, 10, and 11. Provide 8-bit PWM output with the analogWrite ()
function.
 SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI
communication using the SPI library.
 LED: 13. There is a built-in LED connected to digital pin 13. When the pin is HIGH
value, the LED is on, when the pin is LOW, it's off.
The Uno has 6 analog inputs, labeled A0 through A5, each of which provide 10 bits of
resolution (i.e. 1024 different values). By default they measure from ground to 5 volts,
though is it possible to change the upper end of their range using the AREF pin and the
analogReference() function. Additionally, some pins have specialized functionality:
 AREF. Reference voltage for the analog inputs. Used with analogReference().
 Reset. Bring this line LOW to reset the microcontroller. Typically used
to add a reset button to shields which block the one on the board.

Examining the Arduino Architecture


The developers with the Arduino project have built a completely self-contained microcontroller
system on a single circuit board that you can plug into just about any embedded system. The core
of the Arduino project is the microcontroller chip that it uses. To be able to program the Arduino,
you’ll want to know a little about what’s going on “under the hood.”
The ATmega AVR Microcontroller Family
The Arduino developers selected the Atmel ATmega AVR family of microcontroller chips to
power the Arduino. The ATmega AVR microcontroller is an 8-bit computer that contains several
features built in: Flash memory for storing program code statements Static random-access memory
(SRAM) for storing program data Erasable electronic programmable read-only memory
(EEPROM) for storing long-term data Digital input and output ports Analog-to-digital converter
(ADC) for converting analog input signals to digital format The ATmega AVR chip is a complete
microcontroller system built in to a single chip. That allows the Arduino developers to create a
small circuit board with minimal external components. The Arduino series uses several different
ATmega processors. Table 1.1 shows the different ATmega processors you’ll find in Arduino
units.
Processor Flash SRAM EEPROM
ATmega48 4KB 512B 256B
ATmega88 8KB 1KB 512B
ATmega168 16KB 1KB 512B
ATmega328 32KB 2KB 1KB
ATmega32u4 32KB 2.5KB 1KB
Table 1.1 ATmega Processor Family

 Arduino Software
Software programs called sketches are created on a computer using Arduino integrated
development environment IDE. The IDE enables to edit or write a code and convert this
code in to instructions that Arduino hardware understands. The open-source Arduino
environment makes it easy to write code and upload it to the i/o board. This link you can
download the software needed from: http://Arduino.cc/en/Main/Software The software
doesn’t need to be setup jest run the program normally.

The following procedure shows how to use Arduino software.

Step 1- First start Arduino program then the following figure should appear as
shown in figure 4.2
\
\\\\\

Figure 4.2 default window for programming

Step 2- Click tools and check the board Arduino Uno is chosen (“This option
can be changed according to the Arduino’s type needed to be programmed”)
shown in figure 4.3

Figure 4.3 Selection of Board


Step 3- Start writing or choosing the program needed to be transferred to the
Arduino. Choose the program from the examples built in the software as shown in
figure 4.4

Figure 4.4 choose the examples

Step 4- Choose a simple example like blink as shown in figure 4.5


Figure 4.5 choose the example Blink

Step 5- New window will open as follows click upload button then the software will
compile the program for errors and then upload it to the Arduino as shown in figure 4.6

Upload button

Figure 4.6 After completion click the upload button


Lab Task:
Make a project for blinking an LED which is attached on pin 13 Arduino with some delay.

Equipment / Apparatus
 Arduino Kit
 DC Power Supply 5 Volt
 Digital Multimeter
 Breadboard
 Resistors 10 Ω to 1kΩ
 LED’s
 Wires
Schematic Diagram

Figure 4.7 circuit diagram


Arduino C Program

int LED=13;
void setup ( )
{
pinMode(LED, OUTPUT);
}

void loop ( )
{
digitalWrite (LED, HIGH);
delay(500);
digitalWrite (LED, LOW);
delay(500);
}

Observation, Results and Discussion

After program the code inside Arduino check the status of LED on your
breadboard and fill the table 1.2

Table 1.2 LED blinking observation chart


Arduino digital input pin no:

Arduino voltage supply:

Resistor Value:

Time Delay :

LED blinking Yes


/ NO :

Precautions
Before you start to mess with a computer there are basic guidelines to be aware of,
such as turn the power off and watch out for static electricity. The three kind of
activity that requires touching the Arduino

 Setting up wire, component layout or breadboard.


 Debugging a running setup.
 Moving, mounting up the board somewhere.
Review Questions
Question 1
Write a C code in Arduino for blinking an LED on pin number 8 in Arduino with
some specified delay. Also sketch the circuit diagram and paste the hardware result
also

Question 2
Write a C code in Arduino for blinking an LED on pin number 8 ,7 in Arduino with
some specified delay. Also sketch the circuit diagram and paste the hardware result
also.

Question 3
Write a c code in Arduino to perform a simple sequential program to turn ON and
Turn OFF 6 LEDS sequentially. Also sketch the circuit diagram and paste the
hardware result also.

LAB Assessment

Student Name LAB Rubrics CLO3 , P5, PLO3


Total Marks 10
Registration No Obtained Marks

Teacher Name Syed M Hamedoon

Date Signature
Experiment No. 02

Interfacing of push button with an LED using Microcontroller

Introduction
The main aim of this lab is to use push button to turn ON and OFF the LEDs
correspondingly by using microcontroller (Arduino)

Objectives
 How to read the status of digital pin of microcontroller
 How to connect the push button as an input to microcontroller

Outcomes
By the end of this experiment, student will know the basic understanding of how to
read the status of microcontroller and will also understand the working principle of
switch interfacing with microcontroller.

Theory Overview
The pushbutton is a component that connects two points in a circuit when you press it.
The example turns on an LED when you press the button as shown in figure 2.1

When the pushbutton is open (Un pressed) there is no connection between the two legs
of the pushbutton, so the pin is connected to 5 volts (through the pull-up resistor) and
we read a HIGH. When the button is closed (pressed), it makes a connection between
its two legs, connecting the pin to ground, so that we read a LOW. (The pin is still
connected to 5 volts, but the resistor in-between them means that the pin is "closer" to
ground.)

Apparatus
 Adjustable DC Power Supply
 Push Button
 LEDs
 Resistors (220 Ω)
 Digital Multimeter
 Breadboard
 Wires
Circuit Diagram

Figure 2.1 Circuit diagram 2 of Arduino interfacing with push button

Figure 2.2 schematic diagram


Procedure
We connect three wires to the Arduino board. The first goes from one leg of the
pushbutton through a pull-up resistor (here 2.2K Ohms) to the 5 volt supply. The second
goes from the corresponding leg of the pushbutton to ground. The third connects to a
digital i/o pin (here pin 4) which reads the button's state as shown in Figure 2.2.

In this example, a push button switches and an LED is connected to Arduino Uno.
When we press the switch, LED will glow for 3 seconds. A pin is configured as Input
Pin to connect switch and another pin is configured as Output Pin to connect LED. You
need to connect PULL-UP resistors while interfacing switch as shown in figure 2.3.

Figure 2.3 Pull up resistors interfacing with push button

After built the hardware, code will be written accordingly in Arduino UNO software.
In this lab there is two programs are written, you can write or understand any one of
the program. When the code run successfully upload the program in microcontroller,
which will be ready for testing the project.
LAB Exercise

Program 2.1

Write a program in Arduino to interface push button with LED. When the button is
pressed LED should be turn ON otherwise LED will turn OFF. LED is connected to Pin
13 and push button is connected to pin 2 of Arduino.

Solution:

int led = 13;


void setup()
{
//initialize the digital pins.
pinMode(led, OUTPUT);
pinMode(2, INPUT);
}

// the loop routine runs over and over again forever:

void loop()

{
if(digitalRead(2)==HIGH)
{
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)

}
else
{
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW

}
Program 2.2
Write a program in microcontroller to interface push button with LED. When the button
is pressed LED will turn ON otherwise LED will turn OFF. LED is connected to Pin 13
and push button is connected to Pin 7 of microcontroller

int ledPin = 13; // choose the pin for the LED

int inPin = 7; // choose the input pin (for a pushbutton)

int val = 0; // variable for reading the pin status

void setup() {

pinMode(ledPin, OUTPUT); // declare LED as output

pinMode(inPin, INPUT); // declare pushbutton as input

void loop(){

val = digitalRead(inPin); // read input value

if (val == HIGH) { // check if the input is HIGH (button released)

digitalWrite(ledPin, LOW); // turn LED OFF

} else {

digitalWrite(ledPin, HIGH); // turn LED ON

}
Observation and Results

After compile the code and burn successfully in Arduino, test the hardware and fill the table
2.1 and table 2.2 accordingly.

Table 2.1 Table of observation

Supply Voltage Volts

Microcontroller

Resistor R1 Ω

Resistor R2 Ω

Table 2.2 Status of LEDs with respect to push button

Push Button Status ( Pressed ) Push Button Status ( Not


Pressed )
Status of LED
(ON / OFF)

Precautions
Before you start to mess with a computer there are basic guidelines to be aware of,
such as turn the power off and watch out for static electricity. The three kind of
activity that requires touching the Arduino

 Setting up wire, component layout or breadboard.


 Debugging a running setup.
 Moving, mounting up the board somewhere.
Review Questions

Question 1
Write a program in Arduino when the button is pressed it turn OFF the LED otherwise
LED is turn ON. Also monitor the status of LED serially on output screen

Question 2
Sketch a circuit diagram and paste the running picture of Question 1

Question 3
Write a program in Arduino in which switch is connected to pin number 2 red led1 is
connected to pin 4, red led2 is connected to pin 5, green led is connected to pin 3 of
Arduino board. When Switch is pressed both red led should be ON and green led should
turn OFF and when switch is not pressed opposite operation should operate

Question 4
Sketch a circuit diagram and paste the running picture of Question 3

LAB Assessment

Student Name LAB Rubrics CLO3 , P5, PLO3


Total Marks 10
Registration No Obtained Marks

Teacher Name Syed M Hamedoon

Date Signature
Experiment No. 03

Use of Serial Monitor and Serial plotter in Arduino Uno


Microcontroller

Introduction
The Serial Monitor is a tool that we can view data sent via the serial port from the Arduino to the
computer. The Serial Plotter tool is a versatile tool for tracking different data that is sent from your
Arduino board. It functions similarly to your standard Serial Monitor tool which is used to print
data "terminal style", but is a greater visual tool that will help you understand and compare your
data better. The Serial Plotter is a really useful tool for tracking your variables. It can be used for
testing and calibrating sensors, comparing values and other similar scenarios.

Lab Objectives

 To learn how to use the Serial Plotter.


 To learn how to use the Serial Monitor.
 To create a simple sketch and test it out.

Outcomes

By the end of this experiment, student will know the basic understanding of how to use
serial monitor and serial monitor functions in Arduino Uno.

Applications

 Offline Data Visualization

 Code Troubleshooting

 Waveform Analysis
Serial Monitor
The Serial Monitor is a tool that we can view data sent via the serial port from the Arduino to the
computer. The serial monitor is used to retrieve data from Arduino, view data for debugging, and
send data (command) from PC to Arduino. The PC and Arduino must be connected to each other
with a USB cable for the serial monitor to function.

Figure 3.1 serial monitor of Arduino Uno


Items on the serial monitor

1. Output console: Displays the data received from the Arduino.


2. Autoscroll checkbox: The option to choose between auto-scrolling and not scrolling.
3. Show timestamp: Option to view the time stamp before displaying the data on the serial
monitor
4. Clear output: Clears all text in the output console.
5. Baud rate selection: The speed of the serial communication between Arduino and PC is
selected.
6. Textbox: The user can enter the characters they want to send to the Arduino.
7. End selection: The ending character added to the data sent to the Arduino is selected.
8. Send button: When this button is clicked, the serial monitor sends the data in the text box and
the ending character to the Arduino (Arduino-Serial Monitor, n.d.).
Serial Plotter
The Serial Plotter is a tool that can plot graphs of the data sent over the serial port of Arduino. The
Serial Plotter can read temperature, pressure, humidity or any sensor data connected to Arduino
analog input and visualize them as waveforms. It can plot graphs of the data it receives from more
than one sensor at the same time.
Data communication between the serial plotter and Arduino is done with a USB cable. Therefore,
Arduino and PC must be connected to each other with this cable. The baud rate of the Serial Plotter
must be selected to be the same as the Arduino code.
x axis: Represents time. The axis has 500 sample points. The time between each point is usually
equal to the time it takes to execute the code in the void loop() function section.
y-a xis: Represents the values obtained from the sensor output. The y-axis automatically adjusts
itself according to the increase or decrease of the value read from the sensor (Arduino-Serial
Plotter, n.d.).

Figure 3.2 serial plotter of Arduino Uno


Line charts
A line chart is used to show the changes in the current data that occur over a certain time period.
It is possible to present these emerging data changes in an easier and more understandable form
visually with the help of line graphs.

 Drawing a single line graph

Printing a single chart can be done by sending the data and ending it with the character "\r\n".
When writing code for it, the Serial.println (variable) function must be used. Serial.println() adds
the characters "\r\n" automatically after the data (Arduino-Serial Plotter, n.d.).

Figure 3.3 code example


Figure 3.4: Drawing a single line graph of the values received from the analog pin A0 in the
serial plotter.
 Drawing multiple lines on the graph

When we want to plot multiple variables, we must separate the variables with the character "\t" or
" ". The last value must be terminated with the character "\r\n" (Arduino-Serial Plotter, n.d.).

Code
Figure 3.5: Plotting a multi-line graph of the values read from analog input pins A0, A1, A2, A3
and A4 on the serial plotter.

Using Analog Ports


Arduino Uno has six analog inputs from A0 to A5. Since each of these analog inputs has a
resolution of 10 bits, it converts the input voltage into numbers from 0 to 1023. When the grounds
of the circuit to be measured with the Arduino are connected to each other, the analog input pin
allows electrical measurement with a resolution of 5/1024 ≈ 5mV. (Cobanoglu, 2017, p. 216).
Voltage values greater than 5V can also be measured using voltage divider resistors.

Using Digital Ports


Each of the 14 digital pins on the Arduino Uno can be used as both an input and an output. Each
works with 5V and draws 40mA current. Digital ports can be used for various operations, such as
control and measurement. For example, interesting measurements in mechanics (one-dimensional
position and time etc) can be made using ultrasonic sensors.
Digital pins can be used to represent data in binary form or for complex measurements using
existing sensor modules (Organtini, 2018, p. 6 ).
LAB Exercise
Lab Exercise 1
Analog Input, but with Serial Plotter. Demonstrates analog input by reading an analog
sensor on analog pin 0 and turning on and off a light emitting diode(LED) connected to digital
pin 13. The amount of time the LED will be on and off depends on the value obtained by
analogRead().

Circuit Diagram

Figure 3.6: Circuit diagram of Lab Exercise 1

Required hardware
 Arduino Uno
 Potentiometer
 Resistor 220 ohm
 LED
 Jumping wires
 Bread board
Working
Potentiometer attached to analog input 0. The center pin of the potentiometer to the analog
pin. one side pin (either one) to ground and the other side pin to +5V.. LED anode (long leg)
attached to digital output 13. LED cathode (short leg) attached to ground. When you
call Serial.println(value), the Serial Plotter will put that variable on the plot. The Y-Axis of
the plot auto-resizes.
If you want to plot multiple variables, you'll need a Serial.println(value) call for each of the
variables, separated by a Serial.print(" ") or Serial.print("\t"):
Serial.print(variable1);
Serial.print(" ");
Serial.println(variable2);
Let's try it out with the new code above. Compile and upload the program above, then
navigate to Tools > Serial Plotter. The code uses a baud rate of 9600, make sure it's set in
the serial monitor as 9600 too.
You should see something like this when you twist the trim potentiometer around:

Code
int sensorPin = A0;
// select the input pin for the potentiometer
int ledPin = 13;
// select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor
void setup()
{
// declare the ledPin as an OUTPUT:
pinMode(sensorPin, INPUT);
pinMode(ledPin, OUTPUT); // begin the serial monitor @ 9600 baud Serial.begin(9600);
}
void loop()
{
// read the value from the sensor:
sensorValue = analogRead(sensorPin);
digitalWrite(13,HIGH);

Serial.println(sensorValue);
Serial.print(" ");
delay(sensorValue);
digitalWrite(13,LOW);
Serial.println(sensorValue);
Serial.print(" ");
delay(sensorValue);
}

Output
Lab Exercise 2
Sketch (With Potentiometer)
 int potentiometer 

- variable to store value from a potentiometer, connected to an analog pin (gives a value
between 0-1023).

 int static_variable = 500 

- variable that has an unchanged value of 500.

int potentiometer;
int static_variable = 500;

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

void loop() {
potentiometer = analogRead(A1);

Serial.print("Variable_1:");
Serial.print(potentiometer);
Serial.print(",");
Serial.print("Variable_2:");
Serial.println(static_variable);
}
Output

Lab Exercise 3
Sketch (Without Potentiometer)
 int random_variable 

- variable that stores a randomized value between 0-1000.

 int static_variable = 500 

- variable that has an unchanged value of 500.

Code
int random_variable;
int static_variable = 500;

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

void loop() {
random_variable = random(0, 1000);

Serial.print("Variable_1:");
Serial.print(random_variable);
Serial.print(",");
Serial.print("Variable_2:");
Serial.println(static_variable);
}
Lab Exercise 4
To show the working of RC circuit by using microcontroller

The RC circuit is a classic circuit in physics teaching and is composed by just a resistor R and a
capacitor C in series. It is easy to show that the voltage across the capacitor VC is a function of the
time t: when the capacitor is not charged and is connected to a voltage V0 through the resistor, one
gets
VC(t)=V0(1−e−t θ )
Here θ is a parameter having the dimensions of a time called the time constant of the circuit and
is given by the product RC. When the capacitor is at its full charge and the two leads of the circuit
are short circuited, the voltage across the capacitor drops with time with an exponential law whose
time constant is still given by RC.

Circuit Diagram

Figure 3.7: Circuit diagram of Lab Exercise 4

Required hardware
 Arduino Uno
 Capacitor 47uF
 Resistor 10kohm
 Jumping wires
 Bread board

Circuit description
The circuit, shown in the picture below , is easily realised connecting one of the leads of the resistor
to the 5V pin of Arduino; the resistor is mounted in series with the capacitor that, in turn, has its
second lead to the ground (GND). In order to measure the voltage across the capacitor, we connect
the first lead of the capacitor to one of the Arduino analog inputs (A5). initially, the red wire is not
connected to the 5V pin and the capacitor is not charged. Using the new Arduino IDE one can plot
the values written to the Serial monitor as a function of time (in fact as a function of the reading).
Consider the following code:

Code
float lastReading;
unsigned long time;
void setup() {
Serial.begin(9600);
lastReading = analogRead(A5)*5/1024.;
}
void loop() {
while (fabs(analogRead(A5)*5/1024. - lastReading) < 0.1) {
// do nothing
}
for (int i = 0; i < 480; i++) {
float currentReading = analogRead(A5)*5/1024.;
Serial.println(currentReading);
}
while (1) {
// do nothing
}
}

The first loop just waits until the current reading of the A5 pin (analogRead(A5)) differs from the
value of lastReading for more than one tenth of a volt. The fabs function returns the absolute value
of its argument. The reading of the analog input can be an integer number between 0 and 1024
representing a voltage ranging from 0 to 5 V. Multiplying the reading by 5 and dividing it by 1024
we then get the value of the voltage across the capacitor in Volts. Note the dot after 1024 that is
needed to make the value a floating point number. If the dot is missing, both 5 and 1024 are
represented as integers in the Arduino memory, as well as the value returned by analogRead(A5).
This can lead to important consequences. Suppose, for example, that the analogRead(A5) function
returns 123. Once multiplied by 5, we get 615 that, divided by 1024 gives just zero! In fact,
615/1024 is a ratio between two integers and the result is interpreted as an integer, too. Writing
615/1024. (with the dot after 1024) forces the CPU to represent the number 1024 as a floating
point number and any operation made using an integer (615) and a floating point number (1024.)
is a floating point number (about 0.6).

The value of lastReading must be set in the setup() of the Arduino sketch, in which we also
initialise the Serial monitor with

Serial.begin(9600);
The first loop, then, is needed to start the program as well as the Serial plotter, having the time to
connect the red wire to the 5V pin. Only when such a wire is connected to that pin the capacitor
starts charging and the voltage across its leads starts raising. At this point we just read a fixed
number of values of such a voltage (480 in our case) and write them on the Serial monitor. Each
value written to the Serial monitor is shown on the Serial plotter versus time (in fact each value
written to the Serial monitor is plotted against a sequential number, but in our case the readings
are made at almost constant intervals of time, hence the horizontal axis values are proportional to
time).
Once we read all the values we just stop doing anything with the last loop. The result is shown
below.

At the beginning of the loop we still wait for a change in the voltage, but in this case we collect
the current time in the time variable. The current time is given by the micros() function returning
the number of microseconds elapsed since the start of the sketch. As soon as the voltage changes
we start measuring the voltages across the capacitor, but in this case we also get the time of each
measurement and send to the Serial monitor both the time elapsed since the start of the
measurements and the measurement values.

We write those two numbers to the Serial monitor, then copy and paste them into a text file for
subsequent analysis. The picture below shows the data collected by us, during the charge:

Times are in microseconds and you can see how rapid is the process. The capacitor is almost at its
full charge already after 2 seconds. We used a resistor whose resistance was R=9.94 kΩ. We can
then get the value of the capacitor from these measurements. With some mathematics one obtains
a time constant θ of 0.53 s, from which we can derive C as θ/R≈54 μF. The nominal value of the
capacitor we used is 47 μF. The error in the determination of it is then less than 15%.
Review Questions

Question 1

 Solve the LAB Exercise 1


 Attached the code with circuit diagram and graphs

Question 2

 Solve the LAB Exercise 2


 Attached the code with circuit diagram and graphs

Question 3

 Solve the LAB Exercise 3


 Attached the code with circuit diagram and graphs

Question 4

 Solve the LAB Exercise 4


 Attached the code with circuit diagram and graphs

LAB Assessment

Student Name LAB Rubrics CLO3 , P5, PLO3


Total Marks 10
Registration No Obtained Marks

Teacher Name Syed M Hamedoon

Date Signature
Experiment No. 04

Seven Segment display interfacing with Microcontroller.

Introduction
The main aim of this lab is to interface seven segment display with microcontroller (Arduino)
and observe their functionalities. The display counts from 0 -9 and resets itself to zero.

Objectives
 Understand the functionality of Seven Segment Display
 Understand the code of Arduino and its working.
Outcomes
By the end of this experiment, student will have basic understanding of how to interface the
seven segment display with microcontroller and will also understand the working principle of
seven segment display.

Theory Overview
Seven segment displays are the output display devices that provide a way to display information
in the form of image or text. For displaying the images or text in a proper manner, some types
of displays can show only alphanumeric characters and digits. A seven segment display got its
name from the very fact that it got seven illuminating segments. Each of these segments has a
LED (Light Emitting Diode), hence the lighting. The LEDs are so fabricated that lighting of
each LED is contained to its own segment as shown in figure 4.1

Figure 4.1: Seven Segment Display


Figure 4.2: Pin diagram of Seven Segment Display

Types of 7-Segment Displays


There are two types of seven segment displays available in the market. According to the type of
application, these displays can be used as shown in figure 4.3. The two configurations of seven
segment displays are discussed below.
 Common Anode Display
 Common Cathode Display

Figure 4.1 internal connection of seven segment display

Figure 4.3: Types of Seven Segment Display


1) Common Anode Seven Segment Display
In common anode type, all the anodes of 8 LED’s are connected to the common terminal and
cathodes are left free as shown in figure 4.4. Thus, in order to glow the LED, these cathodes have
to be connected to the logic ‘0’ and anode to the logic ‘1’.

Figure 4.4: Common Anode Seven Segment Display

Below truth table gives the information required for driving the common anode seven segments.

Table 4.1: Truth Table of common anode seven segment display


In order to display zero on this segment one should enable logic high on a, b, c, d, e and f
segments and logic low on segment ‘g’. Thus, the above table provides data on seven segments
for displaying numerals from 0-9.

2. Common Cathode Seven Segment Display


As the name indicates cathode is the common pin for this type of seven segments and remaining
8 pins are left free as shown in figure 4.5. Here, logic low is applied to the common pin and logic
high to the remaining pins.

Figure 4.5: Common Cathode Seven Segment Display


Truth Table: The truth table of seven segment display is shown below.
Table 4.2: Truth Table of common cathode seven segment display

Above truth table shows the data to be applied to the seven segments to display the digits. In
order to display digit‘0’ on seven segment , segments a , b , c , d , e and f are applied with logic
high and segment g is applied with logic low.

To test the 7-segment use your Digital multi-meter and set it in the ohmmeter, connect
the red probe to pin 3 or 8 (com pins) of the 7-segment and run the black probe on pins
1,2,4,5,6,7,9,10 (a,b,c,d,e,f,g,dp).When the meter is set to ohmmeter it acts as a voltage
source as the positive terminal is the positive of the source and the negative terminal is
the negative of the source.
LAB Exercise 1
Make a project to display a number 0 to 9 on seven segment display by using Arduino
microcontroller also create a circuit diagram and develop a code.

Required Hardware
 Arduino board
 Adjustable DC Power Supply
 HDSP5503 seven segment display (common cathode)
 Resistors 220Ω
 Digital Multimeter
 Breadboard
 Probes
 Wires 

Circuit Diagram

Figure 4.6 Circuit diagram of Seven Segment Display with Arduino


Procedure
Each segment of display can be checked by using multimeter in diode mode. Each
segment should not be power with a voltage greater than 4v, if did the display will be
damaged permanently. For avoiding this a common resistor can be provider at common
terminal, as shown in circuit diagram. Now, if we want to display a “0” in this display
as shown in figure 4.7.1

Figure 4.7.1 display of ‘0’ on seven segment display

We need to turn the LEDs of segments “A, B, C, D, E F”, so we need to power PIN0,
PIN1, PIN2, PIN3, PIN4 and PIN5. So every time we need a “0”, we need to power all
the pins mentioned. Now, if we want “1” on display as shown in figure 4.7.2

Figure 4.7.2 Display of ‘1’ on seven segment display


We need to power segments “B, C”, for segment B, C to turn ON we need to power
PIN1, PIN2. With both the pins high we get “1” on display. So as seen above we are
going to power pins corresponding to the digit that to be shown on display.
There are sequence of steps to make this project are listed below
Step1: Prepare the circuit diagram according to figure 4.6
Step 2: Make a program to interface seven segment display with Arduino
Step 3: Connect the Arduino board to the computer using USB cable. Launch
Arduino IDE and ensure correct USB port number and board name for establishing
the connection.
Step 4: Once the program is uploaded and running on Arduino, open serial monitor
Step 5: You can verify the output of seven segment digits shows 0 to 9 and repeated
the sequence again and again.

Figure 4.8: connection diagram

Arduino Pin Seven Segment Pin


2 a7
3 b6
4 c4
5 d2
6 e1
7 f9
8 g 10
Code

#define segA 2//connecting segment A to PIN2


#define segB 3// connecting segment B to PIN3
#define segC 4// connecting segment C to PIN4
#define segD 5// connecting segment D to PIN5
#define segE 6// connecting segment E to PIN6
#define segF 7// connecting segment F to PIN7
#define segG 8// connecting segment G to PIN8

int COUNT=0;//count integer for 0-9 increment


void setup()
{

for (int i=2;i<9;i++)

pinMode(i, OUTPUT);// taking all pins from 2-8 as output

void loop()

switch (COUNT)

case 0://when count value is zero show”0” on display


digitalWrite(segA, HIGH);
digitalWrite(segB, HIGH);
digitalWrite(segC, HIGH);
digitalWrite(segD, HIGH);
digitalWrite(segE, HIGH);
digitalWrite(segF, HIGH);
digitalWrite(segG, LOW);
break;

case 1:// when count value is 1 show”1” on display


digitalWrite(segA, LOW);
digitalWrite(segB, HIGH);
digitalWrite(segC, HIGH);
digitalWrite(segD, LOW);
digitalWrite(segE, LOW);
digitalWrite(segF, LOW);
digitalWrite(segG, LOW);
break;

case 2:// when count value is 2 show”2” on disp

digitalWrite(segA, HIGH);
digitalWrite(segB, HIGH);
digitalWrite(segC, LOW);
digitalWrite(segD, HIGH);
digitalWrite(segE, HIGH);
digitalWrite(segF, LOW);
digitalWrite(segG, HIGH);
break;

case 3:// when count value is 3 show”3” on disp


digitalWrite(segA, HIGH);
digitalWrite(segB, HIGH);
digitalWrite(segC, HIGH);
digitalWrite(segD, HIGH);
digitalWrite(segE, LOW);
digitalWrite(segF, LOW);
digitalWrite(segG, HIGH);
break;

case 4:// when count value is 4 show”4” on disp


digitalWrite(segA, LOW);
digitalWrite(segB, HIGH);

digitalWrite(segC, HIGH);
digitalWrite(segD, LOW);
digitalWrite(segE, LOW);
digitalWrite(segF, HIGH);
digitalWrite(segG, HIGH);
break;

case 5:// when count value is 5 show”5” on disp


digitalWrite(segA, HIGH);
digitalWrite(segB, LOW);
digitalWrite(segC, HIGH);
digitalWrite(segD, HIGH);
digitalWrite(segE, LOW);
digitalWrite(segF, HIGH);
digitalWrite(segG, HIGH);
break;

case 6:// when count value is 6 show”6” on disp


digitalWrite(segA, HIGH);
digitalWrite(segB, LOW);
digitalWrite(segC, HIGH);
digitalWrite(segD, HIGH);

digitalWrite(segE, HIGH);
digitalWrite(segF, HIGH);
digitalWrite(segG, HIGH);
break;

case 7:// when count value is 7 show”7” on disp


digitalWrite(segA, HIGH);
digitalWrite(segB, HIGH);
digitalWrite(segC, HIGH);
digitalWrite(segD, LOW);
digitalWrite(segE, LOW);
digitalWrite(segF, LOW);
digitalWrite(segG, LOW);
break;

case 8:// when count value is 8 show”8” on display


digitalWrite(segA, HIGH);
digitalWrite(segB, HIGH);
digitalWrite(segC, HIGH);
digitalWrite(segD, HIGH);
digitalWrite(segE, HIGH);
digitalWrite(segF, HIGH);

digitalWrite(segG, HIGH);
break;

case 9:// when count value is 9 show”9” on


disp digitalWrite(segA, HIGH);
digitalWrite(segB, HIGH);
digitalWrite(segC, HIGH);
digitalWrite(segD, HIGH);
digitalWrite(segE, LOW);
digitalWrite(segF, HIGH);
digitalWrite(segG, HIGH);
break;

break;

if (COUNT<10)

COUNT++;

delay(1000);///increment count integer for every second

if (COUNT==10)

{
COUNT=0;// if count integer value is equal to 10, reset it to zero.
delay(1000);
}

}
LAB Exercise 2
Make a project to display the numbers from 00 to 99 on two Seven-Segment. Create a circuit
diagram an develop code in Arduino IDE.

Required Hardware

 Arduino Uno - 1
 Programmer Cable - 1
 Seven-Segment Display - 2
 Bread Board - 1
 Male-Male Jumper Wires

Figure 4.8: Pin diagram of common anode seven segment

Attach the pins 3 and 8 on both the SSD's to 3.3V.(Use resistors)

Since this is for Common Anode SSD, the LED glows when it is LOW/0.

If you are using a Common Cathode SSD, attach pins 3 and 8 to ground and then the LEDs glow
when attached to HIGH/1.

Do not let 5 V pass through any of your LEDs, You must use resistors.
Table 4.5 connection table of Arduino uno with seven segment display
Arduino Pin SSD 1 Arduino Pin SSD 2
0 7 7 7
1 6 8 6
2 4 9 4
3 2 10 2
4 1 11 1
5 9 12 9
6 10 13 10

Project Circuit Diagram

Figure 4.9: Circuit diagram of counter display 00 to 99


Code

//SSD is Seven-Segment Display

void setup()
{
for (int
i = 0; i <= 13; i++)
pinMode(i, OUTPUT); //Set all pins from 0 to 13 as OUTPUT
}
//The line below is the array containing all the binary numbers
for the digits on a SSD from 0 to 9

const int number[11] = {0b1000000, 0b1111001, 0b0100100,


0b0110000,
0b0011001, 0b0010010, 0b0000010, 0b1111000, 0b0000000,
0b0010000};

void loop()
{

for (int tens = 0; tens < 10; tens++)

{
display_tens(tens);

}
}

void display_tens(const int tens)


{
int pin1, a, ones;

//pin1 is just used to deal with pins of the 1st SSD which
displays the tens digit

for (pin1 = 0, a = 0; pin1 < 7; pin1++, a++)


{
digitalWrite(pin1, bitRead(number[tens], a));
}
for (ones = 0; ones < 10; ones++)
{

display_ones(ones);
delay(300);
//I have given a delay of 300 milliseconds. You can put your
own Time!!
}
}

void display_ones(const int x)


{
int pin2, b;

//pin2 is just used to deal with pins of the 2nd SSD which
desplays the ones digit

for (pin2 = 7, b = 0; pin2 <= 13; pin2++, b++)


{
digitalWrite(pin2, bitRead(number[x], b));

bitRead()

Examples // sets x to 33 (00100001 in binary)


byte x = 33;
// Sets a = 1, since bitRead returns the value of the
5th bit of variable x
byte a = bitRead(x, 5);

Description The bitRead command returns the bit value of the bit index
requested

Syntax var = bitRead(byteValue, bitIndex)


ParametersbyteValue byte: the byte from which read the bit

bitIndex int: the bit to read

Returns the bit value 0 or 1

Precautions

Before you start to mess with a computer there are basic guidelines to be aware of, such as turn
the power off and watch out for static electricity. The three kind of activity that requires
touching the Arduino

 Setting up wire, component layout or breadboard. 


 Debugging a running setup.
 Moving, mounting up the board somewhere. 
Review Questions

Question 1
 Solve the LAB Exercise 1
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color

Question 2
 Solve the LAB Exercise 2
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color

LAB Assessment

Student Name LAB Rubrics CLO3 , P5, PLO3


Total Marks 10
Registration No Obtained Marks

Teacher Name Syed M Hamedoon

Date Signature
Experiment No. 05

Interface an LCD with Microcontroller.

Introduction
The main aim of this lab is to interface LCD with microcontroller (Arduino) and observe their
functionalities. The display shows whatever we transmit the data.

Objectives
 Understand the functionality of LCD
 Understand the code of Arduino and its working.
Outcomes
By the end of this experiment, student will have basic understanding of how to interface the
LCD with microcontroller and will also understand the working principle of LCD.

Theory Overview

LCD (Liquid Crystal Display) screen is an electronic display module and find a wide range of
applications. A 16x2 LCD display is very basic module and is very commonly used in various
devices and circuits. These modules are preferred over seven segments and other multi segment
LEDs as shown in figure 5.1

Figure 5.1 LCD diagram

Figure 5.2 LCD Pin diagram


Table 5.1 shows the basic pin description of LCD

Pin
Function Name
No
1 Ground (0V) Ground
2 Supply voltage; 5V (4.7V – 5.3V) Vcc
3 Contrast adjustment; through a variable resistor VEE
Selects command register when low; and data register Register
4
when high Select
5 Low to write to the register; High to read from the register Read/write
6 Sends data to data pins when a high to low pulse is given Enable
7 DB0
8 DB1
9 DB2
10 DB3
8-bit data pins
11 DB4
12 DB5
13 DB6
14 DB7
15 Backlight VCC (5V) Led+
16 Backlight Ground (0V) Led-

If you’ve ever attempted to connect an LCD display to an Arduino, you’ve probably noticed that it
uses a lot of Arduino pins. Even in 4-bit mode, the Arduino requires seven connections – half of
the Arduino’s available digital I/O pins.
Lab Exercise No 1

Make a project to interface LCD with microcontroller.

a) Make a circuit diagram


b) Develop a code to print your name on the LCD
c) Attached simulation diagram

Required Apparatus
 Arduino board
 Adjustable DC Power Supply
 Standard LCD - 16x2 White On Blue
 Resistors 220Ω
 Variable Resistor/Potential meter 10k Ohm
 Digital Multimeter
 Breadboard
 Probes
 Wires

Circuit Diagram 1

Figure 5.3 Circuit diagram 1 for LCD interfacing with Arduino


Table 5.1: LCD interfacing with Arduino

LCD Pin Arduino Pin


RS 12
EN 11
D4 5
D5 4
D6 3
D7 2

LCD
LCD ANODE +5 Volt
LCD CATHODE Ground

Procedure
The LCDs have a parallel interface, meaning that the microcontroller has to manipulate several
interface pins at once to control the display. The process of controlling the display involves
putting the data that form the image of what you want to display into the data registers, then
putting instructions in the instruction register. The Liquid Crystal Library simplifies this
for you so you don't need to know the low-level instructions. The Hitachi-compatible LCDs can
be controlled in two modes: 4-bit or 8-bit. The 4-bit mode requires seven I/O pins from the
Arduino, while the 8-bit mode requires 11 pins. For displaying text on the screen, you can do
most everything in 4-bit mode, so example shows how to control a 16x2 LCD in 4-bit mode.
There are sequence of steps to make this project are listed below

Step1: Prepare the circuit diagram according to figure 5.4 and figure 5.5
Step 2: Make a program to interface LCD with Arduino
Step 3: Connect the Arduino board to the computer using USB cable. Launch Arduino IDE
and ensure correct USB port number and board name for establishing the connection.
Step 4: Once the program is uploaded and running on Arduino, open serial monitor
Step 5: You can verify the output on LCD that shows the message that you write inside the
code.

CODE
// C++ code
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
const int rs=12;
const int en=11;
const int d4=5;
const int d5=4;
const int d6=3;
const int d7=2;
LiquidCrystal lcd(rs,en,d4,d5,d6,d7);
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
lcd.print("SM Hamedoon");
}

void loop() {
for(int positionCounter=1; positionCounter++;)
{
lcd.scrollDisplayLeft();
delay(500);
}
delay(1000);
}

LAB Exercise No. 2


Make a project by interfacing LCD with microcontroller using I2C

I2C
The I2C protocol is used to establish communication between two or more ICs (Integrated
Circuits), hence why it’s known as Inter-Integrated Circuit (I2C) communication. However, it
should be noted that I2C could also be used as a communication protocol between two ICs that
are located on the same PCB.

The solution is to use an I2C LCD display. It only uses two I/O pins that are not even part of the
digital I/O pin set and can be shared with other I2C devices.

I2C LCD Display Pinout

The I2C LCD Display has only four pins. The following is the pinout:

Figure 5.4 I2C LCD interfacing


Wiring an I2C LCD Display to an Arduino
I2C also known as Inter Integrated Circuit is a communication protocol used in Arduino boards. It
only uses two lines for communication and one of the most complex protocols to implement with
an Arduino board. Using I2C we can connect up to 128 devices with an Arduino board over a
single data line.I2C uses two lines which are SDA and SCL. Along with these two lines a pull up
resistor is used to maintain both SDA and SCL line high

Connecting an I2C LCD is much simpler than connecting a standard LCD. You only need to
connect four pins. Begin by connecting the VCC pin to the Arduino’s 5V output and the GND pin
to ground. Now we are left with the pins that are used for I2C communication. Note that each
Arduino board has different I2C pins that must be connected correctly. On Arduino boards with
the R3 layout, the SDA (data line) and SCL (clock line) are on the pin headers close to the AREF
pin. They are also referred to as A5 (SCL) and A4 (SDA).

I2C Arduino Uno

GND GND

VCC 5 Volt

SDA A4

SCL A5

Figure 5.5: Arduino interfacing with I2C LCD


Adjusting The LCD Contrast

After wiring the LCD, you will need to adjust the contrast of the LCD. On the I2C module, there
is a potentiometer that can be rotated with a small screwdriver.

Library Installation

Before you can proceed, you must install the LiquidCrystal_I2C library. This library allows you to
control I2C displays using functions that are very similar to the LiquidCrystal library.

To install the library, navigate to Sketch > Include Library > Manage Libraries… Wait for the
Library Manager to download the library index and update the list of installed libraries.

Filter your search by entering ‘liquidcrystal‘. Look for the LiquidCrystal I2C library by Frank de
Brabander. Click on that entry and then choose Install.
Determining the I2C Address

As previously stated, the I2C address of your LCD depends on the manufacturer. If your LCD has
a PCF8574 chip from Texas Instruments, its I2C address is 0x27; if it has a PCF8574 chip from
NXP Semiconductors, its I2C address is 0x3F.

If you’re not sure what your LCD’s I2C address is, you can run a simple I2C scanner sketch that
scans your I2C bus and returns the address of each I2C device it finds.

You can find this sketch under File > Examples > Wire > i2c_scanner.

Load the i2c_scanner sketch into your Arduino IDE.


Code

#include <Wire.h>

void setup() {
Wire.begin();

Serial.begin(9600);
while (!Serial); // Leonardo: wait for serial monitor
Serial.println("\nI2C Scanner");
}

void loop() {
int nDevices = 0;

Serial.println("Scanning...");

for (byte address = 1; address < 127; ++address) {


// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
byte error = Wire.endTransmission();

if (error == 0) {
Serial.print("I2C device found at address 0x");
if (address < 16) {
Serial.print("0");
}
Serial.print(address, HEX);
Serial.println(" !");

++nDevices;
} else if (error == 4) {
Serial.print("Unknown error at address 0x");
if (address < 16) {
Serial.print("0");
}
Serial.println(address, HEX);
}
}
if (nDevices == 0) {
Serial.println("No I2C devices found\n");
} else {
Serial.println("done\n");
}
delay(5000); // Wait 5 seconds for next scan
}

After you’ve uploaded the sketch, launch the serial monitor at 9600 baud. You should see the I2C
address of your I2C LCD display.

Please make a note of this address. You’ll need it in later examples.

Code

#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3F,16,2); // set the LCD address to 0x3F for a 16


chars and 2 line display

void setup() {
lcd.init();
lcd.clear();
lcd.backlight(); // Make sure backlight is on

// Print a message on both lines of the LCD.


lcd.setCursor(2,0); //Set cursor to character 2 on line 0
lcd.print("Hello world!");
lcd.setCursor(2,1); //Move cursor to character 2 on line 1
lcd.print("LCD Tutorial");
}

void loop() {
}

This is what you should see on the screen


Review Questions

Question 1
 Solve the LAB Exercise 1
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color

Question 2
 Solve the LAB Exercise 2
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color

LAB Assessment

Student Name LAB Rubrics CLO3 , P5, PLO3


Total Marks 10
Registration No Obtained Marks

Teacher Name Syed M Hamedoon

Date Signature
Experiment No. 6

Keypad interfacing with Microcontroller.

Introduction
The main aim of this lab is to interface keypad with microcontroller (Arduino) and observe their
functionalities.

Objectives
 Understand the functionality of Keypad
 Understand the code of Arduino and its working.
Outcomes
By the end of this experiment, student will understand how to interface the keypad with
microcontroller and will also understand the working principle of keypad.

Theory Overview
The keypad is a group of push buttons connected in such a way that each push button can be
recognized when it is pushed. The 4X4 keypad consists of 4 rows and 4 columns by pressing a push
button a row and a column are connected identifying the push button like an address this connection.
Keypad is used as an input device to read the key pressed by the user and to process it. 4x4 keypad
consists of 4 rows and 4 columns. Switches are placed between the rows and columns. A key press
establishes a connection between the corresponding row and column, between which the switch is
placed is described as the following figure10.1

Figure 6.1 Keypad 4 x 4


 Keypad library installation
The Arduino IDE has some pre-installed installed libraries to work with and these
libraries can be used and edited for the application required.
Keypad library is not installed so we will discuss how we can download a new library
to Arduino from the Internet.
First: search for the desired library which will be Keypad library

Write in the search field


“Arduino keypad
library”

Click on the first link

Figure 6.2 Search keypad library from google search engine

Second: This page will appear then scroll down till reaching the following image.
Click on this link to download the
library

Figure 6.3 clink the download link of the desired library

Third: Extract the downloaded to a folder named “Keypad” then copy the folder and
paste it to the destination where Arduino was downloaded in a folder named
“Libraries”.
Example: The default destination after downloading and installing will be “C:\Program
Files\Arduino\libraries” and if the computer’s processor is 64bit then the destination will be
“C:\Program Files (x86)\Arduino\libraries” .

Fourth: The keypad library will appear in the Arduino program that it can be
important as shown before.
LAB Exercise No. 1
Interface keypad with Arduino microcontroller and display the result on serial monitor screen

Required Hardware
 Arduino board
 Adjustable DC Power Supply
 Keypad 4 x 4
 Digital Multimeter
 Breadboard
 Probes
 Wires

Circuit Diagram

Figure 6.4 circuit diagram of keypad interfacing with Arduino


Pin Connection Table

Keypad pins Arduino Pins


R1 2
R2 3
R3 4
R4 5
C1 6
C2 7
C3 8
C4 9

Procedure
Reading the key pressed on 4x4 keypad and displaying it on the serial terminal of Arduino. Once
the library has been added to the Arduino IDE, open the IDE and open the example sketch for
CustomKeypad from the library added.

The sequence of steps to make this project are listed below


Step1: Prepare the circuit diagram according to figure 6.3
Step 2: Make a program to interface keypad with Arduino
Step 3: Connect the Arduino board to the computer using USB cable. Launch Arduino IDE
and ensure correct USB port number and board name for establishing the connection.
Step 4: Once the program is uploaded and running on Arduino, open the serial monitor
Step 5: Verify the output on Arduino IDE serial monitor

Code

#include <Keypad.h>
const byte rows=4;
const byte cols=4;
char hexkeypad[rows][cols]={{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}};

byte rowspins[rows]={2,3,4,5};
byte colspins[cols]={6,7,8,9};

Keypad kpd=Keypad(makeKeymap(hexkeypad),rowspins,colspins,rows,cols);
//

byte i=0;
void setup()
{
Serial.begin(9600);
for(i=0;i<8;i++)
{
pinMode(i, OUTPUT);

}
}

void loop()
{
char keypressed=kpd.getKey();

if(keypressed)
{
Serial.print("Key pressed is ");
Serial.println(keypressed);
}
}

Results
LAB Exercise No. 2
Interface keypad with Arduino microcontroller and display the result on LCD

Required Hardware
 Arduino board
 DC Power Supply 5 volt
 Keypad 4 x 4
 LCD 16 x 2
 Potentiometer (10k)
 Resistance (330 ohm)
 Digital Multimeter
 Breadboard
 Probes
 Wires

Circuit Diagram

Figure 6.5 Circuit diagram of LAB Exercise 2


Keypad Pin Connection Table

Keypad pins Arduino Pins


R1 9
R2 8
R3 7
R4 6
C1 5
C2 4
C3 3
C4 2

LCD Connection Table

LCD Pin Arduino Pins


1 Ground
2 Power (5volt)
3(contrast) Potentiometer middle Pin
4(Register Select) A0
5(Read/ Write) Ground
6 (Enable) A1
11(DB4) A2
12(DB5) A3
13(DB6) A4
14(DB7) A5
15 (LED Anode) 5 volt
16 (LED Cathode) Ground
Code

#include <Keypad.h>
#include "LiquidCrystal.h"
LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);

const byte ROWS = 4; //four rows


const byte COLS = 4; //four columns
char keys[ROWS][COLS] =
{
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'S','0','H','D'}
};
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

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

String v_passcode="";

void setup()
{
Serial.begin(9600);
lcd.begin(16,2);

lcd.setCursor(0,0);
lcd.print("LDR VALUE");

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

if (key != NO_KEY)
{
Serial.println(key);
lcd.setCursor(0,1);
lcd.print(key);

}
}

Precautions
Before you start to mess with a computer there are basic guidelines to be aware of,
such as turn the power off and watch out for static electricity. The three kind of
activity that requires touching the Arduino

 Setting up wire, component layout or breadboard.


 Debugging a running setup.
 Moving, mounting up the board somewhere.
Review Questions

Question 1
 Solve the LAB Exercise 1
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color
 Explain the working of LAB Exercise 1 with the help of code. Identify the scope of this project
in embedded system

Question 2
 Solve the LAB Exercise 2
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color
 Explain the working of LAB Exercise 2 with the help of code. Identify the scope of this project
in embedded system

Question 3
Identify the difference between stepper motor and servo motor

LAB Assessment

Student Name LAB Rubrics CLO3 , P5, PLO3


Total Marks 10
Registration No Obtained Marks

Teacher Name Syed M Hamedoon

Date Signature
Experiment No. 7
Pulse Width Modulation and its interfacing
Introduction
This lab describes the concept of pulse width modulation (PWM) and its functionalities to control the
LED brightness and control the DC motor using microcontroller. A direct current (DC) motor is a type
of electric machine that converts electrical energy into mechanical energy. DC motors take electrical
power through direct current, and convert this energy into mechanical rotation.

Objectives
 To understand the basic function of PWM using microcontroller (Arduino)
 To understand the basic hardware connection of Arduino with DC motor

Outcomes

By the end of this experiment, students understand the PWM functionality and its interfacing with
DC motor

PWM control using arduino.

PWM control is a very commonly used method for controlling the power across loads. This
method is very easy to implement and has high efficiency. PWM signal is essentially a high
frequency square wave ( typically greater than 1KHz). The duty cycle of this square wave is
varied in order to vary the power supplied to the load. Duty cycle is usually stated in percentage
and it can be expressed using the equation : % Duty cycle = (TON/(TON + TOFF))
*100. Where TON is the time for which the square wave is high and TOFF is the time for which
the square wave is low.When duty cycle is increased the power dropped across the load increases
and when duty cycle is reduced, power across the load decreases. The block diagram of a typical
PWM power controller scheme is shown below.

Figure 7.1 PWM power controller scheme

Control signal is what we give to the PWM controller as the input. It might be an analog or digital
signal according to the design of the PWM controller. The control signal contains information on
how much power has to be applied to the load. The PWM controller accepts the control signal and
adjusts the duty cycle of the PWM signal according to the requirements. PWM waves with various
duty cycle are shown in the figure below.
Figure 7.2 PWM duty cycles

In the above wave forms you can see that the frequency is same but ON time and OFF time are
different.Two applications of PWM control using arduino is shown here. Controlling the LED
brightness using arduino and motor speed control using arduino.

DC Motors

DC motors are becoming increasingly common in a variety of motor applications such as fans,
pumps, appliances, automation, and automotive drive. The reasons for their increased popularity
are better speed versus torque characteristics, high efficiency, long operating life, and noiseless
operation. In addition to these advantages, the ratio of torque delivered to the size of the motor is
higher, making it useful in applications where space and weight are critical factors. This makes
them attractive options for designers who are interested in robotics. You can run a DC motor by
supplying a voltage difference across its leads. However, you need to overcome certain challenges
in order to drive them effectively. The most common goals are variable speed and direction. To
control the direction of the spin of DC motors, without changing the way that the leads are
connected, an H-Bridge is commonly used.

H-Bridge
An H-bridge is an electronic circuit that can drive the motor in both directions. As shown in
Figure. 7.3, one H-bridge uses four transistors connected in such a way that the schematic diagram
appears like an “H”.

The basic operating mode of an H-bridge is fairly simple: if Q1 and Q3 are turned on, the left lead
of the motor is connected to the power supply, while the right lead is connected to the ground.
Current starts flowing through the motor, which energizes the motor in (let us say) the forward
direction and the motor shaft starts spinning.

If Q4 and Q2 are turned on, the reverse happens, the motor gets energized in the reverse direction,
and the shaft will start spinning backwards.
Figure 7.3: Working of H Bridge

In a bridge, you should never ever close both Q1 and Q2 (or Q3 and Q4) at the same time. If you
did that, you may create a really low-resistance path between the power and GND, effectively
short-circuiting your power supply. This condition is called “shoot-through” and is an almost
guaranteed way to quickly destroy your bridge, or something else in your circuit.

DC Motor Driver (L293N)


The common L293N dual motor controller is a 16-DIP IC chip that contains two protected driver
circuits capable of delivering up to 600 mA of continuous current to each motor at up to 36 VDC
(see Figure. 7.4). L298N is a similar chip that can deliver 2 amps to each motor. These chips (and
others) accept standard 0–5 V input signals and have internal logic gates to prevent accidental
overloading and commanding the controller into a destructive state.

Notice in Figure 8.4 that there are six pins labeled IN1, IN2, IN3, IN4, ENA, and ENB. You can
use digital pins on the Arduino to control the four input pins and set the motor direction, while
using a PWM signal on each enable pin (ENA and ENB) to set the speed of each motor. It should
be pointed out that L298N does not have
Figure 7.4: Schematic of L298N

Figure 7.4.1 Motor Driver (L293N)


Figure 7.4.2 Pin Connection Diagram L293N
LAB Exercise No. 1
To control the LED brightness using PWM

Required Hardware

 Arduino Uno
 LED’s
 Resistors (220 ohm)
 Wires
 Bread board

Circuit Diagram

Figure 7.5: Circuit Diagram of LED brightness

Code

int redLED=9;

int greenLED=10;

int blueLED=11;

int brightness=0;
int fade=5;

void setup() {

// put your setup code here, to run once:

pinMode(11, OUTPUT);

void loop() {

// put your main code here, to run repeatedly:

analogWrite(redLED,brightness);

analogWrite(greenLED,brightness);

analogWrite(blueLED,brightness);

brightness=brightness+fade;

if((brightness=0)||(brightness=255))

{ fade=-fade;

delay(50);

}
LAB Exercise No 2

To control the direction of DC motor using microcontroller with and with out PWM

Required Hardware

 DC motor
 Arduino Uno
 DC motor Driver (L293D)
 Wires

Circuit Diagram

Figure 7.6: Circuit diagram of DC motor interfacing with microcontroller

Pin connection Table

L293D Pins Motor and Arduino Pins

1 Enable Arduino Pin 10

2 Input1 Arduino Pin 6

3 Output1 Motor terminal 1


4 Ground Arduino Ground

5 Ground Arduino Ground

6 Output2 Motor terminal 2

7 Input2 Arduino Pin 7

8 VCC1 Arduino 5Volt

16 VCC2 to 8VCC1

Code

// C++ code
//
void setup()
{
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(10, OUTPUT);
digitalWrite(10, HIGH);

void loop()
{
digitalWrite(6, HIGH);
digitalWrite(7, LOW);
delay(3000); // Wait for 1000 millisecond(s)
digitalWrite(6, LOW);
digitalWrite(7, HIGH);
delay(3000); // Wait for 1000 millisecond(s)
}

Task 2

Write a code to control the DC motor using PWM and control the direction of motors in
clockwise, anticlockwise and for brake.

const int pwm = 2 ; //initializing pin 2 as pwm


const int in_1 = 8 ;

const int in_2 = 9 ;

//For providing logic to L298 IC to choose the direction of the DC motor

void setup()
{

pinMode(pwm,OUTPUT) ; //we have to set PWM pin as output

pinMode(in_1,OUTPUT) ; //Logic pins are also set as output

pinMode(in_2,OUTPUT) ;
}

void loop()
{

//For Clock wise motion , in_1 = High , in_2 = Low

digitalWrite(in_1,HIGH) ;

digitalWrite(in_2,LOW) ;

analogWrite(pwm,255) ;

/*setting pwm of the motor to 255

we can change the speed of rotaion

by chaning pwm input but we are only

using arduino so we are using higest

value to driver the motor */

//Clockwise for 3 secs

delay(3000) ;

//For brake

digitalWrite(in_1,HIGH) ;

digitalWrite(in_2,HIGH) ;

delay(1000) ;
//For Anti Clock-wise motion - IN_1 = LOW , IN_2 = HIGH

digitalWrite(in_1,LOW) ;

digitalWrite(in_2,HIGH) ;

delay(3000) ;

//For brake

digitalWrite(in_1,HIGH) ;

digitalWrite(in_2,HIGH) ;

delay(1000) ;

Task 3

Write a code to give command from serial monitor to the arduino and control the direction of
motor (clockwise , anticlock wise and stop)

void setup()
{
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(10, OUTPUT);
digitalWrite(10, HIGH);
Serial.begin(9600);

void loop()
{
if(Serial.available())
{
char ch=Serial.read();
if (ch=='c')
{
digitalWrite(6, LOW);
digitalWrite(7, HIGH);
}
else if (ch=='a')
{
digitalWrite(6, HIGH);
digitalWrite(7, LOW);
}
else if (ch=='s')
{
digitalWrite(6, LOW);
digitalWrite(7, LOW);
}
}
}
LAB Exercise No 3

To control the speed of DC motor by using potentiometer

Required Hardware

 DC motor
 Arduino Uno
 DC motor Driver (L293D)
 Potentiometer (10kohm)
 Supply voltage 9 volt
 Wires

Circuit Diagram

Figure 7.7: Circuit diagram of DC motor using potentiometer

Code

// C++ code
int potIn;
int fwdPin=5;
int revPin=6;

void setup()
{
pinMode(fwdPin, OUTPUT);
pinMode(revPin, OUTPUT);
Serial.begin(9600);
}

void loop()
{
potIn=analogRead(A0);
int output=potIn/4;

analogWrite(fwdPin,output);

Serial.println(output);
delay(100);
}

Output

Code 2

const int pwm = 2 ; //initializing pin 2 as pwm

const int in_1 = 8 ;

const int in_2 = 9 ;

//For providing logic to L298 IC to choose the direction of the DC motor

void setup()

pinMode(pwm,OUTPUT) ; //we have to set PWM pin as output

pinMode(in_1,OUTPUT) ; //Logic pins are also set as output

pinMode(in_2,OUTPUT) ;
}

void loop()
{

//For Clock wise motion , in_1 = High , in_2 = Low

digitalWrite(in_1,HIGH) ;

digitalWrite(in_2,LOW) ;

analogWrite(pwm,255) ;

/*setting pwm of the motor to 255

we can change the speed of rotaion

by chaning pwm input but we are only

using arduino so we are using higest

value to driver the motor */

//Clockwise for 3 secs

delay(3000) ;

//For brake

digitalWrite(in_1,HIGH) ;

digitalWrite(in_2,HIGH) ;

delay(1000) ;

//For Anti Clock-wise motion - IN_1 = LOW , IN_2 = HIGH

digitalWrite(in_1,LOW) ;

digitalWrite(in_2,HIGH) ;

delay(3000) ;

//For brake

digitalWrite(in_1,HIGH) ;

digitalWrite(in_2,HIGH) ;

delay(1000) ;
}
Review Questions
Question 1
 Solve the LAB Exercise 1
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color
 Explain the working of LAB Exercise 1 with the help of code. Identify the scope of this project
in embedded system

Question 2
 Solve the LAB Exercise 2 and LAB Exercise 3
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color
 Explain the working of LAB Exercise 2, 3 with the help of code. Identify the scope of this
project in embedded system
 Explain the working of DC motor

LAB Assessment

Student Name LAB Rubrics CLO3 , P5, PLO3


Total Marks 10
Registration No Obtained Marks

Teacher Name Syed M Hamedoon

Date Signature
Experiment No. 8

Controlling a stepper motor using Microcontroller

Introduction

This lab describes Stepper motors, due to their unique design, can be controlled to a high degree
of accuracy without any feedback mechanisms. The shaft of a stepper, mounted with a series of
magnets, is controlled by a series of electromagnetic coils that are charged positively and
negatively in a specific sequence, precisely moving it forward or backward in small "steps".

Objectives
 Understand the basic utility of microcontroller (Arduino)
 Understand the basic hardware connection of Arduino with stepper motor and servo motor
 Understand the software which is used for programming in Arduino for interfacing it with
stepper motor and servo motor

Outcomes
By the end of this experiment, students understand the Arduino interfacing with stepper motor
and servo motor.

Theory Overview Stepper Motor

To understand this we should first know how a stepper works and what its specialty is. First
of all steppers motors do not rotate, they step and so they also known as step motors. Meaning,
they will move only one step at a time. These motors have a sequence of coils present in them and
these coils have to be energized in a particular fashion to make the motor rotate. When each coil
is being energized the motor takes a step and a sequence of energization will make the motor take
continuous steps, thus making it to rotate. Let us take a look in figure 8.1 the coils present inside
the motor to know exactly know from where these wires come from.
Figure 8.1 Internal diagram of stepper Motor

As you can see the motor has Unipolar 5-lead coil arrangement. There are four coils which have
to be energized in a particular sequence. The Red wires will be supplied with +5V and the
remaining four wires will be pulled to ground for triggering the respective coil. We use a
microcontroller like Arduino energize these coils in a particular sequence and make the motor
perform the required number of steps.

A stepper motor is an electric motor whose main feature is that its shaft rotates by performing
steps, that is, by moving by a fixed amount of degrees. This feature is obtained thanks to the
internal structure of the motor, and allows to know the exact angular position of the shaft by simply
counting how may steps have been performed, with no need for a sensor. This feature also makes
it fit for a wide range of applications.

A stepper motor, also known as a step motor or stepping motor, is a brushless DC electric
motor that divides a full rotation into several equal steps. The motor's position can be commanded
to move and hold at one of these steps without any position sensor for feedback (an open-loop
controller), as long as the motor is correctly sized to the application concerning torque and speed.
Figure 8.2: Stepper Motor with driver ULN2003

Stepper Motor Control

We have seen previously that the motor coils need to be energized, in a specific sequence, to
generate the magnetic field with which the rotor is going to align. Several devices are used to
supply the necessary voltage to the coils, and thus allow the motor to function properly. Starting
from the devices that are closer to the motor we have:

A transistor bridge is the device physically controlling the electrical connection of the motor coils.
Transistors can be seen as electrically controlled interrupters, which, when closed allow the
connection of a coil to the electrical supply and thus the flow of current in the coil. One transistor
bridge is needed for each motor phase.

A pre-driver is a device that controls the activation of the transistors, providing the required voltage
and current, it is in turn controlled by an MCU.

An MCU is a microcontroller unit, which is usually programmed by the motor user and generates
specific signals for the pre-driver to obtain the desired motor behavior. Figure 8.3 shows a simple
representation of a stepper motor control scheme. The pre-driver and the transistor bridge may be
contained in a single device, called a driver.
Figure 8.3 Control circuit of stepper motor

Stepper Motor Driver Types

There are different stepper motor drivers available on the market, which showcase different
features for specific applications. The most important charactreristics include the input interface.
The most common options are:

Step/Direction – By sending a pulse on the Step pin, the driver changes its output such that the
motor will perform a step, the direction of which is determined by the level on the Direction pin.

Phase/Enable – For each stator winding phase, Phase determines the current direction and triggers
Enable if the phase is energized.

PWM – Directly controls the gate signals of the low-side and high-side FETs.

Another important feature of a stepper motor driver is if it is only able to control the voltage across
the winding, or also the current flowing through it:

Step angle
𝑁𝑠−𝑁𝑟
= x 360
𝑁𝑠 𝑁𝑟

Where 𝑁𝑠= number of teeth on stator and 𝑁𝑟= number of teeth on rotar
Example 𝑁𝑠 = 8; 𝑁𝑟 = 4, Find step angle?

8−4
= x360 =45𝑜
(8)(4)

In order to find the step angle of stepper motor when phase are available

Formula

3600
=
(𝑛𝑢𝑚𝑏𝑒𝑟 𝑜𝑓 𝑝ℎ𝑎𝑠𝑒𝑠)𝑁𝑟

Range: Minimum angle of stepper motor available inside market is 0.72 degree and maximum
angle is 90 degree. Most commonly used step size 1.8 degree, 2.7 degree and 15 degree used in
practical application

Stepper Motor Speed Calculation

Keep in mind that the stepper motor speed obtained from this formula is measured in revolutions
per second. Therefore, to measure the stepper motor speed in the more common “revolutions per
minute” convention, engineers should simply multiply the result from the equation by 60, as shown
below:

Example

Consider an example of a stepper motor with a command pulse rate of 20 steps per second and a
step angle of 1.8°. To estimate the stepper motor’s speed

Solution

first we have to calculate the motor’s number of steps in one revolution (360°) . This can be
obtained below:
20
𝑆𝑡𝑒𝑝𝑝𝑒𝑟 𝑀𝑜𝑡𝑜𝑟 𝑆𝑝𝑒𝑒𝑑 = 60 ∗ = 6 rpm
200

Full Step
Step angle 11.25 degree
Number of steps needed for single rotor 360 32 steps
degree
Half step
Step angle 5.625 degree
Number of steps needed for single rotor 360 64 steps
degree

SPECIFICATIONS:

 Stepper Motor Operating Voltage: 5V


 Stepper Motor Diameter: 28mm
 Step angle: 5.625 x 1 / 64
 Reduction ratio: 1 / 64
 5 Line 4 phase stepper motor is driven by ULN2003 chip
 Stepper motor supports easy and direct plugin to driver board
 A, B, C, D four-phase LED indicators indicate the status of the stepper motor
 Minimum delay between per steps=2ms
 Maximum speed =500steps/second

ULN2003 Motor Driver

It is an array of 7 darlington pairs. A Darlington pair is a pair of transistors where the second
transistor amplify the output current of the first transistor. This gives you higher current gain
than a single transistor and allows the low voltage output of microcontroller to drive the higher
current stepper motor. It supports seven input/output pairs but only needs 4 phases so only 4
pins are exposed
Figure 8.4: Motor Driver ULN2003
Figure 8.5: Pin diagram of ULN2003
LAB Exercise No 1

To interface stepper motor with Arduino microcontroller

Required hardware

 Stepper motor 28BYJ-48


 Angle of turn 5.625 degree
 Spin ratio 64
 Operating voltage 5Volt
 Arduino uno
 Wires
 Potentiometer 10kohm
 Stepper Motor Driver Board based on ULN2003.

Circuit diagram

Figure 8.5: Circuit diagram 2 without potentiometer


Figure 8.6: Circuit diagram 3 with pin connections using potentiometer

We can calculate it from the formula:

a number of steps = (360 ° / degree of a single spin) * spin ratio. The example of our stepper is:
(360 ° / 5.625 °) * 64 = 4096 steps.

Question 1

A stepper motor follows the turns of a potentiometer (or other sensor) on analog input 0.

Code

#include <Stepper.h>

// change this to the number of steps on your motor


#define STEPS 100

// create an instance of the stepper class, specifying


// the number of steps of the motor and the pins it's
// attached to
Stepper stepper(STEPS, 8, 9, 10, 11);

// the previous reading from the analog input


int previous = 0;

void setup() {
// set the speed of the motor to 30 RPMs
stepper.setSpeed(30);
}

void loop() {
// get the sensor value
int val = analogRead(0);

// move a number of steps equal to the change in the


// sensor reading
stepper.step(val - previous);

// remember the previous value of the sensor


previous = val;
}

Question 2

The motor should revolve one revolution in one direction, then one revolution in the other
direction.

Code

#include <Stepper.h>
const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:


Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
// set the speed at 60 rpm:
myStepper.setSpeed(60);
// initialize the serial port:
Serial.begin(9600);
}

void loop() {
// step one revolution in one direction:
Serial.println("clockwise");
myStepper.step(stepsPerRevolution);
delay(500);

// step one revolution in the other direction:


Serial.println("counterclockwise");
myStepper.step(-stepsPerRevolution);
delay(500);
}

Question 3

The motor will step one step at a time, very slowly. You can use this to test that you've got the
four wires of your stepper wired to the correctpins. If wired correctly, all steps should be in the
same direction.
Code

#include <Stepper.h>

const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:


Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

int stepCount = 0; // number of steps the motor has taken

void setup() {
// initialize the serial port:
Serial.begin(9600);
}

void loop() {
// step one step:
myStepper.step(1);
Serial.print("steps:");
Serial.println(stepCount);
stepCount++;
delay(500);
}

Question 4

The motor will rotate in a clockwise direction. The higher the potentiometer value, the faster the
motor speed. Because setSpeed() sets the delay between steps, you may notice the motor is less
responsive to changes in the sensor value at low speeds.

Code
#include <Stepper.h>

const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:


Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

int stepCount = 0; // number of steps the motor has taken

void setup() {
// nothing to do inside the setup
}

void loop() {
// read the sensor value:
int sensorReading = analogRead(A0);
// map it to a range from 0 to 100:
int motorSpeed = map(sensorReading, 0, 1023, 0, 100);
// set the motor speed:
if (motorSpeed > 0) {
myStepper.setSpeed(motorSpeed);
// step 1/100 of a revolution:
myStepper.step(stepsPerRevolution / 100);
}
}
Code

#define STEPPER_PIN_1 9
#define STEPPER_PIN_2 10
#define STEPPER_PIN_3 11
#define STEPPER_PIN_4 12
int step_number = 0;
void setup() {
pinMode(STEPPER_PIN_1, OUTPUT);
pinMode(STEPPER_PIN_2, OUTPUT);
pinMode(STEPPER_PIN_3, OUTPUT);
pinMode(STEPPER_PIN_4, OUTPUT);

void loop() {

OneStep(false);
delay(2);

void OneStep(bool dir){


if(dir){
switch(step_number){
case 0:
digitalWrite(STEPPER_PIN_1, HIGH);
digitalWrite(STEPPER_PIN_2, LOW);
digitalWrite(STEPPER_PIN_3, LOW);
digitalWrite(STEPPER_PIN_4, LOW);
break;
case 1:
digitalWrite(STEPPER_PIN_1, LOW);
digitalWrite(STEPPER_PIN_2, HIGH);
digitalWrite(STEPPER_PIN_3, LOW);
digitalWrite(STEPPER_PIN_4, LOW);
break;
case 2:
digitalWrite(STEPPER_PIN_1, LOW);
digitalWrite(STEPPER_PIN_2, LOW);
digitalWrite(STEPPER_PIN_3, HIGH);
digitalWrite(STEPPER_PIN_4, LOW);
break;
case 3:
digitalWrite(STEPPER_PIN_1, LOW);
digitalWrite(STEPPER_PIN_2, LOW);
digitalWrite(STEPPER_PIN_3, LOW);
digitalWrite(STEPPER_PIN_4, HIGH);
break;
}
}else{
switch(step_number){
case 0:
digitalWrite(STEPPER_PIN_1, LOW);
digitalWrite(STEPPER_PIN_2, LOW);
digitalWrite(STEPPER_PIN_3, LOW);
digitalWrite(STEPPER_PIN_4, HIGH);
break;
case 1:
digitalWrite(STEPPER_PIN_1, LOW);
digitalWrite(STEPPER_PIN_2, LOW);
digitalWrite(STEPPER_PIN_3, HIGH);
digitalWrite(STEPPER_PIN_4, LOW);
break;
case 2:
digitalWrite(STEPPER_PIN_1, LOW);
digitalWrite(STEPPER_PIN_2, HIGH);
digitalWrite(STEPPER_PIN_3, LOW);
digitalWrite(STEPPER_PIN_4, LOW);
break;
case 3:
digitalWrite(STEPPER_PIN_1, HIGH);
digitalWrite(STEPPER_PIN_2, LOW);
digitalWrite(STEPPER_PIN_3, LOW);
digitalWrite(STEPPER_PIN_4, LOW);
}
}
step_number++;
if(step_number > 3){
step_number = 0;
}
}
SERVO MOTOR
A servo motor is a type of motor that can rotate with great precision. Normally this type of motor
consists of a control circuit that provides feedback on the current position of the motor shaft, this
feedback allows the servo motors to rotate with great precision. If you want to rotate an object at
some specific angles or distance, then you use a servo motor. It is just made up of a simple motor
which runs through a servo mechanism. If motor is powered by a DC power supply then it is called
DC servo motor, and if it is AC-powered motor then it is called AC servo motor. For this tutorial,
we will be discussing only about the DC servo motor working. Apart from these major
classifications, there are many other types of servo motors based on the type of gear arrangement
and operating characteristics. A servo motor usually comes with a gear arrangement that allows us
to get a very high torque servo motor in small and lightweight packages. Due to these features,
they are being used in many applications like toy car, RC helicopters and planes, Robotics, etc.

For tilting the motors we have used small servo motors. In this experiment, we have mounted two
Futaba S-140 servo motors to tilt the brushless motors to a certain angle. This servomotor is can
rotate up to 180º. So we can rotate each brushless motor up to 45º from normal as the brushless
motors need to be at 90º for vertical takeoff or landing.

Figure 8.7: Servo Motor

Technical specifications of the Futaba S-140 Servo motor are given below:
Table 8 Specifications of Mini Servo Motor

Modulation Analog
Torque 4.8V: 122.0 oz-in (8.78 kg-cm)
Speed 4.8V: 0.70 sec/60°
Weight 2.54 oz (72.0 g)
Dimensions Length: 1.73 in (43.9 mm)
Length: 1.73 in (43.9 mm)

Controlling servo motor


Servo motor is controlled by PWM (Pulse with Modulation) which is provided by the control
wires. There is a minimum pulse, a maximum pulse and a repetition rate. Servo motor can turn 90
degree from either direction form its neutral position. The servo motor expects to see a pulse every
20 milliseconds (ms) and the length of the pulse will determine how far the motor turns. For
example, a 1.5ms pulse will make the motor turn to the 90° position, such as if pulse is shorter
than 1.5ms shaft moves to 0° and if it is longer than 1.5ms than it will turn the servo to 180°.

Figure 8.8: PWM used to move motor angle

This degree of rotation can be controlled by applying the Electrical Pulse of proper width, to its
Control pin. Servo checks the pulse in every 20 milliseconds. The pulse of 1 ms (1 millisecond)
width can rotate the servo to 0 degrees, 1.5ms can rotate to 90 degrees (neutral position) and 2 ms
pulse can rotate it to 180 degree.
LAB Exercise No 2

The first example controls the position of a RC (hobby) servo motor with your Arduino and a
potentiometer.

Hardware Required

 Arduino Board
 Servo Motor
 10k ohm potentiometer
 hook-up wires

Circuit description

Servo motors have three wires: power, ground, and signal. The power wire is typically red, and
should be connected to the 5V pin on the Arduino board. The ground wire is typically black or
brown and should be connected to a ground pin on the board. The signal pin is typically yellow or
orange and should be connected to PWM pin on the board. In these examples, it is pin number 9.
Wire the potentiometer so that its two outer pins are connected to power (+5V) and ground, and
its middle pin is connected to A0 on the board. Then, connect the servo motor to +5V, GND and
pin 9.

Circuit diagram

Figure 8.9 Circuit diagram of servo motor


Connection table

Servo motor Red wire +5volt


Servo motor Black wire ground
Servo motor Yellow/ orange PWM Pin 9 (Arduino )
Potentiometer (middle pin) A0 (Arduino)

Code

include<Servo.h>
Servo s1; // create servo object to control a servo

int pot=A0; // analog pin used to connect the potentiometer


int x;

int value;

void setup()
{
pinMode(A0,INPUT);
s1.attach(9); // attaches the servo on pin 9 to the servo object
}

void loop()
{
x=analogRead(pot); // reads the value of the potentiometer (value between 0 and 1023)
value=map(x,0,1023,0,180);
// scale it to use it with the servo (value between 0 and 180)
s1.write(value); // sets the servo position according to the scaled value
delay(15);
}

Sweeps the shaft of a RC servo motor back and forth across 180 degrees.

#include <Servo.h>

Servo myservo; // create servo object to control a servo


// twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position

void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}

void loop() {
for (pos = 0; pos <= 180; pos += 1)
{ // goes from 0 degrees to 180 degrees // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1)
{ // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
Review Questions

Question 1
 Solve the LAB Exercise 1
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color
 Explain the working of LAB Exercise 1 with the help of code. Identify the scope of this
project in embedded system

Question 2
 Solve the LAB Exercise 2
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color
 Explain the working of LAB Exercise 2 with the help of code. Identify the scope of this
project in embedded system

LAB Assessment

Student Name LAB Rubrics CLO3 , P5, PLO3


Total Marks 10
Registration No Obtained Marks
Teacher Name Syed M Hamedoon
Date Signature
Experiment No 9
Temperature Sensor interfacing with microcontroller

Introduction
This lab describes the temperature sensor LM35 and its interfacing with microcontroller. It is a
temperature measuring device having an analog output voltage proportional to the temperature.
It provides output voltage in Centigrade (Celsius). It does not require any external calibration
circuitry. The sensitivity of LM35 is 10 mV/degree Celsius. As temperature increases, output
voltage also increases. So, the code first reads the ADC value from the sensor, then converts it to
an equivalent voltage, and finally converts that voltage value to a temperature value in degrees
Celsius.

Objectives
 To understand the basic working of temperature sensor
 To understand the basic hardware connection of Arduino with temperature sensor and
observe its working

Outcomes
By the end of this experiment, students understand the Arduino interfacing with temperature
sensor

How to use LM35 Temperature Sensor

LM35 is a precession Integrated circuit Temperature sensor, whose output voltage varies, based
on the temperature around it. It is a small and cheap IC which can be used to measure temperature
anywhere between -55°C to 150°C. It can easily be interfaced with any Microcontroller that has
ADC function or any development platform like Arduino.

Power the IC by applying a regulated voltage like +5V (VS) to the input pin and connected the
ground pin to the ground of the circuit. Now, you can measure the temperature in form of voltage
as shown below.

Figure 9.1 LM35 diagram


If the temperature is 0°C, then the output voltage will also be 0V. There will be rise of 0.01V
(10mV) for every degree Celsius rise in temperature. The voltage can converted into temperature
using the below formulae.

Because we didn’t configure the reference voltage (ARef) used for analog input (the default analog
reference on 5V Arduino boards is 5 volts), the maximum resolution we get from the ADC is
5/1024 = 4.88 mV or 0.49°C.

For better results, using the 3.3v reference voltage as ARef instead of the 5V will be more precise
and less noisy. With 3.3V as the reference voltage, we get a resolution of 3.3/1024 = 3.22 mV or
0.32°C.

Figure 9.2 LM35 Pin Diagram


VCC is the power supply pin of the LM35 temperature sensor IC that can be connected
to 4V or 32V of the supply.

GND is the ground pin of the LM35 temperature sensor IC and it should be connected to
the supply ground.

OUT This is the temperature sensor analog output pin. This is the analog output pin of
the temperature sensor, the output voltage on this pin is directly proportional to the
temperature.

LM35 Sensor Pinout Configuration

Pin Pin Description


Number Name

1 Vcc Input voltage is +5V for typical applications

2 Analog There will be increase in 10mV for raise of every 1°C.


Out Can range from -1V(-55°C) to 6V(150°C)

3 Ground Connected to ground of circuit

LM35 Sensor Features

 Minimum and Maximum Input Voltage is 35V and -2V respectively. Typically 5V.
 Can measure temperature ranging from -55°C to 150°C
 Output voltage is directly proportional (Linear) to temperature (i.e.) there will be a rise of
10mV (0.01V) for every 1°C rise in temperature.
 ±0.5°C Accuracy
 Drain current is less than 60uA
 Low cost temperature sensor
 Small and hence suitable for remote applications
LAB Exercise No 1

To connect temperature sensor with Arduino microcontroller and observe its working using
serial monitor

Required Hardware

 Arduino Uno
 LM35
 Jumping wires
 Breadboard

Circuit diagram

Figure 9.3 Circuit diagram of LAB Exercise 1


Code
// LM35 is connected to this PIN

#define sensorPin A0

void setup() {

// Init serial at 9600 baud

Serial.begin(9600);

void loop() {

//Read Raw ADC Data

int adcData = analogRead(sensorPin);

// Convert that ADC Data into voltage

float voltage = adcData * (5.0 / 1024.0);

// Convert the voltage into temperature

float temperature = voltage * 100;

// Print the temperature data

Serial.print("Temperature: ");

Serial.print(temperature);

Serial.println("*C");

delay(800); // wait a second between readings

}
Lab Exercise No.2
To connect temperature sensor with Arduino and according to the temperature value turn ON the
LEDs.
Required Hardware

 Arduino Uno
 USB Micro-B cable for power
 Breadboard
 5x Jumper wires (M-M)
 1x TMP36 temperature sensor

Circuit diagram

Figure 9.4 Circuit diagram of LAB Exercise No. 2


Connection Table
LED Arduino Pin
RED 12
Yellow 11
Green 10

TMP35 A0

Code
int baselineTemp = 0;
int celsius = 0;
int fahrenheit = 0;

void setup()
{
pinMode(A0, INPUT);
Serial.begin(9600);

pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
}
void loop()
{
// set threshold temperature to activate LEDs
baselineTemp = 40;
// measure temperature in Celsius
celsius = map(((analogRead(A0) - 20) * 3.04), 0, 1023, -40, 125);

// convert to Fahrenheit
fahrenheit = ((celsius * 9) / 5 + 32);
Serial.print(celsius);
Serial.print(" C, ");
Serial.print(fahrenheit);
Serial.println(" F");
if (celsius < baselineTemp) {
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
}
if (celsius >= baselineTemp && celsius < baselineTemp + 10) {
digitalWrite(12, HIGH);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
}
if (celsius >= baselineTemp + 10 && celsius < baselineTemp + 20) {
digitalWrite(12, HIGH);
digitalWrite(11, HIGH);
digitalWrite(10, LOW);
}
if (celsius >= baselineTemp + 20 && celsius < baselineTemp + 30) {
digitalWrite(12, HIGH);
digitalWrite(11, HIGH);
digitalWrite(10, HIGH);
}
if (celsius >= baselineTemp + 30) {
digitalWrite(12, HIGH);
digitalWrite(11, HIGH);
digitalWrite(10, HIGH);
}
delay(1000); // Wait for 1000 millisecond(s)
}

Output

Adjust the temperature by clicking on the temperature sensor and dragging the black circle to
different temperatures, see Fig 9.5.
Figure 9.5: Temperature sensor calibration
Watch the LEDs display that the temperature is either hot, warm or cool, see Figure 9.6 for
the temperature key

Figure 9.6: LED’s Turn ON according to Temperature value


LAB Exercise No 3
To connect the temperature sensor with Arduino and display the temperature reading on the LCD
screen.
Description:
The temperature sensor in Arduino converts the surrounding temperature to voltage. It further
converts the voltage to Celcius, Celcius to Fahrenheit, and prints the Fahrenheit temperature on
the LCD screen.

Hardware Required

The components required for the project are listed below:

 1 x TMP 36 sensor (Temperature sensor)


 1 x LCD display
 Arduino UNO R3 board (We can take any Arduino board).
 Jump wires

Principle

We will connect the LCD Display and TMP 36 temperature sensor with the Arduino UNO R3
board. The sensor detects the surrounding temperature and converts it into volts, to Celsius to
Fahrenheit, and displays Fahrenheit temperature on the LCD screen.

Connection

The steps to set up the connection are listed below:

 Connect the RS pin of LCD to pin 13 of the Arduino board.


 Connect the Enable pin of LCD to pin 12 of the Arduino board.
 Connect the D4 pin of LCD to pin 6 of the Arduino board.
 Connect the D5 pin of LCD to pin 4 of the Arduino board.
 Connect the D6 pin of LCD to pin 3 of the Arduino board.
 Connect the D7 pin of LCD to pin 2 of the Arduino board.
 Connect the Vo pin of LCD to pin 8 of the Arduino board.
 Connect the middle terminal to a sensor to A0(analog pin).
 Connect one end of the sensor to GND and another end to 5V.
 Connect one end of a resistor to the A and K of the LCD and another end to 5V.

Code

#include <LiquidCrystal.h>
// initialize the library with the pins on the Arduino board
LiquidCrystal lcd(13, 12, 6, 4, 3, 2);
const int temperature = A0; //A0 is the analog pin
const int D = 8; // Vo of LCD is connected to pin 8 of the Arduino
void setup()
{
lcd.begin(16, 2);
Serial.begin(9600);
. pinMode(D, OUTPUT);
.}
. void loop()
.{
. digitalWrite(D,LOW);
. int Temp = analogRead(temperature);
. float volts = (Temp / 965.0) * 5;
. float celcius = (volts - 0.5) * 100;
. float fahrenheit = (celcius * 9 / 5 + 32);
. Serial.println(fahrenheit);
. lcd.setCursor(5, 0);
. lcd.print(fahrenheit);
. delay(2000);
. // time delay of 2000 microseconds or 2 seconds
.}
Circuit diagram

Figure 9.7: Circuit diagram of Lab Exercise No 3

Output

The output is now visible on the LCD screen.

For better understanding, let's consider the output on the Serial Monitor.

The following sketch will print the temperature values on the 16×2 character I2C LCD. The code
is similar to the first example, except that the values are printed on the I2C LCD.
Figure 9.8: Circuit diagram of Lab Exercise No 3 with I2C

Code
// Include the LiquidCrystal_I2C library
#include <LiquidCrystal_I2C.h>

// Create a new instance of the LiquidCrystal_I2C class


LiquidCrystal_I2C lcd(0x3F, 16, 2);

// Define a custom degree character


byte Degree[] = {
B00111,
B00101,
B00111,
B00000,
B00000,
B00000,
B00000,
B00000
};

// Define the analog pin, the TMP36's Vout pin is connected to


#define sensorPin A0

void setup() {
// Start the LCD and turn on the backlight
lcd.init();
lcd.backlight();

// Create a custom character


lcd.createChar(0, Degree);
}

void loop() {
// Get the voltage reading from the TMP36
int reading = analogRead(sensorPin);

// Convert that reading into voltage


// Replace 5.0 with 3.3, if you are using a 3.3V Arduino
float voltage = reading * (5.0 / 1024.0);

// Convert the voltage into the temperature in Celsius


float temperatureC = (voltage - 0.5) * 100;

// Print the temperature on the LCD;


lcd.setCursor(0, 0);
lcd.print("Temperature:");
lcd.setCursor(0, 1);
lcd.print(temperatureC, 1);
lcd.write(0); // print the custom degree character
lcd.print("C ");

// Print the temperature in Fahrenheit


float temperatureF = (temperatureC * 9.0 / 5.0) + 32.0;
lcd.print(temperatureF, 1);
lcd.write(0); // print the custom degree character
lcd.print("F ");

delay(1000); // wait a second between readings


}
Review Questions

Question 1
 Solve the LAB Exercise 1
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color
 Explain the working of LAB Exercise 1 with the help of code. Identify the scope of this
project in embedded system

Question 2
 Solve the LAB Exercise 2
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color
 Explain the working of LAB Exercise 2 with the help of code. Identify the scope of this
project in embedded system

Question 3
 Solve the LAB Exercise 3
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color
 Explain the working of LAB Exercise 3 with the help of code. Identify the scope of this
project in embedded system

LAB Assessment

Student Name LAB Rubrics CLO3 , P5, PLO3


Total Marks 10
Registration No Obtained Marks

Teacher Name Syed M Hamedoon

Date Signature
Experiment No 10
Ultrasonic Sensor interfacing with microcontroller

Introduction
This lab describes the working of ultrasonic sensor and its interfacing with microcontroller. It
works by sending out a sound wave at ultrasonic frequency and waits for it to bounce back from
the object. Then, the time delay between transmission of sound and receiving of the sound is used
to calculate the distance. It is used in many projects such as obstacle detector and electronic
distance measurement tapes etc.

Objectives
 To understand the basic working of ultrasonic sensor
 To understand the basic hardware connection of microcontroller with ultrasonic sensor and
observe its working

Outcomes
By the end of this experiment, students understand the microcontroller interfacing with
ultrasonic sensor

Theory
An Ultrasonic Sensor is a device that measures distance to an object using Sound Waves. It works
by sending out a sound wave at ultrasonic frequency and waits for it to bounce back from the
object. Then, the time delay between transmission of sound and receiving of the sound is used to
calculate the distance. It is done using the formula

Distance = (Speed of sound * Time delay) / 2

We divide the distance formula by 2 because the sound waves travel a round trip i.e from the sensor
and back to the sensor which doubles the actual distance.
The HC-SR04 is a typical ultrasonic sensor which is used in many projects such as obstacle
detector and electronic distance measurement tapes. Ultrasound is a high-pitched sound wave
whose frequency exceeds the audible range of human hearing.

Figure 10.1 frequency band of ultrasonic sensor


Humans can hear sound waves that vibrate in the range of about 20 times a second (a deep rumbling
noise) to 20,000 times a second (a high-pitched whistle). However, ultrasound has a frequency of
more than 20,000 Hz and is therefore inaudible to humans.

HC-SR04 Hardware Overview

An HC-SR04 ultrasonic distance sensor actually consists of two ultrasonic transducers.

 One acts as a transmitter that converts the electrical signal into 40 KHz ultrasonic sound
pulses.
 The other acts as a receiver and listens for the transmitted pulses.
 When the receiver receives these pulses, it produces an output pulse whose width is
proportional to the distance of the object in front.

Figure 10.2 HC-SR04

This sensor provides excellent non-contact range detection between 2 cm to 400 cm (~13 feet)
with an accuracy of 3 mm. Since it operates on 5 volts, it can be connected directly to an Arduino
or any other 5V logic microcontroller.
HC-SR04 Ultrasonic Sensor Pinout

Figure 10.3 Ultrasonic sensor pinout

VCC supplies power to the HC-SR04 ultrasonic sensor. You can connect it to the 5V output
from your Arduino.

Trig (Trigger) pin is used to trigger ultrasonic sound pulses. By setting this pin to HIGH for
10µs, the sensor initiates an ultrasonic burst.

Echo pin goes high when the ultrasonic burst is transmitted and remains high until the sensor
receives an echo, after which it goes low. By measuring the time the Echo pin stays high, the
distance can be calculated

How Does HC-SR04 Ultrasonic Distance Sensor Work?

It all starts when the trigger pin is set HIGH for 10µs. In response, the sensor transmits an ultrasonic
burst of eight pulses at 40 kHz. This 8-pulse pattern is specially designed so that the receiver can
distinguish the transmitted pulses from ambient ultrasonic noise.

These eight ultrasonic pulses travel through the air away from the transmitter. Meanwhile the echo
pin goes HIGH to initiate the echo-back signal.
Figure 10.4 Ultrasonic sensor transmission waveform

if those pulses are not reflected back, the echo signal times out and goes low after 38ms (38
milliseconds). Thus a pulse of 38ms indicates no obstruction within the range of the sensor.

If those pulses are reflected back, the echo pin goes low as soon as the signal is received. This
generates a pulse on the echo pin whose width varies from 150 µs to 25 ms depending on the
time taken to receive the signal.
Figure 10.4 Ultrasonic sensor Reception waveform

Calculating the Distance by using an example

The width of the received pulse is used to calculate the distance from the reflected object. This can
be worked out using the simple distance-speed-time equation we learned in high school. An easy
way to remember the equation is to put the letters in a triangle.

Let us take an example to make it more clear. Suppose we have an object in front of the sensor at
an unknown distance and we receive a pulse of 500µs width on the echo pin. Now let’s calculate
how far the object is from the sensor. For this we will use the below equation.

Distance = Speed x Time


Here we have the value of time i.e. 500 µs and we know the speed. Of course it’s the speed of
sound! It is 340 m/s. To calculate the distance we need to convert the speed of sound into cm/µs.
It is 0.034 cm/μs. With that information we can now calculate the distance!

Distance = 0.034 cm/µs x 500 µs

But we’re not done yet! Remember that the echo pulse indicates the time it takes for the signal to
be sent and reflected back. So to get the distance, you have to divide your result by two.

Distance = (0.034 cm/µs x 500 µs) / 2

Distance = 8.5 cm

Now we know that the object is 8.5 cm away from the sensor.
LAB Exercise No 1

To interface ultrasonic sensor with (Arduino) microcontroller and view the distance on the serial
monitor

Required Hardware:

 Arduino Uno

 HC-SR04 Module

 Bread board

 Jumper wires

 HC-SR04.

Circuit Diagram 1

Figure 10.5 Circuit diagram of ultrasonic sensor with Arduino


Circuit Diagram 2

Figure 10.6 Circuit diagram 2 of ultrasonic sensor with Arduino

The connections are as follows:

 Vcc to 5V Pin of the Arduino.

 Gnd to Gnd Pin of the Arduino.

 Trig to Digital Pin 9 .

 Echo to Digital Pin 10.


Code

/*
* Ultrasonic Sensor HC-SR04 interfacing with Arduino.

*/

// defining the pins

const int trigPin = 9;

const int echoPin = 10;

// defining variables

long duration;

int distance;

void setup() {

pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output

pinMode(echoPin, INPUT); // Sets the echoPin as an Input

Serial.begin(9600); // Starts the serial communication

void loop() {

// Clears the trigPin

digitalWrite(trigPin, LOW);

delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds

digitalWrite(trigPin, HIGH);
delayMicroseconds(10);

digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds

duration = pulseIn(echoPin, HIGH);

// Calculating the distance

distance= duration*0.034/2;

// Prints the distance on the Serial Monitor

Serial.print("Distance: ");

Serial.println(distance);

// Calculating the distance


distance= duration*0.034/2
duration is the time it takes for the ultrasonic pulse to travel from the sensor to the object and back,
measured in microseconds.0.034 is the speed of sound in centimeters per microsecond.
duration * 0.034 calculates the distance that the ultrasonic pulse has traveled from the sensor to the object
and back in centimeters. /2 divides the distance by 2 because the distance measured is the round trip distance
from the sensor to the object and back. To get the one-way distance to the object, we need to divide by 2.
The distance is the final result, which represents the distance to the object in centimeters.
Output
Lab Exercise No 2
To interface LEDs with ultrasonic sensor and turn ON the LED on the basis of distances
calculated by the ultrasonic sensor using microcontroller
Circuit diagram

Figure 10.7 Circuit diagram of Lab Exercise No 2

Code
const int trigPin = 6; // Ultrasonic sensor trigger pin
const int echoPin = 5; // Ultrasonic sensor echo pin
const int ledPin1 = 10; // LED 1 pin
const int ledPin2 = 9; // LED 2 pin
const int ledPin3 = 8; // LED 3 pin

void setup() {
Serial.begin(9600); // Start serial communication
pinMode(trigPin, OUTPUT); // Set trigger pin as output
pinMode(echoPin, INPUT); // Set echo pin as input
pinMode(ledPin1, OUTPUT); // Set LED 1 pin as output
pinMode(ledPin2, OUTPUT); // Set LED 2 pin as output
pinMode(ledPin3, OUTPUT); // Set LED 3 pin as output
}

void loop() {
digitalWrite(trigPin, LOW); // Set trigger pin low for 2 microseconds
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); // Set trigger pin high for 10 microseconds
delayMicroseconds(10);
digitalWrite(trigPin, LOW); // Set trigger pin low again

float duration = pulseIn(echoPin, HIGH); // Measure the duration of the pulse from echo pin
float distance = duration * 0.034 / 2; // Convert the duration to distance in centimeters

Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");

if (distance < 20) { // If distance is less than 20 cm, turn on LED 1


digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
}
else if (distance < 40) { // If distance is between 20 cm and 40 cm, turn on LED 2
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, HIGH);
digitalWrite(ledPin3, LOW);
}
else { // If distance is greater than 40 cm, turn on LED 3
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, HIGH);
}

delay(100); // Wait for 100 milliseconds before taking the next measurement
}
LAB Exercise No 3
To interface ultrasonic sensor with microcontroller and measured the distance in cm also display
the value on the LCD screen
Required Hardware
 Ultrasonic sensor
 Jumping wires
 Bread board
 I2C LCD 16 x 2

Circuit Diagram

Figure 10.8 Circuit diagram of Lab Exercise No 3

Library Installation

Before we upload the code and start playing with the sensor we need to install a library called I2C
LCD.
Figure 10.9 Library Installation of I2C LCD
Code
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3F, 16, 2); // I2C address 0x3F, 16


column and 2 rows

int trigPin = 9; // TRIG pin


int echoPin = 8; // ECHO pin

float duration_us, distance_cm;

void setup() {
lcd.init(); // initialize the lcd
lcd.backlight(); // open the backlight
pinMode(trigPin, OUTPUT); // config trigger pin to output mode
pinMode(echoPin, INPUT); // config echo pin to input mode
}

void loop() {
// generate 10-microsecond pulse to TRIG pin
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// measure duration of pulse from ECHO pin


duration_us = pulseIn(echoPin, HIGH);

// calculate the distance


distance_cm = 0.017 * duration_us;

lcd.clear();
lcd.setCursor(0, 0); // start to print at the first row
lcd.print("Distance: ");
lcd.print(distance_cm);

delay(500);
}
Figure 10.10: Project Final running diagram
Review Questions

Question 1
 Solve the LAB Exercise 1
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color
 Explain the working of LAB Exercise 1 with the help of code. Identify the scope of this
project in embedded system

Question 2
 Solve the LAB Exercise 2
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color
 Explain the working of LAB Exercise 2 with the help of code. Identify the scope of this
project in embedded system

Question 3
 Solve the LAB Exercise 3
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color
 Explain the working of LAB Exercise 3 with the help of code. Identify the scope of this
project in embedded system

LAB Assessment

Student Name LAB Rubrics CLO3 , P5, PLO3


Total Marks 10
Registration No Obtained Marks

Teacher Name Syed M Hamedoon

Date Signature
Experiment No. 11
IR sensor and PIR sensor interfacing with microcontroller
Introduction
This lab describes the working of infrared and PIR sensor and its interfacing with
microcontroller.
Objectives
 To understand the basic working of IR and PIR sensor
 To understand the basic hardware connection of microcontroller with IR and PIR sensor
and observe its working

Outcomes
By the end of this experiment, students understand the microcontroller interfacing with IR and
PIR sensor
Theory
An IR sensor or infrared sensor is a type of electronic device that emits light in order to detect
certain aspects of its surroundings. The sensor module is ambient light-adaptable, with a pair of
infrared emitting and receiving tubes. Usually, in the infrared spectrum, all the objects radiate
some form of thermal radiation. These types of radiations are invisible to our eyes, but infrared
sensor can detect these radiations. At a specific frequency, the transmitting tubes emit infrared.
When the direction of an obstacle is detected (reflective surface), the receiving tube receives the
infrared reflected. After a comparator circuit processing, the green light turns on. And the signal
output interfaces a digital signal (a low-level signal). The sensor’s effective distance range is 2 ~
30cm. The sensor’s detection range can be adjusted by adjusting the potentiometer.

IR Sensor Specifications

Voltage 3.3V – 5V DC

Supply Current 20mA

Range Up to 20cm

Sensing range Adjustable via potentiometer


The emitter is simply an IR LED (Light Emitting Diode) and the detector is simply an IR
photodiode . Photodiode is sensitive to IR light of the same wavelength which is emitted by the IR
LED. When IR light falls on the photodiode, the resistances and the output voltages will change
in proportion to the magnitude of the IR light received.
There are different types of infrared transmitters depending on their wavelengths, output power and
response time. An IR sensor consists of an IR LED and an IR Photodiode, together they are called
as PhotoCoupler or OptoCoupler.

IR Transmitter or IR LED

Infrared Transmitter is a light emitting diode (LED) which emits infrared radiations called as IR
LED’s. Even though an IR LED looks like a normal LED, the radiation emitted by it is invisible to
the human eye.

The picture of an Infrared LED is shown below.

Figure 11.1 IR LED

IR Receiver or Photodiode

Infrared receivers or infrared sensors detect the radiation from an IR transmitter. IR receivers come
in the form of photodiodes and phototransistors. Infrared Photodiodes are different from normal
photo diodes as they detect only infrared radiation. Below image shows the picture of an IR
receiver or a photodiode,
Figure 11.2 IR Receiver LED

Different types of IR receivers exist based on the wavelength, voltage, package, etc. When used in
an infrared transmitter – receiver combination, the wavelength of the receiver should match with
that of the transmitter.

The emitter is an IR LED and the detector is an IR photodiode. The IR photodiode is sensitive to
the IR light emitted by an IR LED. The photo-diode’s resistance and output voltage change in
proportion to the IR light received. This is the underlying working principle of the IR sensor.

Figure 11.3: Working of IR sensor


When the IR transmitter emits radiation, it reaches the object and some of the radiation reflects
back to the IR receiver. Based on the intensity of the reception by the IR receiver, the output of
the sensor defines.

Application of IR Sensor

1. Detecting obstacles
2. Safety devices for industry
3. Encoder for shaft
4. Fixed detection of frequency
5. Encoder of wheels

Pin diagram of IR sensor

Figure 11.4 Pin diagram of IR sensor


LAB Exercise No 1
Construct a program in Arduino microcontroller to detect the object using IR sensor when the
object is detected the LED should be turn ON and display the message on serial monitor of
sensor value. IR Sensor’s connected to digital pin 2. LED connected from digital pin 13 to
ground through a 220ohm resistor.
Required Hardware
 Arduino Uno
 IR sensor
 LED
 Bread boards
 Wires

Circuit Diagram

Figure 11.5: Circuit diagram of LAB Exercise No. 1


Code
/*** Arduino with IR Sensor ***/

int SensorPin = 2;
int OutputPin = 13;

void setup() {
pinMode(OutputPin, OUTPUT);
pinMode(SensorPin, INPUT);
Serial.begin(9600);
}

void loop() {
int SensorValue = digitalRead(SensorPin);

Serial.print("SensorPin Value: ");


Serial.println(SensorValue);
delay(1000);
if (SensorValue==LOW){ // LOW MEANS Object Detected
digitalWrite(OutputPin, HIGH);
}
else
{
digitalWrite(OutputPin, LOW);
}
}

You should see your LED turn ON, when a object comes in the range of the IR Sensor. If you
cannot see the desired output, ensure the circuit has been properly assembled, and verified and
uploaded the code to your board.
Lab Exercise No 2
Make a project to detect the obstacle in front of IR sensor counts them and display the value on
the LCD screen using microcontroller
Required hardware
 Arduino Uno
 Breadboard
 Wires
 I2C LCD(16x2)
 IR sensor

Circuit Diagram

Figure 11.6 circuit diagram of LAB Exercise no 2


Code

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// Set the LCD address to 0x27 or 0x3f for a 16 chars and 2 line display

LiquidCrystal_I2C lcd(0x27, 20, 4);


int LED = 11;
// Use the onboard Uno LED
int isObstaclePin = 7;
// This is our input pin

int isObstacle = HIGH;


// HIGH MEANS NO OBSTACLE

void setup()

{
lcd.init();
lcd.backlight();
pinMode(LED, OUTPUT);
pinMode(isObstaclePin, INPUT);
Serial.begin(9600);
}
void loop()
{
int Value = analogRead(A0);
Serial.println("OBSTACLE!!, OBSTACLE!!");
Serial.print("Analog read: ");
Serial.println(Value);
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" INFRARED LIGHT ");
lcd.setCursor(5,1);
lcd.print(Value);
if(Value < 770)
{
digitalWrite(LED,HIGH);
}
else
{
digitalWrite(LED,LOW);
}
delay(200);
}

Project Hardware Diagram


PIR Sensor
PIR sensor is a small low priced passive infrared sensor motion detector sensor. It does not emit
radiation like IR sensor but it detects the changes in infrared radiation of the source.

Figure 11.7: Pin diagram of PIR sensor

PIR sensor working


It works on the principle whenever it detects a change in infrared radiation it generates a digital
output signal. PIR sensor consists of Fresnel -lens. This lens is made of high density polythene that
concentrates the incoming infrared radiations so that they fall on the pyroelectric material. This
type of material detects the change in infrared radiations and generates the output signal.
Figure 11.8: working principle of PIR sensor
It is made up of 2 slots of special material sensitive to IR. When a person comes in the range of
sensor, the first slot creates a potential differential of voltage similarly when a person leave it
creates a negative differential voltage. These changes are detected

Figure 11.9: working principle of PIR sensor


The output signal is further processed by external circuit and converted in to digital output.
The PIR sensor detect the motion and gives the corresponding digital output.
What does PIR sensor detect?
PIR sensor can detect animal and human motion. Human emit infrared radiation. When a human
comes in to the sensing range of the PIR sensor, these changes in radiations are detected by the
PIR sensor which causes the output of the sensor to go high.

Figure 11.10: working principle of PIR sensor

PIR sensor ranges


Indoor 25 to 20 cm
Outdoor 10 to 150 m

A PIR sensor consists of two main parts:

 A pyroelectric sensor, which you can see in the image below as a round metal with a
rectangular crystal in the center.

 A special lens called a fresnel lens which Focuses the infrared signals on the pyroelectric
sensor.
Figure 11.11: PIR sensor parts

Passive Infrared Sensor (PIR sensors) find their applications in many fields. The PIR sensor is
used to detect motion. Some of the applications of motion detection are automatic lights control
(saves Power, gives more lifetime to the LEDs), Burglar detector/intruder detector - which is a
basic safety mechanism to detect movement in unattended houses. It is also used in fencing. For
examples. pets are not allowed to travel very far from the garden or house.

Figure 11.12: PIR sensor coverage angle


LAB Exercise No 3
Make a project to use PIR sensor and detect the motion also turn On the LED in the presence of
any motion also display the output on the serial monitor of Arduino
Required hardware
 Arduino Uno
 Bread board
 Wires
 PIR sensor (HC-SR501)
 LED
 Resistance 220 ohm

Circuit diagram

Figure 11.13: circuit diagram of lab exercise no 3


CODE
int led = 13; // the pin that the LED is atteched to
int sensor = 2; // the pin that the sensor is atteched to
int state = LOW; // by default, no motion detected
int val = 0; // variable to store the sensor status (value)

void setup() {
pinMode(led, OUTPUT); // initalize LED as an output
pinMode(sensor, INPUT); // initialize sensor as an input
Serial.begin(9600); // initialize serial
}

void loop(){
val = digitalRead(sensor); // read sensor value
if (val == HIGH) { // check if the sensor is HIGH
digitalWrite(led, HIGH); // turn LED ON
delay(100); // delay 100 milliseconds

if (state == LOW) {
Serial.println("Motion detected!");
state = HIGH; // update variable state to HIGH
}
}
else {
digitalWrite(led, LOW); // turn LED OFF
delay(200); // delay 200 milliseconds

if (state == HIGH){
Serial.println("Motion stopped!");
state = LOW; // update variable state to LOW
}
}
}
LAB Exercise No 4
Make a project to interface LCD and PIR sensor with microcontroller and detect the motion also
display the result on the LCD screen

Required hardware
 Arduino uno
 Resistance 220 ohm
 LCD 16 x2
 Breadboard
 Wires

Circuit diagram

Figure 11.14: Circuit diagram of Lab exercise No 4


Code
#include "LiquidCrystal.h" //Library of lcd
LiquidCrystal lcd(9,8,7,6,5,4); //pin of lcd
int val = 0 ;
void setup()
{
Serial.begin(9600);
lcd.begin(16,2);
lcd.setCursor(0,0);
lcd.print(" PIR Sensor ");
pinMode(12,INPUT); // pir sensor output pin connected

}
void loop()
{
val = digitalRead(12); // pir sensor output pin connected
Serial.println(val); // see the value in serial mpnitor in Arduino
IDE
//delay(100);

if(val == 1 )
{
lcd.setCursor(0,1);
lcd.print(" DETECTED ");
}
else
{
lcd.setCursor(0,1);
lcd.print(" NOT DETECTED ");
}
}

PIR sensor interfacing with I2C LCD


PIR connection is as follows:
 The VCC pin of the sensor is connected to the positive railing of the breadboard.
 The GND pin is connected to the negative railing of the breadboard.
 The signal pin is connected to the digital pin 2 of the Arduino board.
Connection with I2 C LCD
The connection of the Arduino is as follows:

 The VCC pin of the LCD is connected to the positive railing of the breadboard.

 The GND pin is connected to the negative railing of the breadboard.


 The SDA or data line is connected to the A4 of the Arduino.

 The SCL or clock line is connected to the A5 of the Arduino.

Code

#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3F, 16, 2); // I2C address 0x3F, 16


column and 2 rows

void setup() {
lcd.init(); // initialize the lcd
pinMode(2,INPUT); // pir sensor output pin connected
lcd.backlight(); // open the backlight

void loop() {

val = digitalRead(2); // pir sensor output pin connected


Serial.println(val); // see the value in serial mpnitor in Arduino IDE
//delay(100);

if(val == 1 )
{
lcd.clear();
lcd.setCursor(0,1);
lcd.print(" DETECTED ");
}
else
{
lcd.clear();
lcd.setCursor(0,1);
lcd.print(" NOT DETECTED ");

}
Review Questions

Question 1
 Solve the LAB Exercise 1
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color
 Explain the working of LAB Exercise 1 with the help of code. Identify the scope of this
project in embedded system

Question 2
 Solve the LAB Exercise 2
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color
 Explain the working of LAB Exercise 2 with the help of code. Identify the scope of this
project in embedded system

Question 3
 Solve the LAB Exercise 3
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color
 Explain the working of LAB Exercise 3 with the help of code. Identify the scope of this
project in embedded system

Question 4
 Solve the LAB Exercise 4
 Develop the code
 Sketch the circuit diagram
 Attached the hardware running picture in color
 Explain the working of LAB Exercise 3 with the help of code. Identify the scope of this
project in embedded system
LAB Assessment

Student Name LAB Rubrics CLO3 , P5, PLO3


Total Marks 10
Registration No Obtained Marks

Teacher Name Syed M Hamedoon

Date Signature
Experiment No. 12
Open Ended Lab
Make a project “Line Follower Robot” by using microcontroller. The project description is
mention below.
1) Explain the project description in your words
2) Identify the required hardware
3) Make circuit diagram
4) Interfacing connection table
5) Attach the photo of built project

Project Description
The line follower robot senses a black line by using a sensor and then sends the signal to Arduino.
Then Arduino drives the motor according to sensors' output. Here in this project, we are using two
IR sensor modules namely the left sensor and the right sensor. When both left and right sensor
senses white then the robot moves forward.
If the left sensor comes on a black line then the robot turn the left side.
If the right sensor sense black line then robot turn right side until both sensors comes at the white
surface. When the white surface comes robot starts moving on forward again.

If both sensors come on the black line, the robot stops.


Experiment No. 13
To Control DC motor using Bluetooth interfacing with microcontroller
Introduction
This lab describes the working of DC motor by using Bluetooth and its interfacing with
microcontroller.
Objectives
 To understand the basic working of DC motor by using Bluetooth module

Outcomes
By the end of this experiment, students will able to understand the microcontroller interfacing
with DC motor using Bluetooth module

Working of Bluetooth (HC-05) module

HC-05 is one of the commonly used Bluetooth devices that uses UART communication protocol.
It is a class-2 Bluetooth module with Serial Port Profile, which can configure as either Master or
Slave. We can use it simply for a serial port replacement to establish a connection between MCU,
PC to your embedded project and etc.
It has multiple pins for the different method which makes it unique as compared to others. The
module normally operates at UART serial communication with TX and RX pins at 9600 baud
rates. However, it can be programmed with AT commands and it supports
9600,19200,38400,57600,115200,230400,460800 baud rates.

Figure 13.1 Bluetooth module (HC-05)


Bluetooth Module (HC-05) Pinout
The HC-05 comes with multiple pins and indicators, which helps to control different operations
and view their states through indicators. This pinout diagram provides indications of all pins.

Figure 13.2: Pins of HC-05

The table below also briefly describes the functionality of each pin.

Table 13.1 Pin description of Bluetooth module

Pin Description

The operating voltage range is 3.3 volts. But I/O pins can withstand voltage of up to 5
VCC volts. Therefore, we can connect 5 volts power source to this pin, and also other pins can
also operate on 5 volts signals such as Tx and Rx signals.

Ground reference of both ESP8266 and HC-05 should be at the same level. Therefore, we
GND
should connect a power supply, HC05, and ESP8266 ground pins to each other.

As discussed earlier, the HC-05 Bluetooth module uses UART communication to transmit
Tx data. This is a transmitter pin. The TX pin will be the data transfer pin of the module in
UART.
This pin is a data receiving the pin in UART communication. It is used to receive data
Rx
from the microcontroller and transmits it through Bluetooth.

The state shows the current state of the Bluetooth. It gives feedback to the controller about
State the connectivity of Bluetooth with another device. This pin has an internal connection
with the onboard LED which shows the working of HC05.

Using an external signal, Enable/Key pin is used to change the HC-05 mode between data
mode and command mode. The HIGH logic input will transfer the device in command
Enable/Key
mode and the LOW logic input will change the mode to data mode. By default, it works in
data mode.

The command and data mode states are changeable through a button present on the
Button
module.

LED This pin shows the working status of module along with the State pin

L293D Motor Driver IC


L293D IC is known as a motor driver. It is a low voltage operating device like other ICs. L293D
provides the continuous bidirectional Direct Current to the Motor. The Polarity of current can
change at any time without affecting the whole IC or any other device in the circuit. L293D has an
internal H-bridge installed for two motors.

H-Bridge is an electrical circuit that enables the load in a bidirectional way. L293D bridge is
controlled by external low voltage signals. It may be small in size, but its power output capacity is
higher than our expectation. It could control any DC motor speed and direction with a voltage
range of 4.5 – 36 Volts. Its diodes also save the controlling device and IC from back EMF.
Figure 13.3 L293D Pin details
The table 13.2 below shows the logic signals required for the appropriate spinning action for
motor A.

Table 13.2 Motor operations

IN1 IN2 Motor Action

1 (HIGH) 1 OFF

1 0 (LOW) Backward

0 1 Forward

0 0 OFF
Why we need a Motor Driver Circuit?
Normal DC motors require a current of more than 250mA. Controlling IC’s on motor drivers like
Atmega16/32, 8051 or any microcontroller chip cannot draw that much current through them
directly at their pinouts. If we directly connect the motors to any IC’s it will burn out due to high
current draw.
Also in terms of Operating Voltage required for driving the Motors with the high speed, we need
a higher level of voltage depending upon motor specifications, so here we need motor driver
circuits. To drive a motor, we just cannot connect it directly to the microcontroller. Why? Because
the Microcontroller will generate signals in the form of HIGH (Vcc = 5v) or LOW (zero). But this
voltage is insufficient to run a motor. That’s why we need to use a Motor Driver.
The most commonly used motor driver IC’s are L293 and L298 series

L298N motor module


This L298N Motor Driver Module is a high power motor driver module for driving DC and Stepper
Motors. This module consists of an L298 motor driver IC and a 78M05 5V regulator. L298N
Module can control up to 4 DC motors, or 2 DC motors with directional and speed control

Figure 13.4: L298N module


Figure 13.4: L298N module pins description

The basic difference between L293D and L298N Motor Driver:

1. L293D Drivers Operates at 4.5V to 36V whereas L298N can be Operates at up to 46V.
2. Maximum 600mA Current can be drawn through both channels of L293D whereas
L298N Motor Driver can draw up to 2A from both channels.
3. L293 is a quadruple motor driver that uses a half-H driver while L298 is a dual full-H
driver, i.e, in L293 all four input-output lines are independent while in L298, a half-H
driver cannot be used independently, only a full H driver has to be used.
4. As L293 output current for each channel is 650mA whereas it is 2A for L298. Hence, the
heat sink is provided in L298 motor drivers.
5. EMFs are provided internally in L293D but must be provided externally in L298.
6. L293D is suitable for small current drawing motors like BO motor, DC geared motors up
to 500 RPM, and small stepper motors which take less current up to 600mA at their
highest torque rating. WhereasL298N has the advantage of higher output current up to 2A
and therefore it is suitable for high torque and high RPM motors like Johnson motors and
high torque DC Geared motors.
LAB Exercise No.1
To control single DC Motor by using Bluetooth module
Required Hardware
 Arduino UNO – read Best Arduino Starter Kits
 1x Bluetooth Module (for example: HC-05 or 06)
 1x Smartphone (any Android will work)
 1x L293D IC
 1x DC motor
 1x Breadboard
 Jumper Cables

Circuit Diagram

Figure 13.5 Circuit diagram of lab exercise No. 1


Two common mistakes
 You need to remove the RX and TX cables when you’re uploading the sketch to your
Arduino.
 Sometimes people connect the TX from the bluetooth module to the TX of the Arduino…
that’s wrong and it won’t work. Make sure you connect it properly, the TX into RX and
the RX into the TX.
Note:
If the HC-05 Bluetooth Module asks for a password, It’s ‘1234’.

Code
Make sure you remove the wires from RX and TX otherwise the code won’t upload
properly!
/*
* Control DC motor with Smartphone via bluetooth

int motorPin1 = 3; // pin 2 on L293D IC


int motorPin2 = 4; // pin 7 on L293D IC
int enablePin = 5; // pin 1 on L293D IC
int state;
int flag=0; //makes sure that the serial only prints once the
state

void setup() {
// sets the pins as outputs:
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(enablePin, OUTPUT);
// sets enablePin high so that motor can turn on:
digitalWrite(enablePin, HIGH);
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

void loop() {
//if some date is sent, reads it and saves in state
if(Serial.available() > 0){
state = Serial.read();
flag=0;
}
// if the state is '0' the DC motor will turn off
if (state == '0') {
digitalWrite(motorPin1, LOW); // set pin 2 on L293D low
digitalWrite(motorPin2, LOW); // set pin 7 on L293D low
if(flag == 0){
Serial.println("Motor: off");
flag=1;
}
}
// if the state is '1' the motor will turn right
else if (state == '1') {
digitalWrite(motorPin1, LOW); // set pin 2 on L293D low
digitalWrite(motorPin2, HIGH); // set pin 7 on L293D high
if(flag == 0){
Serial.println("Motor: right");
flag=1;
}
}
// if the state is '2' the motor will turn left
else if (state == '2') {
digitalWrite(motorPin1, HIGH); // set pin 2 on L293D high
digitalWrite(motorPin2, LOW); // set pin 7 on L293D low
if(flag == 0){
Serial.println("Motor: left");
flag=1;
}
}
}

For the android communication with our bluetooth module we have used the BlueTerm app, It’s
completely free, so you just need to go to “Play store” and download it. Then you just need to
connect your smarthphone with the bluetooth module. Remember to remove the TX and RX
cables.

We have only set 3 commands to control the DC motor:


 ‘0’ – Turns off the DC motor
 ‘1’ – DC motor rotates to right
 ‘2’ – DC motor rotates to left
LAB Exercise No 2
To control 2 DC motor by using L293D and 298N motor module and HC-05 with Arduino

Required Hardware
1. Arduino
2. L283D Motor driver IC
3. 2 DC Motors
4. HC-05 Bluetooth Module
5. Breadboard
6. Connecting Wires

Circuit Diagram

Figure 13.6: Circuit diagram of Lab Exercise No. 2

Pin connection Table


We are using DC gear motors for this project. They require an operating voltage of 3-12V DC
where the recommended operating voltage is 3-6V DC. Connect 5V pin of Arduino with pin 8 of
L293D IC and GND with common ground
L293D IC with Arduino Connections

Then, we have connected the input pins Pin2 (IN1), Pin7 (IN2), Pin10 (IN3) and Pin15 (IN4)
with digital pins of the Arduino UNO. We have used Arduino pin 3, 4, 8 and 9 respectively to
connect with each of the input pins of the motor driver IC.

The enable pins pin1 (ENA) and pin9 (ENB) are connected with the digital PWM pins of the
Arduino UNO board. We have used Arduino Pin 2 to connect with EN1,2 and Arduino Pin 11
with EN3,4.

Each of the motor’s terminal is connected at Pin3 (OUT1), Pin6 (OUT2) for one motor and
Pin11 (OUT3), Pin14 (OUT4) for the second motor respectively.

Connect pin16 of the driver IC with 5V from Arduino.

HC-05 with Arduino Connections

 Connect VCC pin of Bluetooth module to 5 volts Arduino pin. 


 Connect GND to Ground.
 Module Rx to Arduino Tx.
 Module Tx to Arduino Rx.

Go to the Play Store and download the application by the name: S2 Terminal.

Open the application and connect to the Bluetooth module. Write the specified commands and
send it. Bluetooth module receives them and the Arduino performs the operation by controlling
the DC motor’s direction of rotation.

The table below shows the commands that we will send by our mobile on the Bluetooth
application and the response that will be received.

Command sent by mobile Function

1 Motor moves forward

2 Motor turns left

3 Motor stops

4 Motor turns right

5 Motor reverses
Code

int motor1Pin1 = 3; // pin 2 on IC


int motor1Pin2 = 4; // pin 7 on IC
int enable1Pin = 2; // pin 1 on IC
int motor2Pin1 = 8; // pin 10 on IC
int motor2Pin2 = 9; // pin 15 on IC
int enable2Pin = 11; // pin 9 on IC

int state;
int flag = 0;
int stateStop = 0;

void setup() {

// sets the pins as outputs:


pinMode(motor1Pin1, OUTPUT);
pinMode(motor1Pin2, OUTPUT);
pinMode(enable1Pin, OUTPUT);
pinMode(motor2Pin1, OUTPUT);
pinMode(motor2Pin2, OUTPUT);
pinMode(enable2Pin, OUTPUT);

// sets enable1Pin and enable2Pin high so that motor can turn


on:
digitalWrite(enable1Pin, HIGH);
digitalWrite(enable2Pin, HIGH);

// initialize serial communication at 9600 bits per second:


Serial.begin(9600);
}

void loop() {

//Start Serial Communication


if (Serial.available() > 0) {
state = Serial.read();
flag = 0;
}
// if the state is '1' the DC motor will go forward
if (state == '1') {
digitalWrite(motor1Pin1, HIGH);
digitalWrite(motor1Pin2, HIGH);
digitalWrite(motor2Pin1, LOW);
digitalWrite(motor2Pin2, HIGH);

if (flag == 0) {
Serial.println("Go Forward!");
flag = 1;
}
delay(3000);
state = 3;
stateStop = 1;
}

// if the state is '2' the motor will turn left


else if (state == '2') {
digitalWrite(motor1Pin1, HIGH);
digitalWrite(motor1Pin2, LOW);
digitalWrite(motor2Pin1, LOW);
digitalWrite(motor2Pin2, LOW);

if (flag == 0) {
Serial.println("Turn LEFT");
flag = 1;
}
delay(3000);
state = 3;
stateStop = 1;
}

// if the state is '3' the motor will Stop


else if (state == '3' || stateStop == 1) {
digitalWrite(motor1Pin1, LOW);
digitalWrite(motor1Pin2, LOW);
digitalWrite(motor2Pin1, LOW);
digitalWrite(motor2Pin2, LOW);

if (flag == 0) {
Serial.println("STOP!");
flag = 1;
}
stateStop = 0;
}

// if the state is '4' the motor will turn right


else if (state == '4') {
digitalWrite(motor1Pin1, LOW);
digitalWrite(motor1Pin2, LOW);
digitalWrite(motor2Pin1, LOW);
digitalWrite(motor2Pin2, HIGH);

if (flag == 0) {
Serial.println("Turn RIGHT");
flag = 1;
}

delay(3000);
state = 3;
stateStop = 1;
}

// if the state is '5' the motor will Reverse


else if (state == '5') {
digitalWrite(motor1Pin1, LOW);
digitalWrite(motor1Pin2, HIGH);
digitalWrite(motor2Pin1, HIGH);
digitalWrite(motor2Pin2, LOW);

if (flag == 0) {
Serial.println("Reverse!");
flag = 1;
}

delay(3000);
state = 3;
stateStop = 1;
}
}
Circuit diagram

Figure 13.7 Circuit diagram of lab exercise No 2 using L298N

Code
// Hardware used HC-05 and Motor Driver connected with motors
#include <SoftwareSerial.h>
SoftwareSerial BlueTooth(0, 1); // (TXD, RXD) of HC-06
char BT_input; // to store input character received via BT.
int motorPin1 = 4; // pin 4 on L293D IC
int motorPin2 = 5; // pin 5 on L293D IC
int motorPin3 = 6; // pin 6 on L293D IC
int motorPin4 = 7; // pin 7 on L293D IC

void setup()
{
BlueTooth.begin(9600);
Serial.begin(9600);
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(motorPin3, OUTPUT);
pinMode(motorPin4, OUTPUT);
}

void loop()
{
if (BlueTooth.available())
{
BT_input=BlueTooth.read();
if (BT_input=='s')
{
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
Serial.println("Motors are Off");
}
else if (BT_input=='b')
{
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, HIGH);
Serial.println("Motors are rotating left");
}
else if (BT_input=='f')
{
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, LOW);
Serial.println("Motors are rotating right");
}
else if (BT_input=='r')
{
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, HIGH);
Serial.println("First Motor is rotating right & Second is left");
}
else if (BT_input=='l')
{
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, LOW);
Serial.println("First Motor is rotating Left & second is right");
}
}

Bluetooth Mobile app


You may download the Nodemcu MOTOR control App on Playstore

Output
After uploading the code, go to the mobile phone and turn ON bluetooth and pair your phone
with HC-05. For doing this go to Settings->Bluetooth->Scan device->select HC-05 and pair it.
Pass code to pair is ‘1234’.

Than open the app in your mobile phone, click on scan button to connect with HC-05.

So now, If you press forward button both motor start rotating right (CW). If you press backward
button both motors get start rotating left (ACW). If you press the left button first motor move
forward direction and the another motor move backward direction and so on.
If you press the accelerate button, then the movement of your phone control the movement of
motors and the other button will get disabled.

You can also see the rotation of motors on Serial Monitor as well, while controlling them through
app.
Alternate circuit diagram

Alternate code 2nd

int ENA = 10;


int IN1 = 9;
int IN2 = 8;
int IN3 = 7;
int IN4 = 6;
int ENB = 5;

void setup() {
pinMode(ENA, OUTPUT);
pinMode(ENB, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);

digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, LOW);
}

void loop() {
setDirection();
delay(1000);
changeSpeed();
delay(1000);
}

void setDirection() {
analogWrite(ENA, 255);
analogWrite(ENB, 255);

digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
delay(5000);

digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
delay(5000);

digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, LOW);
}

void changeSpeed() {
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);

for (int i = 0; i < 256; i++) {


analogWrite(ENA, i);
analogWrite(ENB, i);
delay(20);
}

for (int i = 255; i >= 0; --i) {


analogWrite(ENA, i);
analogWrite(ENB, i);
delay(20);
}
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, LOW);
}

Download Bluetooth car application Bluetooth RC Car from


https://play.google.com/store/apps/details?id=braulio.calle.bluetoothRCcontroller&pli=1
Review Questions
Question 1
Solve the LAB Exercise 2
1. Develop the code
2. Sketch the circuit diagram
3. Attached the hardware running picture in color
4. Explain the working of LAB Exercise 2 with the help of code. Identify the scope of
this project in embedded system

LAB Assessment

Student Name LAB Rubrics CLO3 , P5, PLO3


Total Marks 10
Registration No Obtained Marks

Teacher Name Syed M Hamedoon

Date Signature
Experiment No. 14
Relay interfacing with microcontroller
Introduction
This lab describes the working of relay and its interfacing with microcontroller. This lab shows
the working of a relay module with an Arduino and a PIR motion sensor.
Objectives
 To understand the basic working of relay by using microcontroller
Outcomes
By the end of this experiment, students will able to understand the microcontroller interfacing
with relay. To control mains voltage with the Arduino using a relay module.
Relay module working
A relay is an electrically operated switch that can be turned on or off, letting the current go through
or not, and can be controlled with low voltages, like the 5V provided by the Arduino pins.
Controlling a relay module with the Arduino is as simple as controlling any other output as we’ll
see later on.

Figure 14.1 Relay module


This relay module has two channels (those blue cubes). There are other models with one, four and
eight channels. This module should be powered with 5V, which is appropriate to use with an
Arduino.
Relay Pin out
The six pins on the left side of the relay module connect high voltage, and the pins on the right
side connect the component that requires low voltage—the Arduino pins

Figure 14.2 Relay module pins

Mains voltage connections

The high-voltage side has two connectors, each with three sockets: common (COM), normally
closed (NC), and normally open (NO).

Figure 14.3 Relay module main voltage connections


 COM: common pin
 NC (Normally Closed): the normally closed configuration is used when you want the
relay to be closed by default, meaning the current is flowing unless you send a signal
from the Arduino to the relay module to open the circuit and stop the current.
 NO (Normally Open): the normally open configuration works the other way around: the
relay is always open, so the circuit is broken unless you send a signal from the Arduino to
close the circuit. 

If you just want to light up a lamp occasionally, it is better to use a normally-open circuit
configuration.

Pin wiring
The low-voltage side has a set of four pins and a set of three pins.

Figure 14.4 Low-voltage side Relay module

The set at the right consists of VCC and GND to power up the module, and input 1 (IN1) and
input 2 (IN2) to control the bottom and top relays, respectively.
The second set of pins consists of GND, VCC, and JD-VCC pins. The JD-VCC pin powers the
electromagnet of the relay

The connections between the relay module and the Arduino are really simple:
 GND: goes to ground
 IN1: controls the first relay (it will be connected to an Arduino digital pin)
 IN2: controls the second relay (it should be connected to an Arduino digital pin if you are
using this second relay. Otherwise, you don’t need to connect it)
 VCC: goes to 5V
LAB Exercise No 1

Controlling a Lamp with a Relay Module and PIR Motion Sensor

In this example, we create a motion sensitive lamp. A lamp lights up for 10 seconds every time
motion is detected. Motion will be detected using a PIR motion sensor. To control the lamp with
mains voltage we’ll use a relay module in normally-open configuration.

Required Hardware

Here’s the needed parts for this example:

 Relay Module
 Arduino UNO – read Best Arduino Starter Kits
 PIR Motion Sensor
 Lamp Cord Set

Circuit Diagram

Figure 14.5: Circuit diagram of Lab Exercise No 1


Connections
The lamp is connected to the relay using a normally open configuration. The Arduino controls
the relay through pin 8 (pin 8 is connected to the relay IN1 pin). Finally, the PIR motion sensor
is connected to pin 2.

Code
// Relay pin is controlled with D8. The active wire is connected to
Normally Closed and common
int relay = 8;
volatile byte relayState = LOW;

// PIR Motion Sensor is connected to D2.


int PIRInterrupt = 2;

// Timer Variables
long lastDebounceTime = 0;
long debounceDelay = 10000;

void setup() {
// Pin for relay module set as output
pinMode(relay, OUTPUT);
digitalWrite(relay, HIGH);
// PIR motion sensor set as an input
pinMode(PIRInterrupt, INPUT);
// Triggers detectMotion function on rising mode to turn the relay
on, if the condition is met
attachInterrupt(digitalPinToInterrupt(PIRInterrupt), detectMotion,
RISING);
// Serial communication for debugging purposes
Serial.begin(9600);
}

void loop() {
// If 10 seconds have passed, the relay is turned off
if((millis() - lastDebounceTime) > debounceDelay && relayState ==
HIGH){
digitalWrite(relay, HIGH);
relayState = LOW;
Serial.println("OFF");
}
delay(50);
}
void detectMotion() {
Serial.println("Motion");
if(relayState == LOW){
digitalWrite(relay, LOW);
}
relayState = HIGH;
Serial.println("ON");
lastDebounceTime = millis();
}

Observations
Controlling a relay module with the Arduino is as simple as controlling an output – you just need
to send HIGH or LOW signals using an Arduino digital pin. With the relay module you can
control almost any AC electronics appliances (not just lamps).
Demonstration
After uploading the code and wiring the circuit, you can test your setup.

When motion is detected, your lamp lights up. If there isn’t motion for 10 seconds, the lamp
turns off.
Review Questions
Question 1
Solve the LAB Exercise No.1
1. Develop the code
2. Sketch the circuit diagram
3. Attached the hardware running picture in color
4. Explain the working with the help of code. Identify the scope of this project in
embedded system

LAB Assessment

Student Name LAB Rubrics CLO3 , P5, PLO3


Total Marks 10
Registration No Obtained Marks

Teacher Name Syed M Hamedoon

Date Signature

You might also like