LAB MANUAL Biomedical Instrumentation W24
LAB MANUAL Biomedical Instrumentation W24
EES04307
Laboratory Manual
Before starting a new lab, you must always read the laboratory manual for that
experiment and the instructor will discuss the experiment with you.
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
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
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:
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
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
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
Mapping of Course Learning Outcomes (CLO) to Program Learning Outcomes (PLO) /Graduate Attributes
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
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 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
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.
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.
Step 1- First start Arduino program then the following figure should appear as
shown in figure 4.2
\
\\\\\
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
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
Equipment / Apparatus
Arduino Kit
DC Power Supply 5 Volt
Digital Multimeter
Breadboard
Resistors 10 Ω to 1kΩ
LED’s
Wires
Schematic Diagram
int LED=13;
void setup ( )
{
pinMode(LED, OUTPUT);
}
void loop ( )
{
digitalWrite (LED, HIGH);
delay(500);
digitalWrite (LED, LOW);
delay(500);
}
After program the code inside Arduino check the status of LED on your
breadboard and fill the table 1.2
Resistor Value:
Time Delay :
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
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
Date Signature
Experiment No. 02
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
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.
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:
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
void setup() {
void loop(){
} else {
}
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.
Microcontroller
Resistor R1 Ω
Resistor R2 Ω
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
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
Date Signature
Experiment No. 03
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
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
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.
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.).
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.
Circuit Diagram
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 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
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
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
Question 2
Question 3
Question 4
LAB Assessment
Date Signature
Experiment No. 04
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
Below truth table gives the information required for driving the common anode seven segments.
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
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
void loop()
switch (COUNT)
digitalWrite(segA, HIGH);
digitalWrite(segB, HIGH);
digitalWrite(segC, LOW);
digitalWrite(segD, HIGH);
digitalWrite(segE, HIGH);
digitalWrite(segF, LOW);
digitalWrite(segG, HIGH);
break;
digitalWrite(segC, HIGH);
digitalWrite(segD, LOW);
digitalWrite(segE, LOW);
digitalWrite(segF, HIGH);
digitalWrite(segG, HIGH);
break;
digitalWrite(segE, HIGH);
digitalWrite(segF, HIGH);
digitalWrite(segG, HIGH);
break;
digitalWrite(segG, HIGH);
break;
break;
if (COUNT<10)
COUNT++;
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
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
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
void loop()
{
{
display_tens(tens);
}
}
//pin1 is just used to deal with pins of the 1st SSD which
displays the tens digit
display_ones(ones);
delay(300);
//I have given a delay of 300 milliseconds. You can put your
own Time!!
}
}
//pin2 is just used to deal with pins of the 2nd SSD which
desplays the ones digit
bitRead()
Description The bitRead command returns the bit value of the bit index
requested
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
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
Date Signature
Experiment No. 05
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
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
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
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);
}
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.
The I2C LCD Display has only four pins. The following is the pinout:
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).
GND GND
VCC 5 Volt
SDA A4
SCL A5
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.
#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...");
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.
Code
#include <LiquidCrystal_I2C.h>
void setup() {
lcd.init();
lcd.clear();
lcd.backlight(); // Make sure backlight is on
void loop() {
}
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
Date Signature
Experiment No. 6
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
Second: This page will appear then scroll down till reaching the following image.
Click on this link to download the
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
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.
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
#include <Keypad.h>
#include "LiquidCrystal.h"
LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);
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
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
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 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.
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.
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
Required Hardware
Arduino Uno
LED’s
Resistors (220 ohm)
Wires
Bread board
Circuit Diagram
Code
int redLED=9;
int greenLED=10;
int blueLED=11;
int brightness=0;
int fade=5;
void setup() {
pinMode(11, OUTPUT);
void loop() {
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
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.
void setup()
{
pinMode(in_2,OUTPUT) ;
}
void loop()
{
digitalWrite(in_1,HIGH) ;
digitalWrite(in_2,LOW) ;
analogWrite(pwm,255) ;
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
Required Hardware
DC motor
Arduino Uno
DC motor Driver (L293D)
Potentiometer (10kohm)
Supply voltage 9 volt
Wires
Circuit Diagram
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
void setup()
pinMode(in_2,OUTPUT) ;
}
void loop()
{
digitalWrite(in_1,HIGH) ;
digitalWrite(in_2,LOW) ;
analogWrite(pwm,255) ;
delay(3000) ;
//For brake
digitalWrite(in_1,HIGH) ;
digitalWrite(in_2,HIGH) ;
delay(1000) ;
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
Date Signature
Experiment No. 8
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.
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
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
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
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:
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
Required hardware
Circuit diagram
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>
void setup() {
// set the speed of the motor to 30 RPMs
stepper.setSpeed(30);
}
void loop() {
// get the sensor value
int val = analogRead(0);
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
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);
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
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
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);
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.
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)
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
Code
include<Servo.h>
Servo s1; // create servo object to control a servo
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>
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
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
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.
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.
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.
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
#define sensorPin A0
void setup() {
Serial.begin(9600);
void loop() {
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println("*C");
}
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
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
Hardware Required
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
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
Output
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>
void setup() {
// Start the LCD and turn on the backlight
lcd.init();
lcd.backlight();
void loop() {
// Get the voltage reading from the TMP36
int reading = analogRead(sensorPin);
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
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
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.
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.
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
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
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
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.
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 = 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
/*
* Ultrasonic Sensor HC-SR04 interfacing with Arduino.
*/
// defining variables
long duration;
int distance;
void setup() {
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
distance= duration*0.034/2;
Serial.print("Distance: ");
Serial.println(distance);
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");
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
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>
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);
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
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
Range Up to 20cm
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.
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.
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
Circuit Diagram
int SensorPin = 2;
int OutputPin = 13;
void setup() {
pinMode(OutputPin, OUTPUT);
pinMode(SensorPin, INPUT);
Serial.begin(9600);
}
void loop() {
int SensorValue = digitalRead(SensorPin);
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
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Set the LCD address to 0x27 or 0x3f for a 16 chars and 2 line display
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);
}
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.
Circuit diagram
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
}
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 ");
}
}
The VCC pin of the LCD is connected to the positive railing of the breadboard.
Code
#include <LiquidCrystal_I2C.h>
void setup() {
lcd.init(); // initialize the lcd
pinMode(2,INPUT); // pir sensor output pin connected
lcd.backlight(); // open the backlight
void loop() {
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
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.
Outcomes
By the end of this experiment, students will able to understand the microcontroller interfacing
with DC motor using Bluetooth 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.
The table below also briefly describes the functionality of each pin.
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
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.
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
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
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
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.
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
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.
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.
3 Motor stops
5 Motor reverses
Code
int state;
int flag = 0;
int stateStop = 0;
void setup() {
void loop() {
if (flag == 0) {
Serial.println("Go Forward!");
flag = 1;
}
delay(3000);
state = 3;
stateStop = 1;
}
if (flag == 0) {
Serial.println("Turn LEFT");
flag = 1;
}
delay(3000);
state = 3;
stateStop = 1;
}
if (flag == 0) {
Serial.println("STOP!");
flag = 1;
}
stateStop = 0;
}
if (flag == 0) {
Serial.println("Turn RIGHT");
flag = 1;
}
delay(3000);
state = 3;
stateStop = 1;
}
if (flag == 0) {
Serial.println("Reverse!");
flag = 1;
}
delay(3000);
state = 3;
stateStop = 1;
}
}
Circuit diagram
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");
}
}
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
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);
LAB Assessment
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.
The high-voltage side has two connectors, each with three sockets: common (COM), normally
closed (NC), and normally open (NO).
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.
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
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
Relay Module
Arduino UNO – read Best Arduino Starter Kits
PIR Motion Sensor
Lamp Cord Set
Circuit Diagram
Code
// Relay pin is controlled with D8. The active wire is connected to
Normally Closed and common
int relay = 8;
volatile byte relayState = LOW;
// 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
Date Signature