SlideShare a Scribd company logo
Department of Electrical Engineering
Faculty of Engineering & Technology
International Islamic University, Islamabad
ET 303 L
Microprocessor and Microcontroller
Lab Manual
Subject Teacher:
Lab Instructor:
Student
Name
Reg.
No.
Section
Prepared by:
Engr. Rashid Farid Chishti
Department of Electrical Engineering.
Faculty of Engineering and Technology.
International Islamic University, Islamabad.
[ii]
Department of Electrical Engineering
Faculty of Engineering & Technology
International Islamic University, Islamabad
ET 303 L
Microprocessor and Microcontroller
Lab Manual
Names of Group Members
Student
Name
Reg.
No.
Student
Name
Reg.
No.
Student
Name
Reg.
No.
Student
Name
Reg.
No.
[iii]
OBJECTIVE
The objective of this lab is to,
 Learn interfacing and programming of AVR based microcontroller.
 Do programming for Arduino boards in C++.
CLO CLO Description DOMAIN PLO
01
Demonstrate the skills to design and analyze
Microprocessor & Microcontroller based designs.
C3 02
02
Apply the concepts of Microprocessors & Microcontroller
to AVR.
P3 01
03
Participate actively in performing the procedure.
A2 09
CLO: Class Learning Outcome.
PLO: Program Learning Outcome.
[iv]
Microprocessor and Microcontroller Lab Rubrics
Name: Reg. No.: Signature: Instructor:
a) PSYCHOMOTOR (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Lab
Lab
1
Lab
2
Lab
3
Lab
4
Lab
5
Lab
6
Lab
7
Lab
8
Lab
9
Lab
10
Lab
11
Lab
12
Lab
13
Lab
14
1
Practical
Implementation/
Arrangement of
Equipment
0 1.25 2.5 3.75 5 Weightage 5 5 5 5 5 5 5 5 5 5 5 5 5 5
Absent
With several
critical errors,
incomplete and
not neat
With few
errors,
incomplete
and not
neat
With some
errors,
complete
but not neat
Without
errors,
complete
and neat
Obtained
2
Use of
Equipment or
Simulation/
Programming
Tool
0 0.5 1 1.5 2 Weightage 2 2 2 2 2 2 2 2 2 2 2 2 2 2
Absent
Limited
competence
Some
competence
Considerable
competence
Competence Obtained
(b) COGNITIVE (To be judged on the copy of experiment submitted)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Lab
Lab
1
Lab
2
Lab
3
Lab
4
Lab
5
Lab
6
Lab
7
Lab
8
Lab
9
Lab
10
Lab
11
Lab
12
Lab
13
Lab
14
3
Algorithm Design
or Data Record,
Analysis and
Evaluation
0 0.25 0.5 0.75 1 Weightage 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Absent Incorrect
Complete
with some
errors
Complete
with few
errors
Complete
and
Accurate
Obtained
(c) AFFECTIVE (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Lab
Lab
1
Lab
2
Lab
3
Lab
4
Lab
5
Lab
6
Lab
7
Lab
8
Lab
9
Lab
10
Lab
11
Lab
12
Lab
13
Lab
14
4
Level of
Participation &
Attitude to
Achieve
Individual/Group
Goals
0 0.5 1 1.5 2 Weightage 2 2 2 2 2 2 2 2 2 2 2 2 2 2
Absent
Rare sensible
interaction
Some
sensible
interaction
Good
sensible
interaction
Encouraging
sensible
interaction
Obtained
5 TOTAL OBTAINED MARKS (Out of 10):
[v]
LIST OF EXPERIMENTS
LAB 1 : I/O PORTS PROGRAMMING & LED INTERFACING WITH ARDUINO 6
LAB 2 : SEVEN SEGMENT DISPLAY INTERFACING WITH ARDUINO 12
LAB 3 : KEYPAD INTERFACING WITH ARDUINO 17
LAB 4 : READING AND WRITING EEPROM IN ARDUINO 22
LAB 5 : LCD INTERFACING WITH ARDUINO 28
LAB 6 : PWM SIGNAL GENERATION WITH ARDUINO 34
LAB 7 : TIMER MODE PROGRAMMING WITH ARDUINO 41
LAB 8 : COUNTER MODE PROGRAMMING WITH ARDUINO 49
LAB 9 : INTERRUPT PROGRAMMING WITH ARDUINO 56
LAB 10 : SERIAL PORT PROGRAMMING WITH ARDUINO 62
LAB 11 : BLUETOOTH PROGRAMMING WITH ARDUINO 68
LAB 12 : ADC PROGRAMMING WITH ARDUINO 76
LAB 13 : SPI PROTOCOL PROGRAMMING WITH ARDUINO 82
LAB 14 : I2C PROTOCOL PROGRAMMING WITH ARDUINO 90
Lab 1: I/O Ports Programming & LED Interfacing with Arduino Page 6
International Islamic University Islamabad
Faculty of Engineering and Technology
Department of Electrical Engineering
MICROPROCESSORS AND MICROCONTROLLER LAB
Lab 1 : I/O Ports Programming & LED Interfacing with Arduino
Name:
Reg. No:
Date of
Experiment:
OBE Rubrics Evaluation
a) PSYCHOMOTOR (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
1
Practical
Implementation/
Arrangement of
Equipment
0 1.25 2.5 3.75 5
Absent
With several
critical errors,
incomplete
and not neat
With few
errors,
incomplete
and not neat
With some
errors,
complete
but not neat
Without
errors,
complete
and neat
2
Use of
Equipment or
Simulation/
Programming Tool
0 0.5 1 1.5 2
Absent
Limited
competence
Some
competence
Considerable
competence
Competence
(b) COGNITIVE (To be judged on the copy of experiment submitted)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
3
Algorithm Design
or Data Record,
Analysis and
Evaluation
0 0.25 0.5 0.75 1
Absent Incorrect
Complete with
some errors
Complete
with few
errors
Complete
and Accurate
(c) AFFECTIVE (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
4
Level of
Participation &
Attitude to Achieve
Individual/Group
Goals
0 0.5 1 1.5 2
Absent
Rare sensible
interaction
Some sensible
interaction
Good
sensible
interaction
Encouraging
sensible
interaction
5 Total Marks Obtained (Out of 10):
Lab 1: I/O Ports Programming & LED Interfacing with Arduino Page 7
Objectives:
 To familiarize the student with the basic operation of the Arduino Uno board, and
Integrated Development Environment (IDE). By the end of the exercise, the student
should be able to know the basic functionalities of the IDE.
 To understand that how to make a port input or output
 First C++ Program to blink LEDs
Arduino Overview:
Arduino is a prototype platform (open-source) based on an easy-to-use hardware
and software. It consists of a circuit board, which can be programed (referred to as a
microcontroller) and a ready-made software called Arduino IDE (Integrated
Development Environment), which is used to write and upload the computer code to
the physical board.
The key features are:
 Arduino boards are able to read analog or digital input signals from different
sensors and turn it into an output such as activating a motor, turning LED on/off,
connect to the cloud and many other actions.
 You can control your board functions by sending a set of instructions to the
microcontroller on the board via Arduino IDE (referred to as uploading software).
Unlike most previous programmable circuit boards, Arduino does not need an extra
piece of hardware (called a programmer) in order to load a new code onto the
board. You can simply use a USB cable.
 Additionally, the Arduino IDE uses a simplified version of C++, making it easier to
learn to program.
 Finally, Arduino provides a standard form factor that breaks the functions of the
microcontroller into a more accessible package
Arduino UNO Component View:
 Analog Input Pins – Pins (A0-A5) that take-in analog values to be converted to
be represented with a number range 0-1023 through a 10-bit Analog to Digital
Converter (ADC).
 ATmega328 Chip – 8-bit microcontroller that processes the sketch you
programmed.
 Built-in LED – in order to gain access or control of this pin, you have to change
the configuration of pin 13 where it is connected to.
 Crystal Oscillator – Clock that has a frequency of 16MHz
 DC Jack – where the power source (AC-to-DC adapter or battery) should be
connected. It is limited to input values between 6-20V but recommended to be
around 7-12V.
 Digital I/O Pins – Input and Output pins (0-13) of which 6 of them (3, 5, 6, 9, 10
and 11) also provide PWM (Pulse Width Modulated) output by using the
analogWrite() function. Pins (0 (RX) and 1 (TX)) are also used to transmit and
receive serial data.
 ICSP Header – Pins for “In-Circuit Serial Programming” which is another method
of programming.
Lab 1: I/O Ports Programming & LED Interfacing with Arduino Page 8
 ON indicator – LED that lights up when the board is connected to a power source.
 Power Pins – pins that can be used to supply a circuit with values VIN (voltage
from DC Jack), 3.3V and 5V.
 Reset Button – a button that is pressed whenever you need to restart the sketch
programmed in the board.
 USB port – allows the user to connect with a USB cable the board to a PC to
upload sketches or provide a voltage supply to the board. This is also used for
serial communication through the serial monitor from the Arduino software.
Arduino Program Structure:
Arduino programs (also called sketches) can be divided in three main parts:
Structure, Values (variables and constants), and Functions. In this session, we will
learn about the Arduino software program, step by step, and how we can write the
program without any syntax or compilation error.
Let us start with the Structure. Software structure consist of two main functions:
 void setup( ) function
 void loop( ) function
Lab 1: I/O Ports Programming & LED Interfacing with Arduino Page 9
 The setup() function is called when a sketch starts. Use it to initialize the variables,
pin modes, start using libraries, etc. The setup function will only run once, after
each power up or reset of the Arduino board.
 After creating a setup() function, which initializes and sets the initial values, the
loop() function does precisely what its name suggests, and loops consecutively,
allowing your program to change and respond. Use it to actively control the Arduino
board
First Arduino Sketch:
Write a program to toggle LED connected to PD1 (Pin No.1) with delay of 500 ms
Solution:
void setup ( )
{
}
void loop ( )
{
}
#define LED 1
void setup( )
{
DDRD = DDRD | (1<<LED); // Set PD1 as output pin
}
void loop( )
{
PORTD = PORTD & ~(1<<LED); // Turn OFF LED
delay(500); // keep it OFF for 500 ms
PORTD = PORTD | (1<<LED); // Turn ON LED
delay(500); // keep it ON for 500 ms
}
Lab 1: I/O Ports Programming & LED Interfacing with Arduino Page 10
Lab Task:
Write a program to blink built-in LED (Pin No.13, PB5) on UNO board at a frequency
of 4Hz with 50% duty cycle.
Lab 1: I/O Ports Programming & LED Interfacing with Arduino Page 11
Lab 1 Task Solution:
Lab 2: Seven Segment Display Interfacing with Arduino Page 12
International Islamic University Islamabad
Faculty of Engineering and Technology
Department of Electrical Engineering
MICROPROCESSORS AND MICROCONTROLLER LAB
Lab 2 : Seven Segment Display Interfacing with Arduino
Name:
Reg. No:
Date of
Experiment:
OBE Rubrics Evaluation
a) PSYCHOMOTOR (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
1
Practical
Implementation/
Arrangement of
Equipment
0 1.25 2.5 3.75 5
Absent
With several
critical errors,
incomplete
and not neat
With few
errors,
incomplete
and not neat
With some
errors,
complete
but not neat
Without
errors,
complete
and neat
2
Use of
Equipment or
Simulation/
Programming Tool
0 0.5 1 1.5 2
Absent
Limited
competence
Some
competence
Considerable
competence
Competence
(b) COGNITIVE (To be judged on the copy of experiment submitted)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
3
Algorithm Design
or Data Record,
Analysis and
Evaluation
0 0.25 0.5 0.75 1
Absent Incorrect
Complete with
some errors
Complete
with few
errors
Complete
and Accurate
(c) AFFECTIVE (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
4
Level of
Participation &
Attitude to Achieve
Individual/Group
Goals
0 0.5 1 1.5 2
Absent
Rare sensible
interaction
Some sensible
interaction
Good
sensible
interaction
Encouraging
sensible
interaction
5 Total Marks Obtained (Out of 10):
Lab 2: Seven Segment Display Interfacing with Arduino Page 13
Objectives:
 7 segment display interfacing and programming.
 To understand the multiplexing technique.
Introduction:
A seven segment display, as its name indicates, is composed of seven elements.
Individually on or off, they can be combined to produce simplified representations of the
numerals. A single LED is used inside one segment to radiate light through it. If cathodes
of all the LEDs are common, this type of display is called common cathode and for
common anode type display, anode of all LEDs are common and connected to the
common pin.
Multiplexing:
Multiplexing is required when we want to interface more than one displays with
microcontroller. If we interface them normally, they will require lots of I/O ports. In
multiplexing, only one display is kept active at a time but we see all of them active. For
multiplexing all the displays are connected in parallel such that if you activate any
segment, say ‘a’ the ‘a’ segment of all displays glows up. But we can switch ON and OFF
the “common” line of the displays with the Microcontroller pins. So if we wish to light
up the ‘a’ segment of display 1 we simply switch on display 1 first by applying ground
level (for common cathode display) at the common pin of the display and then send a
high signal on the I/O pin connected to segment ‘a’ to lit it.
Lab 2: Seven Segment Display Interfacing with Arduino Page 14
No. . g f e d c b a Hex
0
1
2
3
4
5
6
7
8
9
0 0 1 1 1 1 1 1
0 0 0 0 0 1 1 0
0 1 0 1 1 0 1 1
0 1 0 0 1 1 1 1
0 1 1 0 0 1 1 0
0 1 1 0 1 1 0 1
0 1 1 1 1 1 0 1
0 0 0 0 0 1 1 1
0 1 1 1 1 1 1 1
0 1 1 0 1 1 1 1
0x3F
0x06
0x5B
0x4F
0x66
0x6D
0x7D
0x07
0x7F
0x6F
Schematic:
PORTD Pins PD7 PD6 PD5 PD4 PD3 PD2 PD1 PD0
Arduino Pins 7 6 5 4 3 2 1 0
Seven Segment Pins DP G F E D C B A
g
a a
g
Lab 2: Seven Segment Display Interfacing with Arduino Page 15
Sketch for Two Digit 7 Segment Displays: Counting from 00 to 99
Lab Task:
Show hexadecimal numbers from 00 to FF on two seven segment displays
#define SEG0_PIN 8
#define SEG1_PIN 9
byte Count;
byte Seven_Segment[] = {
0x3F, 0x06, 0x5B, 0x4F, 0x66,
0x6D, 0x7D, 0x07, 0x7F, 0x6F
};
void Display(byte No)
{
byte units, tens;
tens = No / 10; // Separate tens from a number
units = No % 10; // Separate units from a number
for (int I = 0 ; I < 20 ; I++) // Show for 2 seconds
{
digitalWrite(SEG1_PIN,LOW); // Turn OFF SEG1
PORTD = Seven_Segment[units]; // Display units on SEG0
digitalWrite(SEG0_PIN,HIGH); // Turn ON SEG0
delay(50);
digitalWrite(SEG0_PIN,LOW); // Turn OFF SEG0
PORTD = Seven_Segment[tens]; // Display tens on SEG1
digitalWrite(SEG1_PIN,HIGH); // Turn ON SEG1 to show tens
delay(50);
}
}
void setup(){
DDRD = 0xFF; // OUPTPUT PORTS FOR SEVEN SEGMENT DISPLAYS
pinMode(SEG0_PIN,OUTPUT); // SELECT LINE(pin# 08) FOR SEG0
pinMode(SEG1_PIN,OUTPUT); // SELECT LINE(pin# 09) FOR SEG1
}
void loop(){
Display(Count++); // Displays two digit value on 7 segments
if(Count > 99)
Count = 0;
}
Lab 2: Seven Segment Display Interfacing with Arduino Page 16
Lab 2 Task Solution:
Lab 3: Keypad Interfacing with Arduino Page 17
International Islamic University Islamabad
Faculty of Engineering and Technology
Department of Electrical Engineering
MICROPROCESSORS AND MICROCONTROLLER LAB
Lab 3 : Keypad Interfacing with Arduino
Name:
Reg. No:
Date of
Experiment:
OBE Rubrics Evaluation
a) PSYCHOMOTOR (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
1
Practical
Implementation/
Arrangement of
Equipment
0 1.25 2.5 3.75 5
Absent
With several
critical errors,
incomplete
and not neat
With few
errors,
incomplete
and not neat
With some
errors,
complete
but not neat
Without
errors,
complete
and neat
2
Use of
Equipment or
Simulation/
Programming Tool
0 0.5 1 1.5 2
Absent
Limited
competence
Some
competence
Considerable
competence
Competence
(b) COGNITIVE (To be judged on the copy of experiment submitted)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
3
Algorithm Design
or Data Record,
Analysis and
Evaluation
0 0.25 0.5 0.75 1
Absent Incorrect
Complete with
some errors
Complete
with few
errors
Complete
and Accurate
(c) AFFECTIVE (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
4
Level of
Participation &
Attitude to Achieve
Individual/Group
Goals
0 0.5 1 1.5 2
Absent
Rare sensible
interaction
Some sensible
interaction
Good
sensible
interaction
Encouraging
sensible
interaction
5 Total Marks Obtained (Out of 10):
Lab 3: Keypad Interfacing with Arduino Page 18
Objectives:
 To interface the keypad with Arduino board
 To write the program for communication between Arduino and keypad.
Keypad Overview:
Keypad is input device which is used to give commands to other devices, from
calculator to computer; input is given through keypad. It is an equipment used in the
different projects where we need to send different commands to perform anything. In
embedded devices one of the essential part is keypad and it is used to interact with the
embedded devices. It is a low cost equipment and easily available in the market. Keypad
has several applications in real life based projects e.g. calculators, mobile phones, ATM
machine, Digital Locks etc. A 4x4 Keypad is shown in the figure given below.
Keypad Pins: 4×4 keypad has total eight (8) pins.
Description of Keypad pins:
Keypad’s each pin is assigned with the different task to perform individually. A 4×4
Keypad’s pins functions are listed in the table provided below.
Keypad Pins
Pin No. Pin Name Pin Description
1 Row Pin Controls all the buttons of 1st row
2 Row Pin Controls all the buttons of 2nd row
3 Row Pin Controls all the buttons of 3rd row
4 Row Pin Controls all the buttons of 4th row
5 Column Pin Controls all the buttons of 1st column
6 Column Pin Controls all the buttons of 2nd column
Lab 3: Keypad Interfacing with Arduino Page 19
7 Column Pin Controls all the buttons of 3rd column
8 Column Pin Controls all the buttons of 4th column
The connections between keypad and Arduino are provided in the figure given below.
Lab 3: Keypad Interfacing with Arduino Page 20
Sketch for Keypad Interfacing:
Summary of Keypad Interfacing
 First of all, we have defined the number of rows and columns of keypad.
 Then we have declared the complete keypad characters in terms of rows and columns.
 After that we have defined the row and column pin of keypad attached to the Arduino
pins.
 Then we have simple read the data sent from the keypad and displayed it on the serial
monitor.
Add Keypad Library:
Before going to programming part first download keypad library from Arduino official
website. we are using Arduino keypad library from Mark Stanley. Download the
keypad.zip and add to Arduino library.
Lab Task:
Interface a 4x3 Keypad on Arduino board and show the pressed key serially on terminal
display. A 4x3 Keypad has following key labels: 1 2 3 4 5 6 7 8 9 * 0 #
#include <Keypad.h>
#define ROWS 4 // My Keypad has four rows
#define COLS 4; // and four columns
// define the symbols on the buttons of the keypads
char Keys[ROWS][COLS] =
{
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6}; // row pinouts of the keypad
byte colPins[COLS] = {5, 4, 3, 2}; // and column pinouts
// initialize an instance of class Keypad
Keypad MyKeypad( makeKeymap(Keys), rowPins, colPins,
ROWS, COLS);
void setup(){
Serial.begin(9600);
}
void loop(){
char Key_Pressed = MyKeypad.getKey();
if (Key_Pressed){
Serial.println(Key_Pressed);
}
}
Lab 3: Keypad Interfacing with Arduino Page 21
Lab 3 Task Solution:
Lab 4: Reading and Writing EEPROM in Arduino Page 22
International Islamic University Islamabad
Faculty of Engineering and Technology
Department of Electrical Engineering
MICROPROCESSORS AND MICROCONTROLLER LAB
Lab 4 : Reading and Writing EEPROM in Arduino
Name:
Reg. No:
Date of
Experiment:
OBE Rubrics Evaluation
a) PSYCHOMOTOR (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
1
Practical
Implementation/
Arrangement of
Equipment
0 1.25 2.5 3.75 5
Absent
With several
critical errors,
incomplete
and not neat
With few
errors,
incomplete
and not neat
With some
errors,
complete
but not neat
Without
errors,
complete
and neat
2
Use of
Equipment or
Simulation/
Programming Tool
0 0.5 1 1.5 2
Absent
Limited
competence
Some
competence
Considerable
competence
Competence
(b) COGNITIVE (To be judged on the copy of experiment submitted)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
3
Algorithm Design
or Data Record,
Analysis and
Evaluation
0 0.25 0.5 0.75 1
Absent Incorrect
Complete with
some errors
Complete
with few
errors
Complete
and Accurate
(c) AFFECTIVE (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
4
Level of
Participation &
Attitude to Achieve
Individual/Group
Goals
0 0.5 1 1.5 2
Absent
Rare sensible
interaction
Some sensible
interaction
Good
sensible
interaction
Encouraging
sensible
interaction
5 Total Marks Obtained (Out of 10):
Lab 4: Reading and Writing EEPROM in Arduino Page 23
Objectives:
 To Write and Read data from EEPROM in Arduino.
Introduction:
When you define a variable in programming, the value of this variable only lasts as
long as the Arduino is on. If you reset or power off the Arduino, It’s value disappears. If
you want to keep this data stored for future use you need to use the Arduino EEPROM.
This stores the variable’s data even when the Arduino resets or the power is turned off.
What is EEPROM?
The microcontroller on the Arduino board (ATMEGA328 in case of Arduino UNO)
has EEPROM (Electrically Erasable Programmable Read-Only Memory). It has 1K Byte
memory that can store data. The data stored in the EEPROM is kept there, even when
you reset or power off the Arduino. Simply, the EEPROM is permanent storage similar
to a hard drive in computers. The EEPROM memory has a specified life of 100,000
write/erase cycles, so you may need to be careful about how often you write to it.
However, reads are unlimited. This means you can read from the EEPROM as many
times as you want without compromising its life expectancy.
To include the EEPROM library:
#include <EEPROM.h>
Write: To write data into the EEPROM, you use the EEPROM.write() function that
takes in two arguments. The first one is the EEPROM location or address where you
want to save the data, and the second is the value we want to save:
EEPROM.write(address, value);
For example, to write 9 on address 0, you’ll have: EEPROM.write(0, 9);
Read: To read a byte from the EEPROM, you use the EEPROM.read() function. This
function takes the address of the byte has an argument. EEPROM.read(address);
For example, to read the byte stored previously in address 0.: EEPROM.read(0);
This would return 9, which is the value stored in that location.
Lab 4: Reading and Writing EEPROM in Arduino Page 24
Update a Value: The EEPROM.update() function is particularly useful. It only writes
on the EEPROM if the value written is different from the one already saved.
As the EEPROM has limited life expectancy due to limited write/erase cycles, using the
EEPROM.update() function instead of the EEPROM.write() saves cycles.
You use this function as follows: EEPROM.update(address, value);
At the moment, we had 9 stored in the address 0. So, if we call: EEPROM.update(0, 9);
It won’t write on the EEPROM again, as the value currently saved is the same we want
to write.
Sketch for EEPROM:
#include <EEPROM.h>
char D3,D2,D1,D0; // variables to store password
int Address = 0x100; // EEPROM Address, it's value can be
// from 0x0 to 0x3FF for 1K Byte EEPROM
void setup() {
Serial.begin (9600);
}
void loop() {
D0 = EEPROM.read(Address); //Read Previous State from EEPROM
D1 = EEPROM.read(Address + 1);
D2 = EEPROM.read(Address + 2);
D3 = EEPROM.read(Address + 3);
Serial.print ("Current Password is [");
Serial.print (D0);
Serial.print (D1);
Serial.print (D2);
Serial.print (D3);
Serial.println ("]");
Serial.println ("Precess C to Change Password" );
while(Serial.available()== 0);
if(Serial.available() > 0 ){
int cmd = Serial.read(); // Send the Character Back
Serial.println (char(cmd));
if( cmd == 'c' || cmd == 'C'){
Serial.print ("Enter 1st Digit:" );
while(Serial.available()== 0);
D0 = Serial.read(); Serial.println (D0);
Lab 4: Reading and Writing EEPROM in Arduino Page 25
Lab Task:
Write a program to store and modify 6-digits password. Turn ON Built in LED if
password is correct and Turn OFF if password is incorrect.
Serial.print ("Enter 2nd Digit:" );
while(Serial.available()== 0);
D1 = Serial.read();
Serial.println (D1);
Serial.print ("Enter 3rd Digit:" );
while(Serial.available()== 0);
D2 = Serial.read();
Serial.println (D2);
Serial.print ("Enter 4th Digit:" );
while(Serial.available()== 0);
D3 = Serial.read();
Serial.println (D3);
EEPROM.update(Address , D0);
EEPROM.update(Address + 1 , D1);
EEPROM.update(Address + 2 , D2);
EEPROM.update(Address + 3 , D3);
Serial.println ("Password has been Changed");
}
}
}
Lab 4: Reading and Writing EEPROM in Arduino Page 26
Lab 4: Reading and Writing EEPROM in Arduino Page 27
Lab 4 Task Solution:
Lab 5: LCD Interfacing with Arduino Page 28
International Islamic University Islamabad
Faculty of Engineering and Technology
Department of Electrical Engineering
MICROPROCESSORS AND MICROCONTROLLER LAB
Lab 5 : LCD Interfacing with Arduino
Name:
Reg. No:
Date of
Experiment:
OBE Rubrics Evaluation
a) PSYCHOMOTOR (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
1
Practical
Implementation/
Arrangement of
Equipment
0 1.25 2.5 3.75 5
Absent
With several
critical errors,
incomplete
and not neat
With few
errors,
incomplete
and not neat
With some
errors,
complete
but not neat
Without
errors,
complete
and neat
2
Use of
Equipment or
Simulation/
Programming Tool
0 0.5 1 1.5 2
Absent
Limited
competence
Some
competence
Considerable
competence
Competence
(b) COGNITIVE (To be judged on the copy of experiment submitted)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
3
Algorithm Design
or Data Record,
Analysis and
Evaluation
0 0.25 0.5 0.75 1
Absent Incorrect
Complete with
some errors
Complete
with few
errors
Complete
and Accurate
(c) AFFECTIVE (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
4
Level of
Participation &
Attitude to Achieve
Individual/Group
Goals
0 0.5 1 1.5 2
Absent
Rare sensible
interaction
Some sensible
interaction
Good
sensible
interaction
Encouraging
sensible
interaction
5 Total Marks Obtained (Out of 10):
Lab 5: LCD Interfacing with Arduino Page 29
Objectives:
 To interface the LCD and program Arduino UNO to show the characters on 16x2
LCD.
Introduction:
A 16 × 2 LCD display is commonly used as a display device in various circuits. This
module is preferred over seven segments as they are economical, easily programmable,
and have no limitation of displaying special and even custom characters. A 16 × 2 LCD
means that it can display 16 characters per row and there are two rows. In this LCD, each
character is displayed in a 5 × 7 pixel matrix. This LCD has two registers: (1) Command
register and (2) Data register.
The command register stores the instructions that are given to the LCD. An
instruction is given to the LCD to do a predefined task such as initializing it, clearing its
screen, setting the cursor position, and controlling the display, and so on. The data
register stores the data to be displayed on the LCD. A 20 × 4 LCD means that it can
display 20 characters per row and there are 4 rows. In this LCD, each character is
displayed in a 5×7 pixel matrix. The pin description 16x2 LCD is shown in Table 7.1.
Figure 7.1:16X2 LCD Module
Lab 5: LCD Interfacing with Arduino Page 30
Table 7.1: 44780 based LCD Pin out
PIN SYMBOL I/O DESCRIPTION
1 VSS - Power supply (GND)
2 VCC - Power supply (+5V) (VDD)
3 VEE - Contrast Settings (0 to 2V) (Vo)
4 RS I 0 = Select command reg. 1 = Select data reg. of LCD
5 R/W I 0 = Write to LCD 1 = Read from LCD
6 E I The Enable (E) line allows access to the display through R/W and RS
lines.
0 = Access to LCD disabled 1 = Access to LCD enabled
7 DB0 I/O Data bit line 0 (LSB)
8 DB1 I/O Data bit line 1
9 DB2 I/O Data bit line 2
10 DB3 I/O Data bit line 3
11 DB4 I/O Data bit line 4
For 4-bit Mode, only these pins
are used as data bits
12 DB5 I/O Data bit line 5
13 DB6 I/O Data bit line 6
14 DB7 I/O Data bit line 7 (MSB)
15 A - Back Light Anode (+5V)
16 K - Back Light Cathode (GND)
Schematic:
Lab 5: LCD Interfacing with Arduino Page 31
LCD Functions:
1. LiquidCrystal()
Description
It creates a variable or object of type LiquidCrystal. The display can be controlled using
4 or 8 data lines. For 4 data lines we omit the pin numbers for D0 to D3 and leave those
lines unconnected. The RW pin can be tied to ground instead of connected to a pin on
the Arduino; if so, omit it from this function's parameters.
Syntax
LiquidCrystal(RS, E, D4, D5, D6, D7)
LiquidCrystal(RS, RW, E, D4, D5, D6, D7)
LiquidCrystal(RS, E, D0, D1, D2, D3, D4, D5, D6, D7)
LiquidCrystal(RS, RW, E, D0, D1, D2, D3, D4, D5, D6, D7)
Parameters
RS: The number of the Arduino pin that is connected to the RS pin on the LCD
RW: The number of the Arduino pin that is connected to the RW pin on the LCD (optional)
E: The number of the Arduino pin that is connected to the enable pin on the LCD
D0, D1, D2, D3, D4, D5, D6, D7: The numbers of the Arduino pins which are connected
to the corresponding data pins on the LCD. D0, D1, D2, and D3 are optional; if omitted,
the LCD will be controlled using only the four data lines (D4, D5, D6, D7).
2. lcd.begin(16, 2); // initialize LCD 16 * 2
3. lcd.print("DEE"); // print a string “DEE” on LCD
4. lcd.setCursor(x, y); // set the cursor of LCD at the desired
// location inwhich x is the number of
// COLUMN and y is the ROW Number.
5. lcd.print(x); // print a x as an integer on the LCD
6. lcd.Clear(); // clear the contents of the LCD
Lab 5: LCD Interfacing with Arduino Page 32
Sketch for LCD Display:
Lab Task:
Write a sketch to display your registration number in first line and your name in
Urdu language using 4 custom characters in second line of LCD.
#include <LiquidCrystal.h>
const int RS = 13, E = 12, D4 = 11, D5 = 10, D6 = 9, D7 = 8;
LiquidCrystal lcd(RS, E, D4, D5, D6, D7);
byte k=0;
byte Shape0[7]={
0b01110,
0b01110,
0b00100,
0b01110,
0b10101,
0b00100,
0b01010, };
byte Shape1[7]={ 0x0E,0x0E,0x15,0xE,0x04,0x04,0x0A};
void setup(){
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
lcd.createChar(0, Shape0); // create a new character
lcd.createChar(1, Shape1); // create a new character
lcd.setCursor(0, 0); // Go to Column 0, Row 0
lcd.print("hello, world!"); // Print a message to the LCD.
}
void loop(){
// set the cursor to column 0, line 1
// note: line 1 is the second row,
// since counting begins with 0
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis() / 1000);
lcd.write(byte(k++%2)); // Show Custom Character 0 and 1
delay(500);
}
Lab 5: LCD Interfacing with Arduino Page 33
Lab 5 Task Solution:
Lab 6: PWM Signal Generation with Arduino Page 34
International Islamic University Islamabad
Faculty of Engineering and Technology
Department of Electrical Engineering
MICROPROCESSORS AND MICROCONTROLLER LAB
Lab 6 : PWM Signal Generation with Arduino
Name:
Reg. No:
Date of
Experiment:
OBE Rubrics Evaluation
a) PSYCHOMOTOR (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
1
Practical
Implementation/
Arrangement of
Equipment
0 1.25 2.5 3.75 5
Absent
With several
critical errors,
incomplete
and not neat
With few
errors,
incomplete
and not neat
With some
errors,
complete
but not neat
Without
errors,
complete
and neat
2
Use of
Equipment or
Simulation/
Programming Tool
0 0.5 1 1.5 2
Absent
Limited
competence
Some
competence
Considerable
competence
Competence
(b) COGNITIVE (To be judged on the copy of experiment submitted)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
3
Algorithm Design
or Data Record,
Analysis and
Evaluation
0 0.25 0.5 0.75 1
Absent Incorrect
Complete with
some errors
Complete
with few
errors
Complete
and Accurate
(c) AFFECTIVE (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
4
Level of
Participation &
Attitude to Achieve
Individual/Group
Goals
0 0.5 1 1.5 2
Absent
Rare sensible
interaction
Some sensible
interaction
Good
sensible
interaction
Encouraging
sensible
interaction
5 Total Marks Obtained (Out of 10):
Lab 6: PWM Signal Generation with Arduino Page 35
Objectives:
 What is PWM and how you can get the PWM output from the digital pins of Arduino
 To program and use the PWM feature of AVR
 To generate a square wave of different duty cycles using PWM feature of AVR
 To control the brightness of LED through programming and then we will control it
manually by adding the potentiometer.
Introduction:
PWM stands for Pulse Width Modulation and it is a technique used in controlling
the brightness of LED, speed control of DC motor, controlling a servo motor or
where you have to get analog output with digital means. The Arduino digital pins either
gives us 5V (when turned HIGH) or 0V (when turned LOW) and the output is a square
wave signal. So if we want to dim a LED, we cannot get the voltage between 0 and 5V
from the digital pin but we can change the ON and OFF time of the signal. If we will
change the ON and OFF time fast enough then the brightness of the led will be changed.
Before going further, let’s discuss some terms associated with PWM.
TON (On Time): It is the time when the signal is high.
TOFF (Off Time): It is the time when the signal is low.
Time Period: It is the sum of on time and off time.
Duty Cycle: It is the percentage of time when the signal was high during the time of
period.
So at 50% duty cycle and 1Hz frequency, the LED will be high for half a second and will
be low for the other half second. If we increase the frequency to 50Hz (50 times ON and
OFF per second), then the led will be seen glowing at half brightness by the human eye.
Lab 6: PWM Signal Generation with Arduino Page 36
Arduino and PWM:
The Arduino IDE has a built in function analogWrite() which can be used to generate
a PWM signal. The frequency of this generated signal for most pins will be about 490Hz
and we can give the value from 0-255 using this function. analogWrite(0) means a signal
of 0% duty cycle. analogWrite(127) means a signal of 50% duty cycle. analogWrite(255)
means a signal of 100% duty cycle. On Arduino UNO, the PWM pins are labeled with
~ sign.
BOARD PWM PINS PWM FREQUENCY
UNO, Nano, Mini 3, 5, 6, 9, 10, 11 490 Hz
(pins 5 and 6: 980 Hz)
Mega 2 - 13, 44 - 46 490 Hz
(pins 4 and 13: 980 Hz)
Leonardo, Micro,
Yún
3, 5, 6, 9, 10, 11,
13
490 Hz
(pins 3 and 11: 980 Hz)
Uno WiFi Rev.2 3, 5, 6, 9, 10 976 Hz
Controlling Brightness of LED through Code:
Connect the positive leg of LED which is the longer leg to the Pin No.11 of Arduino UNO.
Then connect the 220Ω resistor to the negative leg of LED and connect the other end of
resistor to the ground pin of Arduino as shown in Figure 1.
Lab 6: PWM Signal Generation with Arduino Page 37
Figure 1: Circuit Diagram to PWM Implementation
Now write the following code to change the brightness of the LED using PWM.
Arduino Code: PWD Generation
Arduino Code to manually control the Brightness of LED:
An addition to Figure 1, take a 10KΩ potentiometer and connect its left pin to GND
and right pin to 5V of Arduino. and then connect the center pin of potentiometer to the A0
Pin of Arduino as shown in figure 2.
int led_pin = 11; // Initializing LED Pin
int i;
void setup() {
pinMode(led_pin, OUTPUT); // Declare LED pin as output
}
void loop()
{
for( i=0; i<255; i++) // Fading the LED
{
analogWrite(led_pin, i);
delay(10);
}
for( i=255; i>0; i--)
{
analogWrite(led_pin, i);
delay(10);
}
}
Lab 6: PWM Signal Generation with Arduino Page 38
Figure 2: Manually Controlling Brightness of LED
Sketch:
Upload the code in the Arduino IDE and on moving the knob of the potentiometer, the
brightness of the LED will change.
int led_pin = 11; // Initializing LED Pin
int pot_pin = A0; // Initializing LED Pin
int data_10_bit, data_8_bit;
void setup() {
pinMode(led_pin, OUTPUT); // Declare LED pin as output
}
void loop()
{
data_10_bit = analogRead(pot_pin); // Reading from potentiometer
// Mapping the Values between 0 to 255 because we can give
// output from 0-255 using the analogwrite() funtion
data_8_bit = data_10_bit >> 2;
// data_8_bit = map(data_10_bit, 0, 1023, 0, 255);
analogWrite(led_pin, data_8_bit);
delay(10);
}
Lab 6: PWM Signal Generation with Arduino Page 39
Lab Task:
Generate a PWM Signal of frequency 490 Hz on Pin No.9 of Arduino UNO Board.
 Place an LED with 220 Ω resistor on Pin No.9.
 Connect Two Push Buttons on Pin No.2 and Pin No.4. and join their other ends
to Ground.
o Label one button as Up and Other button as Down.
o When we press the Up Button, it should increase the Duty Cycle of PWD
Signal
o When we press the Down Button, it should decrease the Duty Cycle of
PWD Signal.
Lab 6: PWM Signal Generation with Arduino Page 40
Lab 6 Task Solution:
Lab 7: Timer Mode Programming with Arduino Page 41
International Islamic University Islamabad
Faculty of Engineering and Technology
Department of Electrical Engineering
MICROPROCESSORS AND MICROCONTROLLER LAB
Lab 7 : Timer Mode Programming with Arduino
Name:
Reg. No:
Date of
Experiment:
OBE Rubrics Evaluation
a) PSYCHOMOTOR (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
1
Practical
Implementation/
Arrangement of
Equipment
0 1.25 2.5 3.75 5
Absent
With several
critical errors,
incomplete
and not neat
With few
errors,
incomplete
and not neat
With some
errors,
complete
but not neat
Without
errors,
complete
and neat
2
Use of
Equipment or
Simulation/
Programming Tool
0 0.5 1 1.5 2
Absent
Limited
competence
Some
competence
Considerable
competence
Competence
(b) COGNITIVE (To be judged on the copy of experiment submitted)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
3
Algorithm Design
or Data Record,
Analysis and
Evaluation
0 0.25 0.5 0.75 1
Absent Incorrect
Complete with
some errors
Complete
with few
errors
Complete
and Accurate
(c) AFFECTIVE (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
4
Level of
Participation &
Attitude to Achieve
Individual/Group
Goals
0 0.5 1 1.5 2
Absent
Rare sensible
interaction
Some sensible
interaction
Good
sensible
interaction
Encouraging
sensible
interaction
5 Total Marks Obtained (Out of 10):
Lab 7: Timer Mode Programming with Arduino Page 42
Objectives:
 To understand the modes and functionality of timers of ATmega328.
 To program Timer for event counting.
Introduction:
There are counter registers in microcontrollers,
 to generate time delays
 to count an event.
 for waveform generation
 for input capture.
When we connect the external event source to the clock pin of the counter register. This
is counter mode. When we connect the oscillator to the clock pin of the counter. This is
timer mode.
Timers/Counters are essential part of any modern MCU. They are an independent unit
inside a micro-controller. They basically run independently of what instruction CPU is
executing. They are primarily used for the following:
 Internal Timer: As an internal timer the unit, ticks on the oscillator frequency. The
oscillator frequency can be directly feed to the timer or it can be pre-scaled. In this
mode it used generate precise delays. Or as precise time counting machine.
 External Counter: In this mode the unit is used to count events on a specific external
pin on a MCU.
 Pulse width Modulation (PWM) Generator: PWM is used in speed control of motors
and various other applications.
 Input Capture Mode: Input capture mode is used to measure time period and pulse
width of an external frequency.
Arduino UNO has 3 timers and these times count at some frequency derived from the
16MHz system clock:
 Timer0 is an 8-bit timer:
It is used by millis(), delay() and analogWrite() on pins 5 and 6.
 Timer1 is a 16-bit timer:
It is used by analogWrite() functions on pins 9 and 10;
It is also used for driving servos using the Servo library so you can’t use
analogWrite with these pins when using the Servo library.
 Timer2 is an 8-bit timer.
It is used by analogWrite() functions on pins 3 and 11 and the Tone() library
 Clock Divisor: configured to alter the frequency and various counting modes
 Timers can be configured to generate interrupts when they overflow or reach a
specific count
Important Registers and Flags Associated with Timers:
Each timer has following registers associated with it, we can change the Timer behavior
through the timer register:
 TCNTn (Timer/Counter Reg): Upon reset, it has zero value and counts with
each timer clock. We can load/read a value into the TCNT0 register
Lab 7: Timer Mode Programming with Arduino Page 43
 TCCRn (Timer/Counter Control Reg): For setting modes of operation (Timer
/Counter) of Timer
 OCRn (Output Compare Reg): The OCR0A register is used with CTC mode. In CTC
mode timer is incremented with a clock. When contents of TCNT are equal to OCRA,
OCF flag is raised and value of TCNTn is reset to zero
 TOVn (Timer Overflow Flag): When overflow occurs, this flag is raised /set
 OCFn (Output Compare Flag): When contents of TCNT are equal to OCR, OCF flag
(located in TIFR register) is raised and value of TCNTn is reset to zero.
7 6 5 4 3 2 1 0 Bit No.
COM0A1 COM0A0 COM0B1 COM0B0 - -
WGM
01
WGM
00
TCCR0A
R/W R/W R/W R/W R R R/W R/W
0 0 0 0 0 0 0 0 Default
7 6 5 4 3 2 1 0 Bit No.
FOC0A FOC0B - - WGM02 CS02 CS01 CS00 TCCR0B
W W R R R/W R/W R/W R/W
0 0 0 0 0 0 0 0 Default
Clock Source Select
Description
CS02 CS01 CS00
0 0 0 No clock source (Timer/ Counter Stopped)
0 0 1 CLKI/O (No Pre-scaling)
0 1 0 CLKI/O/8 (1:8 Pre-scaling)
0 1 1 CLKI/O/64 (1:64 Pre-scaling)
1 0 0 CLKI/O/256 (1:256 Pre-scaling)
1 0 1 CLKI/O/1024 (1:1024 Pre-scaling)
1 1 0 External clock source on T0 pin. Counting on falling edge
1 1 1 External clock source on T0 pin. Counting on rising edge
Mode WGM02 WGM01 WGM00 Timer / Counter Mode of Operation
0 0 0 0 Normal
1 0 0 1 PWM Phase Correct
2 0 1 0 CTC (Clear Timer on Compare Match)
3 0 1 1 Fast PWM (Pulse Width Modulation)
4 1 0 0 Reserved
5 1 0 1 PWM Phase Correct
6 1 1 0 Reserved
7 1 1 1 Fast PWM
7 6 5 4 3 2 1 0
- - - - - OCF0B OCF0A TOV0 TIFR0
R R R R R R/W R/W R/W
0 0 0 0 0 0 0 0
Lab 7: Timer Mode Programming with Arduino Page 44
Timer Modes:
Normal mode:
In this mode, the content of the timer/counter increments with each clock. It counts
up until it reaches its max of 0xFF. When it rolls over from 0xFF to 0x00, it sets high a
flag bit called TOV0 (Timer0 Overflow).
Steps to program Timer0 in Normal mode:
1. Load the TCNT0 register with the initial count value.
2. Load the value into the TCCR0A and TCCR0B register, indicating which mode is to
be used and the pre-scaler option.
3. When you select the clock source, the timer/counter starts to count, and each tick
causes the content of the timer/counter to increment by 1.
4. Keep monitoring the timer overflow flag (TOV0) to see if it is raised. Get out of the
loop when TOV0 becomes high.
5. Stop the timer by disconnecting the clock source
6. Clear the TOV0 flag for the next round.
7. Go back to Step 1 to load TCNT0 again.
CTC mode:
The OCR0A register is used with CTC mode. In CTC mode timer is incremented
with a clock and it counts until the contents of TCNT0 register becomes equal to the
contents of OCR0A register (compare match occurs); then the timer will be cleared and
the OCF0A flag will be set when the next clock occurs. OCF0A flag is in TIFR register.
The difference between Timer0 and Timer2:
Last two combinations of CS02-00 bits select the rising and falling edge of external
event counter in Timer0. Whereas in Timer2 these two combinations of CS22-20 bits
used to select different options of pre-scaler.
Timer1
Timer 1 is 16-bit timer and following is the register’s details
7 6 5 4 3 2 1 0
COM1A
1
COM1A
0
COM1B
1
COM1B
0
- -
WGM1
1
WGM1
0
TCCR1
A
R/W R/W R/W R/W R R R/W R/W
0 0 0 0 0 0 0 0
7 6 5 4 3 2 1 0
Lab 7: Timer Mode Programming with Arduino Page 45
ICNC1 ICES1 - WGM13
WGM1
2
CS1
2
CS11 CS10
TCCR1
B
R/W R/W R R R/W R/W R/W R/W
0 0 0 0 0 0 0 0
Clock Source Select
Description
CS12 CS11 CS10
0 0 0 No clock source (Timer/ Counter Stopped)
0 0 1 CLKI/O (No Pre-scaling)
0 1 0 CLKI/O/8 (1:8 Pre-scaling)
0 1 1 CLKI/O/64 (1:64 Pre-scaling)
1 0 0 CLKI/O/256 (1:256 Pre-scaling)
1 0 1 CLKI/O/1024 (1:1024 Pre-scaling)
1 1 0 External clock source on T1 pin. Counting on falling edge
1 1 1 External clock source on T1 pin. Counting on rising edge
Mode WGM12 WGM11 WGM10 Timer / Counter Mode of Operation
0 0 0 0 Normal
4 1 0 0 CTC (Clear Timer on Compare Match)
Read Data Sheet for Other Modes
Assuming XTAL = 16 MHz, write a program to generate a delay of 1ms using CTC
and Normal mode.
Pre-
Scaler
Timer Clock Timer Period
(Time of One Count)
Total Counts
None 16 MHz 1/16MHz = 0.0625 µs 1ms / 0.0625 µs = 16,000
8 16 MHz / 8 = 2MHz 1/2MHz = 0.5 µs 1ms / 0.5 µs = 2000
64 16 MHz / 64 = 250KHz 1/250KHz = 4 µs 1ms / 4 µs = 250
256 16 MHz / 256 = 62.5KHz 1/62.5KHz = 16 µs 1ms / 16 µs = 62.5
1024 16 MHz / 1024 = 15.625 KHz 1/15.625 KHz = 64 µs 1ms / 64 µs = 15.625
From the above calculation we can only use the options Pre-scaler = 64 since we cannot use a
decimal point and to wait 250 clocks we should load OCR0A with 250-1 = 249
If we are programming for Normal Mode, then we will write TCNT0 = - 250
Lab 7: Timer Mode Programming with Arduino Page 46
Timer0 Normal Mode Programing
Timer0 CTC Mode Programing
void T0_Delay() {
TCNT0 = -250; // TCNT0 = 6 = 0x06 = -250
TCCR0A = 0x00; // Normal mode
TCCR0B = 0x03; // Run Timer0 with 1:64 Pre-scaler
// wait for TOV0 to roll over
while ((TIFR0&(1<<TOV0))==0);
TCCR0B = 0; // Stop Timer
TIFR0 |= 1<<TOV0; // Clear TOV0
}
void setup(){
DDRB = DDRB | (1<<5) ; // PB5 as output
TIMSK0 &= ~(1<<0); // Disable Timer0 Overflow Interrupt
}
void loop(){
PORTB = PORTB | (1<<5);T0_Delay(); // Turn ON LED for 1 ms
PORTB = PORTB & ~(1<<5);T0_Delay(); // Turn OFF LED for 1 ms
}
// toggle bits of PB5 continuously with 1ms delay using CTC Mode.
void T0_Delay(){
TCNT0 = 0x00; // Start timer from 0x00
OCR0A = 250-1; // initial Value of OCR0A = 249
TCCR0A = 0x02; // CTC mode
TCCR0B = 0x03; // Run Timer0 with 1:64 Pre-scaler
while ((TIFR0 & (1<<OCF0A))== 0); // wait for Compare Match
TCCR0B = 0; // Stop Timer
TIFR0 |= 1<<OCF0A; // Clear OCF0A
}
void setup(){
DDRB = DDRB | (1<<5) ; // PB5 as output
TIMSK0 &= ~(1<<0); // Disable Timer0 Overflow Interrupt
}
void loop(){
PORTB = PORTB | (1<<5);T0_Delay(); // Turn ON LED
PORTB = PORTB & ~(1<<5);T0_Delay(); // Turn OFF LED
}
Lab 7: Timer Mode Programming with Arduino Page 47
Schematic Diagram:
Lab Task:
Using Timer0 write a program to generate a Frequency 39.06 Hz on PB5 using Normal
Mode or CTC Mode.
Lab 7: Timer Mode Programming with Arduino Page 48
Lab 7 Task Solution:
Lab 8: Counter Mode Programming with Arduino Page 49
International Islamic University Islamabad
Faculty of Engineering and Technology
Department of Electrical Engineering
MICROPROCESSORS AND MICROCONTROLLER LAB
Lab 8 : Counter Mode Programming with Arduino
Name:
Reg. No:
Date of
Experiment:
OBE Rubrics Evaluation
a) PSYCHOMOTOR (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
1
Practical
Implementation/
Arrangement of
Equipment
0 1.25 2.5 3.75 5
Absent
With several
critical errors,
incomplete
and not neat
With few
errors,
incomplete
and not neat
With some
errors,
complete
but not neat
Without
errors,
complete
and neat
2
Use of
Equipment or
Simulation/
Programming Tool
0 0.5 1 1.5 2
Absent
Limited
competence
Some
competence
Considerable
competence
Competence
(b) COGNITIVE (To be judged on the copy of experiment submitted)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
3
Algorithm Design
or Data Record,
Analysis and
Evaluation
0 0.25 0.5 0.75 1
Absent Incorrect
Complete with
some errors
Complete
with few
errors
Complete
and Accurate
(c) AFFECTIVE (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
4
Level of
Participation &
Attitude to Achieve
Individual/Group
Goals
0 0.5 1 1.5 2
Absent
Rare sensible
interaction
Some sensible
interaction
Good
sensible
interaction
Encouraging
sensible
interaction
5 Total Marks Obtained (Out of 10):
Lab 8: Counter Mode Programming with Arduino Page 50
Objectives:
 To understand the modes and functionality of timers of ATmega328.
 To program Timer for event counting.
Introduction:
There are counter registers in microcontrollers,
 to generate time delays
 to count an event.
 for waveform generation
 for input capture.
When we connect the external event source to the clock pin of the counter register. This
is counter mode. When we connect the oscillator to the clock pin of the counter. This is
timer mode.
Timers/Counters are essential part of any modern MCU. They are an independent unit
inside a micro-controller. They basically run independently of what instruction CPU is
executing. They are primarily used for the following:
 Internal Timer: As an internal timer the unit, ticks on the oscillator frequency. The
oscillator frequency can be directly feed to the timer or it can be pre-scaled. In this
mode it used generate precise delays. Or as precise time counting machine.
 External Counter: In this mode the unit is used to count events on a specific external
pin on a MCU.
 Pulse width Modulation (PWM) Generator: PWM is used in speed control of motors
and various other applications.
 Input Capture Mode: Input capture mode is used to measure time period and pulse
width of an external frequency.
Arduino UNO has 3 timers and these times count at some frequency derived from the
16MHz system clock:
 Timer0 is an 8-bit timer:
It is used by millis(), delay() and analogWrite() on pins 5 and 6.
 Timer1 is a 16-bit timer:
It is used by analogWrite() functions on pins 9 and 10;
It is also used for driving servos using the Servo library so you can’t use
analogWrite with these pins when using the Servo library.
 Timer2 is an 8-bit timer.
It is used by analogWrite() functions on pins 3 and 11 and the Tone() library
 Clock Divisor: configured to alter the frequency and various counting modes
 Timers can be configured to generate interrupts when they overflow or reach a
specific count
Important Registers and Flags Associated with Timers:
Each timer has following registers associated with it, we can change the Timer behavior
through the timer register:
 TCNTn (Timer/Counter Reg): Upon reset, it has zero value and counts with
each timer clock. We can load/read a value into the TCNT0 register
Lab 8: Counter Mode Programming with Arduino Page 51
 TCCRn (Timer/Counter Control Reg): For setting modes of operation (Timer
/Counter) of Timer
 OCRn (Output Compare Reg): The OCR0A register is used with CTC mode. In CTC
mode timer is incremented with a clock. When contents of TCNT are equal to OCRA,
OCF flag is raised and value of TCNTn is reset to zero
 TOVn (Timer Overflow Flag): When overflow occurs, this flag is raised /set
 OCFn (Output Compare Flag): When contents of TCNT are equal to OCR, OCF flag
(located in TIFR register) is raised and value of TCNTn is reset to zero.
7 6 5 4 3 2 1 0
COM0A1 COM0A0 COM0B1 COM0B0 - -
WGM
01
WGM
00
TCCR0
A
R/W R/W R/W R/W R R R/W R/W
0 0 0 0 0 0 0 0
7 6 5 4 3 2 1 0
FOC0A FOC0B - -
WGM
02
CS
02
CS01 CS00
TCCR0
B
W W R R R/W R/
W
R/W R/W
0 0 0 0 0 0 0 0
Clock Source Select
Description
CS02 CS01 CS00
0 0 0 No clock source (Timer/ Counter Stopped)
0 0 1 CLKI/O (No Pre-scaling)
0 1 0 CLKI/O/8 (1:8 Pre-scaling)
0 1 1 CLKI/O/64 (1:64 Pre-scaling)
1 0 0 CLKI/O/256 (1:256 Pre-scaling)
1 0 1 CLKI/O/1024 (1:1024 Pre-scaling)
1 1 0 External clock source on T0 pin. Counting on falling edge
1 1 1 External clock source on T0 pin. Counting on rising edge
Mode WGM02 WGM01 WGM00 Timer / Counter Mode of Operation
0 0 0 0 Normal
1 0 0 1 PWM Phase Correct
2 0 1 0 CTC (Clear Timer on Compare Match)
3 0 1 1 Fast PWM (Pulse Width Modulation)
4 1 0 0 Reserved
5 1 0 1 PWM Phase Correct
6 1 1 0 Reserved
7 1 1 1 Fast PWM
Lab 8: Counter Mode Programming with Arduino Page 52
7 6 5 4 3 2 1 0
- - - - - OCF0B OCF0A TOV0 TIFR0
R R R R R R/W R/W R/W
0 0 0 0 0 0 0 0
Timer Modes:
Normal mode:
In this mode, the content of the timer/counter increments with each clock. It counts
up until it reaches its max of 0xFF. When it rolls over from 0xFF to 0x00, it sets high a
flag bit called TOV0 (Timer0 Overflow).
Steps to program Timer0 in Normal mode:
8. Load the TCNT0 register with the initial count value.
9. Load the value into the TCCR0A and TCCR0B register, indicating which mode is to
be used and the pre-scaler option.
10.When you select the clock source, the timer/counter starts to count, and each tick
causes the content of the timer/counter to increment by 1.
11.Keep monitoring the timer overflow flag (TOV0) to see if it is raised. Get out of the
loop when TOV0 becomes high.
12.Stop the timer by disconnecting the clock source
13.Clear the TOV0 flag for the next round.
14.Go back to Step 1 to load TCNT0 again.
CTC mode:
The OCR0A register is used with CTC mode. In CTC mode timer is incremented
with a clock and it counts until the contents of TCNT0 register becomes equal to the
contents of OCR0A register (compare match occurs); then the timer will be cleared and
the OCF0A flag will be set when the next clock occurs. OCF0A flag is in TIFR register.
The difference between Timer0 and Timer2:
Last two combinations of CS02-00 bits select the rising and falling edge of external
event counter in Timer0. Whereas in Timer2 these two combinations of CS22-20 bits
used to select different options of pre-scaler.
Timer1
Timer 1 is 16-bit timer and following is the register’s details
7 6 5 4 3 2 1 0
COM1A
1
COM1A
0
COM1B
1
COM1B
0
- -
WGM1
1
WGM1
0
TCCR1
A
R/W R/W R/W R/W R R R/W R/W
Lab 8: Counter Mode Programming with Arduino Page 53
0 0 0 0 0 0 0 0
7 6 5 4 3 2 1 0
ICNC1 ICES1 - WGM13
WGM1
2
CS1
2
CS11 CS10
TCCR1
B
R/W R/W R R R/W R/W R/W R/W
0 0 0 0 0 0 0 0
Clock Source Select
Description
CS12 CS11 CS10
0 0 0 No clock source (Timer/ Counter Stopped)
0 0 1 CLKI/O (No Pre-scaling)
0 1 0 CLKI/O/8 (1:8 Pre-scaling)
0 1 1 CLKI/O/64 (1:64 Pre-scaling)
1 0 0 CLKI/O/256 (1:256 Pre-scaling)
1 0 1 CLKI/O/1024 (1:1024 Pre-scaling)
1 1 0 External clock source on T1 pin. Counting on falling edge
1 1 1 External clock source on T1 pin. Counting on rising edge
Mode WGM12 WGM11 WGM10 Timer / Counter Mode of Operation
0 0 0 0 Normal
4 1 0 0 CTC (Clear Timer on Compare Match)
Read Data Sheet for Other Modes
Schematic Diagram:
Lab 8: Counter Mode Programming with Arduino Page 54
Sketch for Delay and Event Counting (Frequency Checker):
Lab Task:
Heart pulses of a patient, in the form of square wave are reaching at Pin T1 (PD5)
(Arduino PIN No. 5) of Arduino UNO Board. Write a program to measure the current pulse
rate per minute of that patient after each 20 seconds and send this answer via serial port
to Computer.
void setup() {
Serial.begin(9600);
pinMode(5,INPUT_PULLUP); // Set Pin No.5 (T1 Pin) as input
}
void loop(){
TCNT1 = 0x0000; // Start counting from 0
TCCR1A = 0x00; // 16-bit counter, Normal Mode
TCCR1B = 0x06; // Start Counting at
// Falling Edge using T1 pin
// For Rising Edge put 0x07
delay(1000); // delay of One Second
TCCR1B = 0x00; // Stop Counting
Serial.print("Input Frequency = ");
Serial.print(TCNT1);
Serial.print(" Hz ");
Serial.print("Time Period = ");
float tp = 1000.0F / TCNT1;
Serial.print(tp);
Serial.println(" ms");
}
Lab 8: Counter Mode Programming with Arduino Page 55
Lab 8 Task Solution:
Lab No. 9: Interrupt Programming with Arduino Page 56
International Islamic University Islamabad
Faculty of Engineering and Technology
Department of Electrical Engineering
MICROPROCESSORS AND MICROCONTROLLER LAB
Lab 9 : Interrupt Programming with Arduino
Name:
Reg. No:
Date of
Experiment:
OBE Rubrics Evaluation
a) PSYCHOMOTOR (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
1
Practical
Implementation/
Arrangement of
Equipment
0 1.25 2.5 3.75 5
Absent
With several
critical errors,
incomplete
and not neat
With few
errors,
incomplete
and not neat
With some
errors,
complete
but not neat
Without
errors,
complete
and neat
2
Use of
Equipment or
Simulation/
Programming Tool
0 0.5 1 1.5 2
Absent
Limited
competence
Some
competence
Considerable
competence
Competence
(b) COGNITIVE (To be judged on the copy of experiment submitted)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
3
Algorithm Design
or Data Record,
Analysis and
Evaluation
0 0.25 0.5 0.75 1
Absent Incorrect
Complete with
some errors
Complete
with few
errors
Complete
and Accurate
(c) AFFECTIVE (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
4
Level of
Participation &
Attitude to Achieve
Individual/Group
Goals
0 0.5 1 1.5 2
Absent
Rare sensible
interaction
Some sensible
interaction
Good
sensible
interaction
Encouraging
sensible
interaction
5 Total Marks Obtained (Out of 10):
Lab No. 9: Interrupt Programming with Arduino Page 57
Objectives:
 To learn the difference between polling and interrupt based programming.
 To use the timer interrupt.
 To use external hardware interrupt.
Introduction:
There are two methods by which a microcontroller can serve a device.
 Interrupt: In interrupt method, a device sends an interrupt signal to microcontroller.
Upon reception of interrupt, microcontroller stops its working and serves the device.
Program executed after receiving an interrupt is called Interrupt Service Routine
(ISR).
 Polling: In polling, microcontroller continuously monitors the status of device, if the
status is met, microcontroller serves the device. In polling method, microcontroller
can only check single device at a time.
Interrupt Vector Table in ATmega328P:
Sr.No. Interrupt Vector Name Address (in Hex)
1 Reset 0000
2 External Interrupt Request 0 INT0_vect 0002
3 External Interrupt Request 1 INT1_vect 0004
4 Pin Change Interrupt Request 0 PCINT0_vect 0006
5 Pin Change Interrupt Request 1 PCINT1_vect 0008
6 Pin Change Interrupt Request 2 PCINT2_vect 000A
7 Watchdog Time-out Interrupt WDT_vect 000C
8
Timer/Counter2 Compare
Match A
TIMER2_COMPA_vect 000E
9
Timer/Counter2 Compare
Match B
TIMER2_COMPB_vect 0010
10 Timer/Counter2 Overflow TIMER2_OVF_vect 0012
11 Timer/Counter1 Capture Event TIMER1_CAPT_vect 0014
12
Timer/Counter1 Compare
Match A
TIMER1_COMPA_vect 0016
13
Timer/Counter1 Compare
Match B
TIMER1_COMPB_vect 0018
14 Timer/Counter1 Overflow TIMER1_OVF_vect 001A
15
Timer/Counter0 Compare
Match A
TIMER0_COMPA_vect 001C
16
Timer/Counter0 Compare
Match B
TIMER0_COMPB_vect 001E
17 Timer/Counter0 Overflow TIMER0_OVF_vect 0020
18 SPI Serial Transfer Complete SPI_STC_vect 0022
19 USART Rx Complete USART_RX_vect 0024
20 USART Data Register Empty USART_UDRE_vect 0026
21 USART Tx Complete USART_TX_vect 0028
22 ADC Conversion Complete ADC_vect 002A
Lab No. 11: Bluetooth Programming with Arduino Page 58
Sr.No. Interrupt Vector Name Address (in Hex)
23 EEPROM ready EE_READY_vect 002C
24 Analog Comparator ANALOG_COMP_vect 002E
25 Two-wire Serial Interface TWI_vect 0030
26 Store Program Memory Read SPM_READY_vect 0032
The above table shows the interrupt sources and their interrupt vectors for AVR
ATmega328P. Memory locations from 0002 to 0032 locations are reserve for interrupt vectors.
Each interrupt has 2 words (4 bytes) of memory space for its ISR. For example, 0012 to 0013
memory space is set aside for Timer2 Overflow ISR.
Usually ISR cannot fit into 4-bytes memory space. So a JMP instruction is kept at the vector
address from where ISR jumps to another location where rest of the code of ISR can be written.
At the end of each ISR, RETI (Return from Interrupt) instruction is placed which gives the control
back to the location from where it was interrupted.
Steps to enable an Interrupt:
To enable any interrupt of AVR, we need to take the following steps:
a) Bit D7 (I) of SREG (Status Register) must be set in order to enable the global interrupt.
Without enabling global interrupt, no interrupt can happen. This can be done by using SEI
(assembly instruction) or sei(); (C instruction).
b) After enabling global interrupt, by setting the IE (Interrupt Enable) bit of each interrupt, that
specific interrupt can be enabled. For example, to enable Timer0 overflow interrupt, we
need to set TOIE0 (Bit0 of TIMSK0 Register).
When interrupt is executed, Bit D7 of SREG is cleared by the microcontroller to avoid the
occurrence of another interrupt. Moreover, if Timer0 Overflow interrupt is enabled, TOV0 (Timer0
Overflow flag) is automatically cleared when microcontroller jumps to the Timer0 Overflow
Interrupt Vector Table.
TIMER INTERRUPTS:
 Timer Interrupt Flag Registers (TIFRn) holds Overflow flag and Compare Match flag bits
related to timers.
 Timer Interrupt Mask Registers (TIMSKn) hold the different interrupt enable bits related to
timers.
- - - - - OCF0B OCF0A TOV0 TIFR0
TIMSK0 - - - - - OCIE0B OCIE0A TOI0E
- - ICF1 - - OCF1B OCF1A TOV1 TIFR1
TIMSK1 - - ICIE - - OCIE1B OCIE1A TOI1E
- - - - - OCF2B OCF2A TOV2 TIFR2
TIMSK2 - - - - - OCIE2B OCIE2A TOI2E
EXTERNAL HARDWARE INTERRUPTS:
There are two external hardware interrupts are INT0 and INT1 located on pins PD2 and PD3
respectively. These are enabled and disabled by External Interrupt Mask Register (EIMSK)
Lab No. 11: Bluetooth Programming with Arduino Page 59
EIMSK - - - - - - INT1 INT0
INT0 External hardware interrupt request 0 enable
INT1 External hardware interrupt request 1 enable
Schematic:
We can set external interrupt as Edge Triggered or Level Triggered using External Interrupt
Control Register A (EICRA).
EICRA - - - - ISC11 ISC10 ISC01 ISC00
ISCx1 ISCx0
0 0 Low Level Triggered
0 1 Rising and Falling Edge
Triggered
1 0 Falling Edge Triggered
1 0 Rising Edge Triggered
INT1 INT0
Lab No. 11: Bluetooth Programming with Arduino Page 60
Sketch for Timer difference calculator using Two External Interrupts:
Lab Task:
Two IR Sensors at distance of 1 meter are placed on a road. Sensor0 is connected to
INT0 interrupt pin and Sensor1 is connected to INT1 interrupt pin. A moving car crosses
the Sensor0 first and then Sensor1. Calculate the time difference between two sensors
detection and then the speed of that Car in Kilometer per Hour Units. Send these two
answers via serial port to PC.
// Calculates Timer Difference between two External Interrupts
unsigned long t1 = 0;
unsigned long t2 = 0;
unsigned long t3 = 0;
void setup() {
Serial.begin(9600);
DDRD = DDRD & 0b11110011; // Set PD2, PD3 as input pins
PORTD = PORTD | 0b00001100; // Enable Pull Ups on PD2 and PD3
EIMSK = EIMSK | 0b00000011; // Enable external Inter. INT0 INT1
EICRA = 0b00001010; // INT0, INT1 is Falling Edge Trig.
SREG = SREG | (1 << 7); // Enable Global Interrupts
}
void loop(){ }
ISR(INT0_vect) { // ISR for external interrupt 0
t1 = millis(); // Arduino Pin
}
ISR(INT1_vect){ // ISR for external interrupt 1
t2 = millis(); t3 = t2 - t1;
Serial.print("Time Difference = ");
Serial.print(t3);
Serial.println(" mili seconds.");
}
Lab No. 11: Bluetooth Programming with Arduino Page 61
Lab 9 Task Solution:
Lab No. 10: Serial Port Programming with Arduino Page 62
International Islamic University Islamabad
Faculty of Engineering and Technology
Department of Electrical Engineering
MICROPROCESSORS AND MICROCONTROLLER LAB
Lab 10 : Serial Port Programming with Arduino
Name:
Reg. No:
Date of
Experiment:
OBE Rubrics Evaluation
a) PSYCHOMOTOR (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
1
Practical
Implementation/
Arrangement of
Equipment
0 1.25 2.5 3.75 5
Absent
With several
critical errors,
incomplete
and not neat
With few
errors,
incomplete
and not neat
With some
errors,
complete
but not neat
Without
errors,
complete
and neat
2
Use of
Equipment or
Simulation/
Programming Tool
0 0.5 1 1.5 2
Absent
Limited
competence
Some
competence
Considerable
competence
Competence
(b) COGNITIVE (To be judged on the copy of experiment submitted)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
3
Algorithm Design
or Data Record,
Analysis and
Evaluation
0 0.25 0.5 0.75 1
Absent Incorrect
Complete with
some errors
Complete
with few
errors
Complete
and Accurate
(c) AFFECTIVE (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
4
Level of
Participation &
Attitude to Achieve
Individual/Group
Goals
0 0.5 1 1.5 2
Absent
Rare sensible
interaction
Some sensible
interaction
Good
sensible
interaction
Encouraging
sensible
interaction
5 Total Marks Obtained (Out of 10):
Lab No. 10: Serial Port Programming with Arduino Page 63
Objectives:
 To interface the serial port of PC with USART of AVR
 To learn that how to program the USART (Universal Synchronous Asynchronous
Receiver / Transmitter) of AVR to transmit & receive asynchronously
Introduction:
AVR has a built in USART (Universal Synchronous Asynchronous Receiver and
Transmitter). We are using asynchronous communication for serial data transfer.
Baud Rate is the data transfer rate, normally we prefer to use 9600 baud rate. So
USART sends Start Bit first then 8 Data bits and then a Stop Bit as shown below.
Serial Functions:
i. Serial is a serial port object. It is used to access first serial port of Arduino.
ii. Serial.begin(baud) Sets the data rate in bits per second (baud) for serial data
transmission. An optional second argument configures the data, parity, and stop
bits. The default is 8 data bits, no parity and one stop bit. It returns nothing.
 Serial.begin(9600); // opens serial port,
// sets data rate to 9600 bps
 Serial.begin(9600,SERIAL_8N1); // 9600 baud rate, 8-bit data,
// No Parity, 1 Stop Bit
iii. Serial.available()Gets the number of bytes (characters) available for reading from
the serial port. This is data that’s already arrived and stored in the serial receive
buffer (which holds 64 bytes). So it returns the number of bytes available to read.
 if (Serial.available()){
int inByte = Serial.read();
} // if receive buffer has some data then read first byte.
iv. Serial.read()Reads data from serial receive buffer and returns the first byte of
incoming serial data available (or -1 if no data is available)
v. Serial.println(val) Prints data to the serial port as human-readable ASCII text
followed by a carriage return character (ASCII 13, or 'r') and a newline character
(ASCII 10, or 'n'). This command takes the same forms as Serial.print()
Input Argument: val is any data type as input argument.
Return Type: It returns the number of byes written to serial port
int analogValue = 100;
 Serial.println(analogValue); // print as an ASCII-encoded decimal
 Serial.println(analogValue, DEC); // print as an ASCII-encoded decimal
 Serial.println(analogValue, HEX); // print as an ASCII-enc hexadecimal
Lab No. 11: Bluetooth Programming with Arduino Page 64
 Serial.println(analogValue, OCT); // print as an ASCII-encoded octal
 Serial.println(analogValue, BIN); // print as an ASCII-encoded binary
 Serial.println("Hello World"); // prints “Hello Worldrn”
vi. Serial.write() Writes binary data to the serial port. This data is sent as a byte or
series of bytes. Note: to send the characters representing the digits of a number
use the print() function instead.
Syntax:Serial.write(val) Serial.write(str) Serial.write(buf, len)
Parameters :
val: a value to send as a single byte
str: a string to send as a series of bytes
buf: an array to send as a series of bytes
len: the number of bytes to be sent from the array
Returns: it returns size_t, the number of bytes written.
 Serial.write(45); // send a byte with the value 45
 int bytesSent = Serial.write("hello"); // sends the string “hello”
// and returns the length of the string.
Notes and Warnings: Serial transmission is asynchronous in Arduino IDE 1.0.
 If there is enough empty space in the transmit buffer, Serial.write() will return
before any characters are transmitted over serial.
 If the transmit buffer is full then Serial.write() will block until there is enough
space in the buffer.
 To avoid blocking calls to Serial.write(), you can first check the amount of free
space in the transmit buffer using availableForWrite().
Schematic:
Lab No. 11: Bluetooth Programming with Arduino Page 65
Sketch:
Next program turns ON/OFF built in LED based on commands given
in the form of string.
void setup() {
DDRB |= (1<<5); // Set PB5(LED PIN) as Output Pin
PORTB |= 1<<5 ; // Turn OFF Relay Switch
Serial.begin(9600, SERIAL_8N1); // 9600 baud rate, 8 data bit
// No Parity, 1 Stop Bit
}
void loop(){
if (Serial.available()) { // if some bytes have received
int inByte = Serial.read(); // read first byte
switch(inByte) {
case'0': // if received byte is '0' = 0x30
PORTB |= (1<<5); // Turn OFF Relay Switch
Serial.println("0 - Relay Switch is OFF Now");
break;
case'1': // if received byte is '1' = 0x31
PORTB = ~(1<<5); // Turn ON Relay Switch
Serial.println("1 - Relay Switch is ON Now");
break;
case'2': // if received byte is '2' = 0x32
if(PORTB &(1<<5))
Serial.println("2 - Relay Switch Status = OFF");
else
Serial.println("2 - Relay Switch Status = ON");
break;
case'n':
Serial.println("I Got n");
break;
case'r':
Serial.println("I Got r");
break;
default: // if received byte is defferent
Serial.write(inByte);
Serial.println(" - is Unrecognized Command");
}
}
}
Lab No. 11: Bluetooth Programming with Arduino Page 66
Lab Task:
An LED is connected to Arduino Pin No.13(PB5). Write a Program that that receives a
String serially and acts according to following table.
Received String Action to Perform
FAN ON Turns ON Relay Switch
FAN OFF Turns OFF Relay Switch
STATUS Shows message “FAN is ON” or “FAN is OFF” depending on Relay Status
Any other string Shows message “Invalid Command”
String cmd;
String cmd_on = "on", cmd_off = "off", cmd_status = "status";
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
Serial.begin(9600, SERIAL_8N1); // 9600 baud rate, 8 data bit
// No Parity, 1 Stop Bit
}
void loop(){
if (Serial.available()) { // if some bytes have received
cmd = Serial.readString(); // read the whole string
if( cmd == cmd_on){
Serial.println("Turning ON LED");
digitalWrite(LED_BUILTIN, HIGH);
}
else if( cmd == cmd_off){
Serial.println("Tuurning OFF LED");
digitalWrite(LED_BUILTIN, LOW);
}
else if( cmd == cmd_status){
if(digitalRead(LED_BUILTIN))
Serial.println("LED is ON");
else
Serial.println("LED is OFF");
}
else{
Serial.print(cmd);
Serial.println(" Command is Invalid");
}
}
}
Lab No. 11: Bluetooth Programming with Arduino Page 67
Lab 10 Task Solution:
Lab No. 11: Bluetooth Programming with Arduino Page 68
International Islamic University Islamabad
Faculty of Engineering and Technology
Department of Electrical Engineering
MICROPROCESSORS AND MICROCONTROLLER LAB
Lab 11 : Bluetooth Programming with Arduino
Name:
Reg. No:
Date of
Experiment:
OBE Rubrics Evaluation
a) PSYCHOMOTOR (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
1
Practical
Implementation/
Arrangement of
Equipment
0 1.25 2.5 3.75 5
Absent
With several
critical errors,
incomplete
and not neat
With few
errors,
incomplete
and not neat
With some
errors,
complete
but not neat
Without
errors,
complete
and neat
2
Use of
Equipment or
Simulation/
Programming Tool
0 0.5 1 1.5 2
Absent
Limited
competence
Some
competence
Considerable
competence
Competence
(b) COGNITIVE (To be judged on the copy of experiment submitted)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
3
Algorithm Design
or Data Record,
Analysis and
Evaluation
0 0.25 0.5 0.75 1
Absent Incorrect
Complete with
some errors
Complete
with few
errors
Complete
and Accurate
(c) AFFECTIVE (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
4
Level of
Participation &
Attitude to Achieve
Individual/Group
Goals
0 0.5 1 1.5 2
Absent
Rare sensible
interaction
Some sensible
interaction
Good
sensible
interaction
Encouraging
sensible
interaction
5 Total Marks Obtained (Out of 10):
Lab No. 11: Bluetooth Programming with Arduino Page 69
Objectives:
 To interface the Bluetooth Module with USART of AVR
 To communicate with Mobile App “Bluetooth Buddy” using HC-05 / HC-06
Bluetooth Module.
Specifications:
Parameter JDY-31 HC-05 HC-06
Working frequency band 2.4 GHz 2.4 GHz 2.4 GHz
Bluetooth Version V3.0 SPP V2.0+EDR V2.0+EDR
Communication interface UART 3.3V TTL level UART 3.3V TTL level UART 3.3V TTL level
Working voltage 3.6~6V 3.6~3.6V 3.6~6V
Communication level 3.3V 3.3V 3.3V
Transmit power (Max) 8 dBm 6 dBm 6 dBm
Receive sensitivity -97dBm -85dBm -85dBm
Transmission distance 30 meters 10 meters 10 meters
Maximum throughput 128 Kbps 450 Kbps 1350 Kbps
Antenna interface built-in PCB
antenna
built-in PCB
antenna
built-in PCB
antenna
Current in Pairing 4.7mA 30~40 mA 30~40 mA
Communication current 7.3 mA 20 mA 20 mA
Module size 27x13 mm 27x13 mm 27x13 mm
Default Baud Rate 9600 38400 9600
Default Password 1234 1234 1234
Master-slave support Slave Master / Slave Slave
JDY- 31
Lab No. 11: Bluetooth Programming with Arduino Page 70
HC-05 HC-06
HC-05 Connection with Arduino HC-05 Connection with Arduino
It can act as both master and slave It functions only as slave
Continuously Press button on Bluetooth
then Concoct USB Cable with Arduino
and PC. Release Button after two
Seconds Now LED on Bluetooth device
will Switch ON and OFF after two
Seconds it means it is in AT command
mode.
It does not have button. If it not
connected to other Bluetooth device then
it is in AT Command Mode
LED is Fast blinking
 It is searching for Paired Device
LED is Fast blinking
 It is searching for Paired Device
No Blinking
 It is now connected to a paired
device
No Blinking
 It is now connected to a paired
device
Arduino Serial Monitor:
Select 38400 Baud rate and “Both NL &
CR” option
Arduino Serial Monitor:
Select 9600 Baud rate and “No line
ending” option.
Lab No. 11: Bluetooth Programming with Arduino Page 71
Circuit for AT Commands
Circuit for Bluetooth Communication
Lab No. 11: Bluetooth Programming with Arduino Page 72
HC-05 AT Commands
Command Reply Purpose
AT OK Write in all commands in Capital
Letters
AT+VERSION? +VERSION:4.0-
20190815
Firmware version.
AT+ADDR? +ADDR:0019:10:08C65E See MAC Address
AT+NAME? +NAME:HC-05 See Device Name
AT+NAME=LAB OK Change name to LAB
AT+PIN? 1234 Shows Bluetooth Password
AT+PIN=0000 OK Set 0000 as Bluetooth Password
AT+UART? +UART:9600,0,0 What is baud rate
AT+UART=57600,1,0 OK Baud =57600, 1 stop bit, 0 parity
AT+UART=115200,1,
0
OK Baud =115200,1 stop bit,0 parity
Other Baud Rates: 4800, 9600,
19200, 38400, 230400, 230400,
460800, 921600, 1382400
AT+ROLE? 0=Salve, 1=Master
AT+ROLE=0 OK Sets in Slave Mode
AT+ROLE=1 OK Sets in Master Mode
AT+RESET Reset and save changes.
HC-06 AT Commands
Command Reply Purpose
AT OK Write in all commands in Capital Letters
AT+VERSION OKlinvorV1.8 Firmware version.
AT+NAMELAB10 OKsetname Sets the modules name to “LAB10”
AT+PIN1234 OKsetPIN Set the PIN to 1234
AT+BAUD1 OK1200 Sets the baud rate to 1200
AT+BAUD2 OK2400 Sets the baud rate to 2400
AT+BAUD3 OK4800 Sets the baud rate to 4800
AT+BAUD4 OK9600 Sets the baud rate to 9600
AT+BAUD5 OK19200 Sets the baud rate to 19200
AT+BAUD6 OK38400 Sets the baud rate to 38400
AT+BAUD7 OK57600 Sets the baud rate to 57600
AT+BAUD8 OK115200 Sets the baud rate to 115200
AT+BAUD9 OK230400 Sets the baud rate to 230400
AT+BAUDA OK460800 Sets the baud rate to 460800
AT+BAUDB OK921600 Sets the baud rate to 921600
AT+BAUDC OK1382400 Sets the baud rate to 1382400
Lab No. 11: Bluetooth Programming with Arduino Page 73
JDY-31 AT Commands
Command Reply Purpose
AT No Response Write in all commands in Capital
Letters
AT+VERSION +VERSION=JDY-31-
V1.35,Bluetooth V3.0
Firmware version.
AT+LADDR +LADDR=7E2904147447 Shows MAC address
AT+NAMELAB10 +OK Sets the modules name to “LAB10”
AT+PIN1234 +OK Set the PIN to 1234
AT+BAUD1 +OK Sets the baud rate to 1200
AT+BAUD2 +OK Sets the baud rate to 2400
AT+BAUD3 +OK Sets the baud rate to 4800
AT+BAUD4 +OK Sets the baud rate to 9600
AT+BAUD5 +OK Sets the baud rate to 19200
AT+BAUD6 +OK Sets the baud rate to 38400
AT+BAUD7 +OK Sets the baud rate to 57600
AT+BAUD8 +OK Sets the baud rate to 115200
AT+BAUD9 +OK Sets the baud rate to 128000
 JDY-31 is in AT mode by default until a Bluetooth connection is established.
 JDY-31 default rate is 9600 BAUD, 0-stop bits, 0-parity, using both carriage return
and new line ending (rn).
 JDY-31 has NO RESPONSE to an empty AT command. You should, however,
get a response to "AT+VERSION"
 Try other BAUD rates if 9600 does not work.
 Now its LED on Bluetooth device will Switch ON and OFF after 1 Seconds > it
means it is in Searching Mode.
 No Blinking > It is now connected to a paired device
Now go to google play store from your android phone and search “Bluetooth Buddy”.
Download and install this app in your mobile phone. Turn on Bluetooth Search and
Add HC-05 or HC-06 Device to your mobile.
Arduino Sketch for AT Commands
void setup() { }
void loop(){ }
Lab No. 11: Bluetooth Programming with Arduino Page 74
Arduino Sketch for Bluetooth Communication
Lab Task:
Download and install "Bluetooth Buddy” app from google play store to your android
phone. Make two buttons in this app. Pressing “ON” button should turn ON LED and
while pressing OFF Button it should turn OFF LED.
String cmd;
String cmd_on = "on";
String cmd_off = "off";
String cmd_status = "status";
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
Serial.begin(9600, SERIAL_8N1); // 9600 baud rate, 8 data bit
// No Parity, 1 Stop Bit
}
void loop(){
if (Serial.available()) { // if some bytes have received
cmd = Serial.readString(); // read the whole string
if( cmd == cmd_on){
Serial.println("Turning ON LED");
digitalWrite(LED_BUILTIN, HIGH);
}
else if( cmd == cmd_off){
Serial.println("Tuurning OFF LED");
digitalWrite(LED_BUILTIN, LOW);
}
else if( cmd == cmd_status){
if(digitalRead(LED_BUILTIN))
Serial.println("LED is ON");
else
Serial.println("LED is OFF");
}
else{
Serial.print(cmd);
Serial.println(" Command is Invalid");
}
}
}
Lab No. 11: Bluetooth Programming with Arduino Page 75
Lab 11 Task Solution:
Lab No. 12: ADC Programming with Arduino Page 76
International Islamic University Islamabad
Faculty of Engineering and Technology
Department of Electrical Engineering
MICROPROCESSORS AND MICROCONTROLLER LAB
Lab 12 : ADC Programming with Arduino
Name:
Reg. No:
Date of
Experiment:
OBE Rubrics Evaluation
a) PSYCHOMOTOR (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
1
Practical
Implementation/
Arrangement of
Equipment
0 1.25 2.5 3.75 5
Absent
With several
critical errors,
incomplete
and not neat
With few
errors,
incomplete
and not neat
With some
errors,
complete
but not neat
Without
errors,
complete
and neat
2
Use of
Equipment or
Simulation/
Programming Tool
0 0.5 1 1.5 2
Absent
Limited
competence
Some
competence
Considerable
competence
Competence
(b) COGNITIVE (To be judged on the copy of experiment submitted)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
3
Algorithm Design
or Data Record,
Analysis and
Evaluation
0 0.25 0.5 0.75 1
Absent Incorrect
Complete with
some errors
Complete
with few
errors
Complete
and Accurate
(c) AFFECTIVE (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
4
Level of
Participation &
Attitude to Achieve
Individual/Group
Goals
0 0.5 1 1.5 2
Absent
Rare sensible
interaction
Some sensible
interaction
Good
sensible
interaction
Encouraging
sensible
interaction
5 Total Marks Obtained (Out of 10):
Lab No. 12: ADC Programming with Arduino Page 77
Objectives:
 To program and use the ADC feature of ATmega328
 Show 10 bit value of ADC on Serial Port.
Introduction:
ADC is used to convert the analog voltages into digital value. ADC is widely used in
data acquisition so most of the modern microcontrollers have on-chip ADC peripheral.
Arduino UNO has on-chip ADC of 10-bit resolution. It has 6 analog input channels. As
the ADC is 10-bit, so the converted digital output is stored in two 8-bit registers ADCL and
ADCH. Reference voltages for ADC can be connected to AVCC (Analog Vcc), internal
1.1V reference or external AREF pin. Minimum 0V and maximum Vcc can be converted
to a digital value. In ADC, Successive approximation method is used to convert analog
voltage into digital value. This circuitry requires a clock frequency between 50 kHz to 100
kHz.
Important Registers Associated with ADC:
Following registers are associated with the ADC of AVR:
ADCL Has 8 LSBs of converted digital result
ADCH Has 2 MSBs of converted digital result
ADMUX For left / right adjusted result, reference voltage and channel
selection
ADCSRA ADC control and status register
Single ended result can be found from following formula:
𝐴𝐷𝐶 =
𝑉𝑖𝑛 × 1024
𝑉𝑟𝑒𝑓
Where Vin is the voltage on the selected input channel, Vref the selected voltage
reference and ADC is the 10-bit converted digital decimal value.
ADMUX Register:
Bit # 7 6 5 4 3 2 1 0
Bit Name REFS1 REFS0 ADLAR MUX4 MUX3 MUX2 MUX1 MUX0
REF1 REF1 Voltage Reference Selection
0 0 AREF Pin Set Externally
0 1 AVCC Pin Same as VCC
1 0 (Reserved)
1 1 Internal 1.1V Fixed Regardless of VCC value
ADLAR = 0  Right Adjust the Result
ADCH ADCL
0 0 0 0 0 0 ADC9 ADC8 ADC7 ADC6 ADC5 ADC4 ADC3 ADC2 ADC1 ADC0
ADLAR = 1  Left Adjust the Result
ADCH ADCL
ADC9 ADC8 ADC7 ADC6 ADC5 ADC4 ADC3 ADC2 ADC1 ADC0 0 0 0 0 0 0
Lab No. 12: ADC Programming with Arduino Page 78
Analog Channel Selection Bits
MUX3…
0
Input MUX3…0 Input
0000 ADC0 1000 ADC8(1)
0001 ADC1 1001 (Reserved)
0010 ADC2 1010 (Reserved)
0011 ADC3 1011 (Reserved)
0100 ADC4 1100 (Reserved)
0101 ADC5 1101 (Reserved)
0110 ADC6 1110 1.1 V
(VBG)
0111 ADC7 1111 0 V (GND)
Note: 1. For Temperature Sensor.
ADCSRA Register:
Bit # 7 6 5 4 3 2 1 0
Bit Name ADEN ADSC ADATE ADIF ADIE ADPS2 ADPS1 ADPS0
ADEN (Bit 7) ADC Enable:
1 = ADC is enabled 0 = ADC is disabled
ADSC (Bit 6) ADC Start Conversion:
Write this bit to 1 to start each conversion.
ADATE (Bit 5) ADC Auto Trigger Enable:
Auto Triggering of the ADC is enabled when this bit is set to 1.
ADIF (Bit 4) ADC Interrupt Flag: This bit is set when an ADC conversion
completes and the Data Registers are updated.
ADIE (Bit 3) ADC Interrupt Enable: Writing this bit to 1 enables the ADC
Conversion Complete Interrupt.
ADPS2:0 (Bits 2:0) ADC Prescaler Select Bits: These bits determine the
division factor between the XTAL frequency and the input clock to
the ADC
ADPS2 ADPS1 ADPS0 Division Factor
0 0 0 2
0 0 1 2
0 1 0 4
0 1 1 8
1 0 0 16
Lab No. 12: ADC Programming with Arduino Page 79
1 0 1 32
1 1 0 64
1 1 1 128
Schematic:
Sketch:
#define STEP_SIZE 5/1024
int ADC_Read(byte An) {
DDRC = 0x00; // make Port C an input for ADC input
ADCSRA = 0x87; // Enable ADC and select CLK/128
ADMUX = 0x40 | An; // 5V Vref, Select ADCn, right-justified
ADCSRA|=(1<<ADSC); // start conversion
while(( ADCSRA & (1<< ADIF ))==0); // wait for conversion to finish
ADCSRA |= (1<<ADIF); // Clear ADIF Flag
return ADC; // return ADC Value
}
void setup() {
Serial.begin(9600); // use 9600 bits per second
}
void loop() {
int A0 = ADC_Read(0); // Read Channel 0
Serial.print("ADC = ");
Serial.print(A0); // Send ADC Value Serially
Serial.print(" Vin = ");
Serial.println(float(ADC) * STEP_SIZE); // Show input Volts
delay(1000);
}
Lab No. 12: ADC Programming with Arduino Page 80
Lab Task:
An LM35 temperature sensor is connected to ADC A0 Pin. Write a Program to read
analog value of LM35 convert it to Centigrade and Send it to serial port. Use 1.1V Vref
and CLK/128 Prescalar.
Lab No. 12: ADC Programming with Arduino Page 81
Lab 12 Task Solution:
Lab No. 13: SPI Protocol Programming with Arduino Page 82
International Islamic University Islamabad
Faculty of Engineering and Technology
Department of Electrical Engineering
MICROPROCESSORS AND MICROCONTROLLER LAB
Lab 13 : SPI Protocol Programming with Arduino
Name:
Reg. No:
Date of
Experiment:
OBE Rubrics Evaluation
a) PSYCHOMOTOR (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
1
Practical
Implementation/
Arrangement of
Equipment
0 1.25 2.5 3.75 5
Absent
With several
critical errors,
incomplete
and not neat
With few
errors,
incomplete
and not neat
With some
errors,
complete
but not neat
Without
errors,
complete
and neat
2
Use of
Equipment or
Simulation/
Programming Tool
0 0.5 1 1.5 2
Absent
Limited
competence
Some
competence
Considerable
competence
Competence
(b) COGNITIVE (To be judged on the copy of experiment submitted)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
3
Algorithm Design
or Data Record,
Analysis and
Evaluation
0 0.25 0.5 0.75 1
Absent Incorrect
Complete with
some errors
Complete
with few
errors
Complete
and Accurate
(c) AFFECTIVE (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
4
Level of
Participation &
Attitude to Achieve
Individual/Group
Goals
0 0.5 1 1.5 2
Absent
Rare sensible
interaction
Some sensible
interaction
Good
sensible
interaction
Encouraging
sensible
interaction
5 Total Marks Obtained (Out of 10):
Lab No. 13: SPI Protocol Programming with Arduino Page 83
Objective:
 To set up and use the on-chip Serial Peripheral Interface (SPI) of the Arduino Board.
Serial Peripheral Interface (SPI) Overview:
A Serial Peripheral Interface (SPI) bus is a system for serial communication, which
uses up to four conductors, commonly three. One conductor is used for data receiving,
one for data sending, one for synchronization and one alternatively for selecting a device
to communicate with. It is a full duplex connection, which means that the data is sent and
received simultaneously. The maximum baud rate is higher than that in the I2C
communication system.
The SPI allows high-speed synchronous data transfer between the AVR and
peripheral devices or between several AVR devices. On most parts the SPI has a second
purpose where it is used for In System Programming (ISP).
The interconnection between two SPI devices always happens between a master
device and a slave device. Compared to some peripheral devices like sensors, which can
only run in slave mode, the SPI of the AVR can be configured for both master and slave
mode. The mode the AVR is running in is specified by the settings of the master bit
(MSTR) in the SPI control register (SPCR). Special considerations about the SS pin must
be considered for Multi Slave Systems. The master is the active part in this system and
must provide the clock signal a serial data transmission is based on. The slave is not
capable of generating the clock signal and thus cannot get active on its own. The slave
just sends and receives data, if the master generates the necessary clock signal. The
master, however, generates the clock signal only while sending data. That means the
master must send data to the slave to read data from the slave.
SPI uses the following four wires −
1. SCK − This is the serial clock driven by the master.
2. MOSI − This is the master output / slave input driven by the master.
3. MISO − This is the master input / slave output driven by the master.
4. SS − This is the slave-selection wire.
Lab No. 13: SPI Protocol Programming with Arduino Page 84
The following functions are used. You have to include the SPI.h.
i. SPI.begin() − Initializes the SPI bus by setting SCK, MOSI, and SS to outputs,
pulling SCK and MOSI low, and SS high.
ii. SPI.setClockDivider(divider) − To set the SPI clock divider relative to the system
clock. On AVR based boards, the dividers available are 2, 4, 8, 16, 32, 64 or 128.
The default setting is SPI_CLOCK_DIV4, which sets the SPI clock to one-quarter
of the frequency of the system clock (5 Mhz for the boards at 20 MHz).
iii. Divider − It could be (SPI_CLOCK_DIV2, SPI_CLOCK_DIV4, SPI_CLOCK_DIV8,
SPI_CLOCK_DIV16, SPI_CLOCK_DIV32, SPI_CLOCK_DIV64,
SPI_CLOCK_DIV128).
iv. SPI.transfer(val) − SPI transfer is based on a simultaneous send and receive: the
received data is returned in receivedVal.
v. SPI.beginTransaction(SPISettings(speedMaximum, dataOrder, dataMode)) −
speedMaximum is the clock, dataOrder(MSBFIRST or LSBFIRST),
dataMode(SPI_MODE0, SPI_MODE1, SPI_MODE2, or SPI_MODE3).
vi. SPI.attachInterrupt(handler) − Function to be called when a slave device receives
data from the master.
We have four modes of operation in SPI as follows –
a. Mode 0 (the default) − Clock is normally low (CPOL = 0), and the data is sampled on
the transition from low to high (leading edge) (CPHA = 0).
b. Mode 1 − Clock is normally low (CPOL = 0), and the data is sampled on the transition
from high to low (trailing edge) (CPHA = 1).
c. Mode 2 − Clock is normally high (CPOL = 1), and the data is sampled on the transition
from high to low (leading edge) (CPHA = 0).
d. Mode 3 − Clock is normally high (CPOL = 1), and the data is sampled on the transition
from low to high (trailing edge) (CPHA = 1).
CPOL CPHA Data Read and Change Time SPI Mode
0 0 Read on Rising Edge, Changed on a Falling
Edge
0
0 1 Read on Falling Edge, Changed on a Rising
Edge
1
1 0 Read on Falling Edge, Changed on a Rising
Edge
2
1 1 Read on Rising Edge, Changed on a Falling
Edge
3
Lab No. 13: SPI Protocol Programming with Arduino Page 85
AVR Registers
 Control register:
SPCR (SPI Control Register)
 Status Register:
SPSR (SPI Status Register)
 Data Register:
SPDR (SPI Data Register)
SPSR Register:
SPIF WCOL - - - - - SPI2X
SPSR:
 SPIF (SPI Interrupt Flag)
A serial transfer is completed.
The SS pin is driven low in slave mode
WCOL (Write Collision)
SPI2X (Double SPI Speed)
SPCR Register:
SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0
SPCR:
 SPIE (SPI Interrupt Enable)
 SPE (SPI Enable)
 DORD (Data Order)
 MSTR (Master)
 CPOL (Clock Polarity)
 CPHA (Clock Phase)
 SPR1, SPR0 :SPI Clock Rate
SPI2X SPR1 SPR0 SCK Freq.
0 0 0 Fosc/4
0 0 1 Fosc/16
0 1 0 Fosc/64
0 1 1 Fosc/128
1 0 0 Fosc/2
1 0 1 Fosc/8
1 1 0 Fosc/32
1 1 1 Fosc/64
Lab No. 13: SPI Protocol Programming with Arduino Page 86
Now, we will connect two Arduino UNO boards together; one as a master and the other
as a slave.
 (SS) : pin 10
 (MOSI) : pin 11
 (MISO) : pin 12
 (SCK) : pin 13
Programming for SPI Protocol:
Sketch for Master:
#define SCK 5 // Shift Clock is PB5
#define MISO 4 // Master In Slave Out is PB4
#define MOSI 3 // Master Out Slave In is PB3
#define SS 2 // Slave Select is PB2
void SPI_Begin(){
// Set MOSI, SCK and SS as Output Pins
DDRB |= (1<<MOSI) | (1<<SCK) | (1<<SS) ;
DDRB &= ~(1<<MISO); // Set MISO as an Input Pin
// Enable SPI, Master mode, Shift Clock = CLK /16
SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
PORTB &= ~(1<<SS); // Enable Slave Select Pin
}
byte SPI_Transfer(byte data){
SPDR = data; // Start transmission
while(!(SPSR & (1<<SPIF))); // Wait for transmission complete
return SPDR;
}
void setup(){
Serial.begin(9600);
SPI_Begin();
Serial.println ("SPI Master");
}
void loop(){
static byte R, S = 1;
delay(1000); // Call One Sec delay
R = SPI_Transfer(S);
Serial.print ("Sent ");
Serial.print (S,DEC);
Serial.print (" Received ");
Serial.println (R,DEC);
S++;
}
Lab No. 13: SPI Protocol Programming with Arduino Page 87
Sketch for Slave :
#define SCK 5 // Shift Clock is PB5
#define MISO 4 // Master In Slave Out is PB4
#define MOSI 3 // Master Out Slave In is PB3
#define SS 2 // Slave Select is PB2
void SPI_Begin_Slave(){
DDRB |= (1<<MISO); // Set MISO as an Output Pin
// Set MOSI, SCK and SS as Input Pins
DDRB &= ~(1<<MOSI) & ~(1<<SCK) & ~(1<<SS) ;
SPCR = (1<<SPE); // Enable SPI as a Slave Device
}
byte SPI_Transfer(byte data){
SPDR = data;
while(!(SPSR & (1<<SPIF))); // Wait for Reception complete
return SPDR; // return the received data
}
void setup(){
Serial.begin(9600);
SPI_Begin_Slave();
Serial.println ("SPI Slave");
}
void loop(){
static byte R,S = 100;
R = SPI_Transfer(S);
Serial.print ("Sent ");
Serial.print (S,DEC);
Serial.print (" Received ");
Serial.println (R,DEC);
S++;
}
Lab No. 13: SPI Protocol Programming with Arduino Page 88
Schematic Diagram:
Lab Task:
SPI Master unit sends string “SPI is working” to slave unit.
SPI Slave waits for data. SPI Slave receives the string and sends it to the serial terminal.
Lab No. 13: SPI Protocol Programming with Arduino Page 89
Lab 13 Task Solution:
Lab 14: I2C Protocol Programming with Arduino Page 90
International Islamic University Islamabad
Faculty of Engineering and Technology
Department of Electrical Engineering
MICROPROCESSORS AND MICROCONTROLLER LAB
Lab 14 : I2C Protocol Programming with Arduino
Name:
Reg. No:
Date of
Experiment:
OBE Rubrics Evaluation
a) PSYCHOMOTOR (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
1
Practical
Implementation/
Arrangement of
Equipment
0 1.25 2.5 3.75 5
Absent
With several
critical errors,
incomplete
and not neat
With few
errors,
incomplete
and not neat
With some
errors,
complete
but not neat
Without
errors,
complete
and neat
2
Use of
Equipment or
Simulation/
Programming Tool
0 0.5 1 1.5 2
Absent
Limited
competence
Some
competence
Considerable
competence
Competence
(b) COGNITIVE (To be judged on the copy of experiment submitted)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
3
Algorithm Design
or Data Record,
Analysis and
Evaluation
0 0.25 0.5 0.75 1
Absent Incorrect
Complete with
some errors
Complete
with few
errors
Complete
and Accurate
(c) AFFECTIVE (To be judged in the field/lab during experiment)
Sr.
No.
Criteria
Level 1
(0%)
Level 2
(25%)
Level 3
(50%)
Level 4
(75%)
Level 5
(100%)
Marks
Obtained
4
Level of
Participation &
Attitude to Achieve
Individual/Group
Goals
0 0.5 1 1.5 2
Absent
Rare sensible
interaction
Some sensible
interaction
Good
sensible
interaction
Encouraging
sensible
interaction
5 Total Marks Obtained (Out of 10):
Lab 14: I2C Protocol Programming with Arduino Page 91
Objective:
 To program and use the TWI feature of AVR
 To transmit a character from Master and receive at Slave using Arduino
Introduction:
The Two Wire Interface (TWI) protocol allows the systems designer to interconnect up to 128
different devices using only two bi-directional bus lines, one for clock (SCL) and one for data
(SDA). An external pull-up resistor is required to be connected for both the TWI pins to keep the
line in high state when these are not driven by any TWI device. All devices connected to the bus
have individual addresses. In TWI protocol, there are built-in mechanisms to resolve the issues
of bus contention. The ATmega16 TWI includes the following features:
 Simple, powerful and flexible communication interface with only two bus lines
 Master and Slave operation supported
 Device can operate as transmitter and receiver
 7-bit address space allows 128 different slave addresses
 Multi-master arbitration support
 Up to 400 kHz data transfer speed
 Fully programmable slave address with general call support
 Address recognition causes Wake-up when AVR is in Sleep Mode
Following figure show the interconnection of different devices connected to Serial Data (SDA) and
Serial Clock (SCL) pins. If none of device is driving the lines, pull-up resistors will keep the lines
at Vcc potential.
Following figure shows the condition for a valid data:
Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx

More Related Content

Similar to Lab Manual Arduino UNO Microcontrollar.docx

Microcontroller Programming & Hardware Introduction
Microcontroller Programming & Hardware IntroductionMicrocontroller Programming & Hardware Introduction
Microcontroller Programming & Hardware Introduction
Joseph Sanchez
 
Physical prototyping lab1-input_output (2)
Physical prototyping lab1-input_output (2)Physical prototyping lab1-input_output (2)
Physical prototyping lab1-input_output (2)
Tony Olsson.
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
vishal choudhary
 
Arduino: Arduino starter kit
Arduino: Arduino starter kitArduino: Arduino starter kit
Arduino: Arduino starter kit
SANTIAGO PABLO ALBERTO
 
SKAD Electronics Training Manual.pdf
SKAD Electronics Training Manual.pdfSKAD Electronics Training Manual.pdf
SKAD Electronics Training Manual.pdf
KadiriIbrahim2
 
Arduino Programming Basic
Arduino Programming BasicArduino Programming Basic
Arduino programming
Arduino programmingArduino programming
Arduino programming
MdAshrafulAlam47
 
Arduino programming
Arduino programmingArduino programming
Arduino programming
Siji Sunny
 
Rdl esp32 development board trainer kit
Rdl esp32 development board trainer kitRdl esp32 development board trainer kit
Rdl esp32 development board trainer kit
Research Design Lab
 
Arduino IDE
Arduino IDE Arduino IDE
Arduino IDE
Mrunal Deshkar
 
Introduction to Arduino.pptx
Introduction to Arduino.pptxIntroduction to Arduino.pptx
Introduction to Arduino.pptx
Akshat Bijronia
 
Basics of arduino uno
Basics of arduino unoBasics of arduino uno
Basics of arduino uno
Rahat Sood
 
wireless charging of an electrical vechicle 3
wireless charging of an electrical vechicle 3wireless charging of an electrical vechicle 3
wireless charging of an electrical vechicle 3
hari prasad
 
Arduino اردوينو
Arduino اردوينوArduino اردوينو
Arduino اردوينو
salih mahmod
 
Embedded system application
Embedded system applicationEmbedded system application
Embedded system application
Dhruwank Vankawala
 
What is Arduino ?
What is Arduino ?What is Arduino ?
What is Arduino ?
Niket Chandrawanshi
 
Introduction of Arduino Uno
Introduction of Arduino UnoIntroduction of Arduino Uno
Introduction of Arduino Uno
Md. Nahidul Islam
 
Lab 2_ Programming an Arduino.pdf
Lab 2_ Programming an Arduino.pdfLab 2_ Programming an Arduino.pdf
Lab 2_ Programming an Arduino.pdf
ssuser0e9cc4
 
IRJET - Automatic Mechanism for LED Parameters Testing & Checking
IRJET -  	  Automatic Mechanism for LED Parameters Testing & CheckingIRJET -  	  Automatic Mechanism for LED Parameters Testing & Checking
IRJET - Automatic Mechanism for LED Parameters Testing & Checking
IRJET Journal
 
Arduino
ArduinoArduino
Arduino
Jerin John
 

Similar to Lab Manual Arduino UNO Microcontrollar.docx (20)

Microcontroller Programming & Hardware Introduction
Microcontroller Programming & Hardware IntroductionMicrocontroller Programming & Hardware Introduction
Microcontroller Programming & Hardware Introduction
 
Physical prototyping lab1-input_output (2)
Physical prototyping lab1-input_output (2)Physical prototyping lab1-input_output (2)
Physical prototyping lab1-input_output (2)
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Arduino: Arduino starter kit
Arduino: Arduino starter kitArduino: Arduino starter kit
Arduino: Arduino starter kit
 
SKAD Electronics Training Manual.pdf
SKAD Electronics Training Manual.pdfSKAD Electronics Training Manual.pdf
SKAD Electronics Training Manual.pdf
 
Arduino Programming Basic
Arduino Programming BasicArduino Programming Basic
Arduino Programming Basic
 
Arduino programming
Arduino programmingArduino programming
Arduino programming
 
Arduino programming
Arduino programmingArduino programming
Arduino programming
 
Rdl esp32 development board trainer kit
Rdl esp32 development board trainer kitRdl esp32 development board trainer kit
Rdl esp32 development board trainer kit
 
Arduino IDE
Arduino IDE Arduino IDE
Arduino IDE
 
Introduction to Arduino.pptx
Introduction to Arduino.pptxIntroduction to Arduino.pptx
Introduction to Arduino.pptx
 
Basics of arduino uno
Basics of arduino unoBasics of arduino uno
Basics of arduino uno
 
wireless charging of an electrical vechicle 3
wireless charging of an electrical vechicle 3wireless charging of an electrical vechicle 3
wireless charging of an electrical vechicle 3
 
Arduino اردوينو
Arduino اردوينوArduino اردوينو
Arduino اردوينو
 
Embedded system application
Embedded system applicationEmbedded system application
Embedded system application
 
What is Arduino ?
What is Arduino ?What is Arduino ?
What is Arduino ?
 
Introduction of Arduino Uno
Introduction of Arduino UnoIntroduction of Arduino Uno
Introduction of Arduino Uno
 
Lab 2_ Programming an Arduino.pdf
Lab 2_ Programming an Arduino.pdfLab 2_ Programming an Arduino.pdf
Lab 2_ Programming an Arduino.pdf
 
IRJET - Automatic Mechanism for LED Parameters Testing & Checking
IRJET -  	  Automatic Mechanism for LED Parameters Testing & CheckingIRJET -  	  Automatic Mechanism for LED Parameters Testing & Checking
IRJET - Automatic Mechanism for LED Parameters Testing & Checking
 
Arduino
ArduinoArduino
Arduino
 

More from RashidFaridChishti

Object Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docxObject Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docx
RashidFaridChishti
 
Lab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docxLab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docx
RashidFaridChishti
 
Data Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptxData Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptxData Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptxData Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptxData Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptxData Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptxData Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptxData Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptxData Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptxData Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptxData Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptxData Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptxData Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptxData Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptxData Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptxData Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptxData Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptx
RashidFaridChishti
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
RashidFaridChishti
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
RashidFaridChishti
 

More from RashidFaridChishti (20)

Object Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docxObject Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docx
 
Lab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docxLab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docx
 
Data Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptxData Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptx
 
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptxData Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptxData Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptx
 
Data Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptxData Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptx
 
Data Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptxData Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptx
 
Data Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptxData Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptx
 
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptxData Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
 
Data Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptxData Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptx
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptxData Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
 
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptxData Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
 
Data Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptxData Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptx
 
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptxData Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
 
Data Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptxData Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptx
 
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptxData Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
 
Data Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptxData Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptx
 
Data Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptxData Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptx
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
 

Recently uploaded

Welding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdfWelding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdf
AjmalKhan50578
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
harshapolam10
 
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
PriyankaKilaniya
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
UReason
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
Gino153088
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
upoux
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
Anant Corporation
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
shadow0702a
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
RamonNovais6
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
AI for Legal Research with applications, tools
AI for Legal Research with applications, toolsAI for Legal Research with applications, tools
AI for Legal Research with applications, tools
mahaffeycheryld
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
ElakkiaU
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...
Prakhyath Rai
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
Yasser Mahgoub
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
ecqow
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
upoux
 

Recently uploaded (20)

Welding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdfWelding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdf
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
 
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
AI for Legal Research with applications, tools
AI for Legal Research with applications, toolsAI for Legal Research with applications, tools
AI for Legal Research with applications, tools
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
 

Lab Manual Arduino UNO Microcontrollar.docx

  • 1. Department of Electrical Engineering Faculty of Engineering & Technology International Islamic University, Islamabad ET 303 L Microprocessor and Microcontroller Lab Manual Subject Teacher: Lab Instructor: Student Name Reg. No. Section Prepared by: Engr. Rashid Farid Chishti Department of Electrical Engineering. Faculty of Engineering and Technology. International Islamic University, Islamabad.
  • 2. [ii] Department of Electrical Engineering Faculty of Engineering & Technology International Islamic University, Islamabad ET 303 L Microprocessor and Microcontroller Lab Manual Names of Group Members Student Name Reg. No. Student Name Reg. No. Student Name Reg. No. Student Name Reg. No.
  • 3. [iii] OBJECTIVE The objective of this lab is to,  Learn interfacing and programming of AVR based microcontroller.  Do programming for Arduino boards in C++. CLO CLO Description DOMAIN PLO 01 Demonstrate the skills to design and analyze Microprocessor & Microcontroller based designs. C3 02 02 Apply the concepts of Microprocessors & Microcontroller to AVR. P3 01 03 Participate actively in performing the procedure. A2 09 CLO: Class Learning Outcome. PLO: Program Learning Outcome.
  • 4. [iv] Microprocessor and Microcontroller Lab Rubrics Name: Reg. No.: Signature: Instructor: a) PSYCHOMOTOR (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Lab Lab 1 Lab 2 Lab 3 Lab 4 Lab 5 Lab 6 Lab 7 Lab 8 Lab 9 Lab 10 Lab 11 Lab 12 Lab 13 Lab 14 1 Practical Implementation/ Arrangement of Equipment 0 1.25 2.5 3.75 5 Weightage 5 5 5 5 5 5 5 5 5 5 5 5 5 5 Absent With several critical errors, incomplete and not neat With few errors, incomplete and not neat With some errors, complete but not neat Without errors, complete and neat Obtained 2 Use of Equipment or Simulation/ Programming Tool 0 0.5 1 1.5 2 Weightage 2 2 2 2 2 2 2 2 2 2 2 2 2 2 Absent Limited competence Some competence Considerable competence Competence Obtained (b) COGNITIVE (To be judged on the copy of experiment submitted) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Lab Lab 1 Lab 2 Lab 3 Lab 4 Lab 5 Lab 6 Lab 7 Lab 8 Lab 9 Lab 10 Lab 11 Lab 12 Lab 13 Lab 14 3 Algorithm Design or Data Record, Analysis and Evaluation 0 0.25 0.5 0.75 1 Weightage 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Absent Incorrect Complete with some errors Complete with few errors Complete and Accurate Obtained (c) AFFECTIVE (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Lab Lab 1 Lab 2 Lab 3 Lab 4 Lab 5 Lab 6 Lab 7 Lab 8 Lab 9 Lab 10 Lab 11 Lab 12 Lab 13 Lab 14 4 Level of Participation & Attitude to Achieve Individual/Group Goals 0 0.5 1 1.5 2 Weightage 2 2 2 2 2 2 2 2 2 2 2 2 2 2 Absent Rare sensible interaction Some sensible interaction Good sensible interaction Encouraging sensible interaction Obtained 5 TOTAL OBTAINED MARKS (Out of 10):
  • 5. [v] LIST OF EXPERIMENTS LAB 1 : I/O PORTS PROGRAMMING & LED INTERFACING WITH ARDUINO 6 LAB 2 : SEVEN SEGMENT DISPLAY INTERFACING WITH ARDUINO 12 LAB 3 : KEYPAD INTERFACING WITH ARDUINO 17 LAB 4 : READING AND WRITING EEPROM IN ARDUINO 22 LAB 5 : LCD INTERFACING WITH ARDUINO 28 LAB 6 : PWM SIGNAL GENERATION WITH ARDUINO 34 LAB 7 : TIMER MODE PROGRAMMING WITH ARDUINO 41 LAB 8 : COUNTER MODE PROGRAMMING WITH ARDUINO 49 LAB 9 : INTERRUPT PROGRAMMING WITH ARDUINO 56 LAB 10 : SERIAL PORT PROGRAMMING WITH ARDUINO 62 LAB 11 : BLUETOOTH PROGRAMMING WITH ARDUINO 68 LAB 12 : ADC PROGRAMMING WITH ARDUINO 76 LAB 13 : SPI PROTOCOL PROGRAMMING WITH ARDUINO 82 LAB 14 : I2C PROTOCOL PROGRAMMING WITH ARDUINO 90
  • 6. Lab 1: I/O Ports Programming & LED Interfacing with Arduino Page 6 International Islamic University Islamabad Faculty of Engineering and Technology Department of Electrical Engineering MICROPROCESSORS AND MICROCONTROLLER LAB Lab 1 : I/O Ports Programming & LED Interfacing with Arduino Name: Reg. No: Date of Experiment: OBE Rubrics Evaluation a) PSYCHOMOTOR (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 1 Practical Implementation/ Arrangement of Equipment 0 1.25 2.5 3.75 5 Absent With several critical errors, incomplete and not neat With few errors, incomplete and not neat With some errors, complete but not neat Without errors, complete and neat 2 Use of Equipment or Simulation/ Programming Tool 0 0.5 1 1.5 2 Absent Limited competence Some competence Considerable competence Competence (b) COGNITIVE (To be judged on the copy of experiment submitted) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 3 Algorithm Design or Data Record, Analysis and Evaluation 0 0.25 0.5 0.75 1 Absent Incorrect Complete with some errors Complete with few errors Complete and Accurate (c) AFFECTIVE (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 4 Level of Participation & Attitude to Achieve Individual/Group Goals 0 0.5 1 1.5 2 Absent Rare sensible interaction Some sensible interaction Good sensible interaction Encouraging sensible interaction 5 Total Marks Obtained (Out of 10):
  • 7. Lab 1: I/O Ports Programming & LED Interfacing with Arduino Page 7 Objectives:  To familiarize the student with the basic operation of the Arduino Uno board, and Integrated Development Environment (IDE). By the end of the exercise, the student should be able to know the basic functionalities of the IDE.  To understand that how to make a port input or output  First C++ Program to blink LEDs Arduino Overview: Arduino is a prototype platform (open-source) based on an easy-to-use hardware and software. It consists of a circuit board, which can be programed (referred to as a microcontroller) and a ready-made software called Arduino IDE (Integrated Development Environment), which is used to write and upload the computer code to the physical board. The key features are:  Arduino boards are able to read analog or digital input signals from different sensors and turn it into an output such as activating a motor, turning LED on/off, connect to the cloud and many other actions.  You can control your board functions by sending a set of instructions to the microcontroller on the board via Arduino IDE (referred to as uploading software). Unlike most previous programmable circuit boards, Arduino does not need an extra piece of hardware (called a programmer) in order to load a new code onto the board. You can simply use a USB cable.  Additionally, the Arduino IDE uses a simplified version of C++, making it easier to learn to program.  Finally, Arduino provides a standard form factor that breaks the functions of the microcontroller into a more accessible package Arduino UNO Component View:  Analog Input Pins – Pins (A0-A5) that take-in analog values to be converted to be represented with a number range 0-1023 through a 10-bit Analog to Digital Converter (ADC).  ATmega328 Chip – 8-bit microcontroller that processes the sketch you programmed.  Built-in LED – in order to gain access or control of this pin, you have to change the configuration of pin 13 where it is connected to.  Crystal Oscillator – Clock that has a frequency of 16MHz  DC Jack – where the power source (AC-to-DC adapter or battery) should be connected. It is limited to input values between 6-20V but recommended to be around 7-12V.  Digital I/O Pins – Input and Output pins (0-13) of which 6 of them (3, 5, 6, 9, 10 and 11) also provide PWM (Pulse Width Modulated) output by using the analogWrite() function. Pins (0 (RX) and 1 (TX)) are also used to transmit and receive serial data.  ICSP Header – Pins for “In-Circuit Serial Programming” which is another method of programming.
  • 8. Lab 1: I/O Ports Programming & LED Interfacing with Arduino Page 8  ON indicator – LED that lights up when the board is connected to a power source.  Power Pins – pins that can be used to supply a circuit with values VIN (voltage from DC Jack), 3.3V and 5V.  Reset Button – a button that is pressed whenever you need to restart the sketch programmed in the board.  USB port – allows the user to connect with a USB cable the board to a PC to upload sketches or provide a voltage supply to the board. This is also used for serial communication through the serial monitor from the Arduino software. Arduino Program Structure: Arduino programs (also called sketches) can be divided in three main parts: Structure, Values (variables and constants), and Functions. In this session, we will learn about the Arduino software program, step by step, and how we can write the program without any syntax or compilation error. Let us start with the Structure. Software structure consist of two main functions:  void setup( ) function  void loop( ) function
  • 9. Lab 1: I/O Ports Programming & LED Interfacing with Arduino Page 9  The setup() function is called when a sketch starts. Use it to initialize the variables, pin modes, start using libraries, etc. The setup function will only run once, after each power up or reset of the Arduino board.  After creating a setup() function, which initializes and sets the initial values, the loop() function does precisely what its name suggests, and loops consecutively, allowing your program to change and respond. Use it to actively control the Arduino board First Arduino Sketch: Write a program to toggle LED connected to PD1 (Pin No.1) with delay of 500 ms Solution: void setup ( ) { } void loop ( ) { } #define LED 1 void setup( ) { DDRD = DDRD | (1<<LED); // Set PD1 as output pin } void loop( ) { PORTD = PORTD & ~(1<<LED); // Turn OFF LED delay(500); // keep it OFF for 500 ms PORTD = PORTD | (1<<LED); // Turn ON LED delay(500); // keep it ON for 500 ms }
  • 10. Lab 1: I/O Ports Programming & LED Interfacing with Arduino Page 10 Lab Task: Write a program to blink built-in LED (Pin No.13, PB5) on UNO board at a frequency of 4Hz with 50% duty cycle.
  • 11. Lab 1: I/O Ports Programming & LED Interfacing with Arduino Page 11 Lab 1 Task Solution:
  • 12. Lab 2: Seven Segment Display Interfacing with Arduino Page 12 International Islamic University Islamabad Faculty of Engineering and Technology Department of Electrical Engineering MICROPROCESSORS AND MICROCONTROLLER LAB Lab 2 : Seven Segment Display Interfacing with Arduino Name: Reg. No: Date of Experiment: OBE Rubrics Evaluation a) PSYCHOMOTOR (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 1 Practical Implementation/ Arrangement of Equipment 0 1.25 2.5 3.75 5 Absent With several critical errors, incomplete and not neat With few errors, incomplete and not neat With some errors, complete but not neat Without errors, complete and neat 2 Use of Equipment or Simulation/ Programming Tool 0 0.5 1 1.5 2 Absent Limited competence Some competence Considerable competence Competence (b) COGNITIVE (To be judged on the copy of experiment submitted) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 3 Algorithm Design or Data Record, Analysis and Evaluation 0 0.25 0.5 0.75 1 Absent Incorrect Complete with some errors Complete with few errors Complete and Accurate (c) AFFECTIVE (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 4 Level of Participation & Attitude to Achieve Individual/Group Goals 0 0.5 1 1.5 2 Absent Rare sensible interaction Some sensible interaction Good sensible interaction Encouraging sensible interaction 5 Total Marks Obtained (Out of 10):
  • 13. Lab 2: Seven Segment Display Interfacing with Arduino Page 13 Objectives:  7 segment display interfacing and programming.  To understand the multiplexing technique. Introduction: A seven segment display, as its name indicates, is composed of seven elements. Individually on or off, they can be combined to produce simplified representations of the numerals. A single LED is used inside one segment to radiate light through it. If cathodes of all the LEDs are common, this type of display is called common cathode and for common anode type display, anode of all LEDs are common and connected to the common pin. Multiplexing: Multiplexing is required when we want to interface more than one displays with microcontroller. If we interface them normally, they will require lots of I/O ports. In multiplexing, only one display is kept active at a time but we see all of them active. For multiplexing all the displays are connected in parallel such that if you activate any segment, say ‘a’ the ‘a’ segment of all displays glows up. But we can switch ON and OFF the “common” line of the displays with the Microcontroller pins. So if we wish to light up the ‘a’ segment of display 1 we simply switch on display 1 first by applying ground level (for common cathode display) at the common pin of the display and then send a high signal on the I/O pin connected to segment ‘a’ to lit it.
  • 14. Lab 2: Seven Segment Display Interfacing with Arduino Page 14 No. . g f e d c b a Hex 0 1 2 3 4 5 6 7 8 9 0 0 1 1 1 1 1 1 0 0 0 0 0 1 1 0 0 1 0 1 1 0 1 1 0 1 0 0 1 1 1 1 0 1 1 0 0 1 1 0 0 1 1 0 1 1 0 1 0 1 1 1 1 1 0 1 0 0 0 0 0 1 1 1 0 1 1 1 1 1 1 1 0 1 1 0 1 1 1 1 0x3F 0x06 0x5B 0x4F 0x66 0x6D 0x7D 0x07 0x7F 0x6F Schematic: PORTD Pins PD7 PD6 PD5 PD4 PD3 PD2 PD1 PD0 Arduino Pins 7 6 5 4 3 2 1 0 Seven Segment Pins DP G F E D C B A g a a g
  • 15. Lab 2: Seven Segment Display Interfacing with Arduino Page 15 Sketch for Two Digit 7 Segment Displays: Counting from 00 to 99 Lab Task: Show hexadecimal numbers from 00 to FF on two seven segment displays #define SEG0_PIN 8 #define SEG1_PIN 9 byte Count; byte Seven_Segment[] = { 0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F }; void Display(byte No) { byte units, tens; tens = No / 10; // Separate tens from a number units = No % 10; // Separate units from a number for (int I = 0 ; I < 20 ; I++) // Show for 2 seconds { digitalWrite(SEG1_PIN,LOW); // Turn OFF SEG1 PORTD = Seven_Segment[units]; // Display units on SEG0 digitalWrite(SEG0_PIN,HIGH); // Turn ON SEG0 delay(50); digitalWrite(SEG0_PIN,LOW); // Turn OFF SEG0 PORTD = Seven_Segment[tens]; // Display tens on SEG1 digitalWrite(SEG1_PIN,HIGH); // Turn ON SEG1 to show tens delay(50); } } void setup(){ DDRD = 0xFF; // OUPTPUT PORTS FOR SEVEN SEGMENT DISPLAYS pinMode(SEG0_PIN,OUTPUT); // SELECT LINE(pin# 08) FOR SEG0 pinMode(SEG1_PIN,OUTPUT); // SELECT LINE(pin# 09) FOR SEG1 } void loop(){ Display(Count++); // Displays two digit value on 7 segments if(Count > 99) Count = 0; }
  • 16. Lab 2: Seven Segment Display Interfacing with Arduino Page 16 Lab 2 Task Solution:
  • 17. Lab 3: Keypad Interfacing with Arduino Page 17 International Islamic University Islamabad Faculty of Engineering and Technology Department of Electrical Engineering MICROPROCESSORS AND MICROCONTROLLER LAB Lab 3 : Keypad Interfacing with Arduino Name: Reg. No: Date of Experiment: OBE Rubrics Evaluation a) PSYCHOMOTOR (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 1 Practical Implementation/ Arrangement of Equipment 0 1.25 2.5 3.75 5 Absent With several critical errors, incomplete and not neat With few errors, incomplete and not neat With some errors, complete but not neat Without errors, complete and neat 2 Use of Equipment or Simulation/ Programming Tool 0 0.5 1 1.5 2 Absent Limited competence Some competence Considerable competence Competence (b) COGNITIVE (To be judged on the copy of experiment submitted) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 3 Algorithm Design or Data Record, Analysis and Evaluation 0 0.25 0.5 0.75 1 Absent Incorrect Complete with some errors Complete with few errors Complete and Accurate (c) AFFECTIVE (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 4 Level of Participation & Attitude to Achieve Individual/Group Goals 0 0.5 1 1.5 2 Absent Rare sensible interaction Some sensible interaction Good sensible interaction Encouraging sensible interaction 5 Total Marks Obtained (Out of 10):
  • 18. Lab 3: Keypad Interfacing with Arduino Page 18 Objectives:  To interface the keypad with Arduino board  To write the program for communication between Arduino and keypad. Keypad Overview: Keypad is input device which is used to give commands to other devices, from calculator to computer; input is given through keypad. It is an equipment used in the different projects where we need to send different commands to perform anything. In embedded devices one of the essential part is keypad and it is used to interact with the embedded devices. It is a low cost equipment and easily available in the market. Keypad has several applications in real life based projects e.g. calculators, mobile phones, ATM machine, Digital Locks etc. A 4x4 Keypad is shown in the figure given below. Keypad Pins: 4×4 keypad has total eight (8) pins. Description of Keypad pins: Keypad’s each pin is assigned with the different task to perform individually. A 4×4 Keypad’s pins functions are listed in the table provided below. Keypad Pins Pin No. Pin Name Pin Description 1 Row Pin Controls all the buttons of 1st row 2 Row Pin Controls all the buttons of 2nd row 3 Row Pin Controls all the buttons of 3rd row 4 Row Pin Controls all the buttons of 4th row 5 Column Pin Controls all the buttons of 1st column 6 Column Pin Controls all the buttons of 2nd column
  • 19. Lab 3: Keypad Interfacing with Arduino Page 19 7 Column Pin Controls all the buttons of 3rd column 8 Column Pin Controls all the buttons of 4th column The connections between keypad and Arduino are provided in the figure given below.
  • 20. Lab 3: Keypad Interfacing with Arduino Page 20 Sketch for Keypad Interfacing: Summary of Keypad Interfacing  First of all, we have defined the number of rows and columns of keypad.  Then we have declared the complete keypad characters in terms of rows and columns.  After that we have defined the row and column pin of keypad attached to the Arduino pins.  Then we have simple read the data sent from the keypad and displayed it on the serial monitor. Add Keypad Library: Before going to programming part first download keypad library from Arduino official website. we are using Arduino keypad library from Mark Stanley. Download the keypad.zip and add to Arduino library. Lab Task: Interface a 4x3 Keypad on Arduino board and show the pressed key serially on terminal display. A 4x3 Keypad has following key labels: 1 2 3 4 5 6 7 8 9 * 0 # #include <Keypad.h> #define ROWS 4 // My Keypad has four rows #define COLS 4; // and four columns // define the symbols on the buttons of the keypads char Keys[ROWS][COLS] = { {'1','2','3','A'}, {'4','5','6','B'}, {'7','8','9','C'}, {'*','0','#','D'} }; byte rowPins[ROWS] = {9, 8, 7, 6}; // row pinouts of the keypad byte colPins[COLS] = {5, 4, 3, 2}; // and column pinouts // initialize an instance of class Keypad Keypad MyKeypad( makeKeymap(Keys), rowPins, colPins, ROWS, COLS); void setup(){ Serial.begin(9600); } void loop(){ char Key_Pressed = MyKeypad.getKey(); if (Key_Pressed){ Serial.println(Key_Pressed); } }
  • 21. Lab 3: Keypad Interfacing with Arduino Page 21 Lab 3 Task Solution:
  • 22. Lab 4: Reading and Writing EEPROM in Arduino Page 22 International Islamic University Islamabad Faculty of Engineering and Technology Department of Electrical Engineering MICROPROCESSORS AND MICROCONTROLLER LAB Lab 4 : Reading and Writing EEPROM in Arduino Name: Reg. No: Date of Experiment: OBE Rubrics Evaluation a) PSYCHOMOTOR (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 1 Practical Implementation/ Arrangement of Equipment 0 1.25 2.5 3.75 5 Absent With several critical errors, incomplete and not neat With few errors, incomplete and not neat With some errors, complete but not neat Without errors, complete and neat 2 Use of Equipment or Simulation/ Programming Tool 0 0.5 1 1.5 2 Absent Limited competence Some competence Considerable competence Competence (b) COGNITIVE (To be judged on the copy of experiment submitted) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 3 Algorithm Design or Data Record, Analysis and Evaluation 0 0.25 0.5 0.75 1 Absent Incorrect Complete with some errors Complete with few errors Complete and Accurate (c) AFFECTIVE (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 4 Level of Participation & Attitude to Achieve Individual/Group Goals 0 0.5 1 1.5 2 Absent Rare sensible interaction Some sensible interaction Good sensible interaction Encouraging sensible interaction 5 Total Marks Obtained (Out of 10):
  • 23. Lab 4: Reading and Writing EEPROM in Arduino Page 23 Objectives:  To Write and Read data from EEPROM in Arduino. Introduction: When you define a variable in programming, the value of this variable only lasts as long as the Arduino is on. If you reset or power off the Arduino, It’s value disappears. If you want to keep this data stored for future use you need to use the Arduino EEPROM. This stores the variable’s data even when the Arduino resets or the power is turned off. What is EEPROM? The microcontroller on the Arduino board (ATMEGA328 in case of Arduino UNO) has EEPROM (Electrically Erasable Programmable Read-Only Memory). It has 1K Byte memory that can store data. The data stored in the EEPROM is kept there, even when you reset or power off the Arduino. Simply, the EEPROM is permanent storage similar to a hard drive in computers. The EEPROM memory has a specified life of 100,000 write/erase cycles, so you may need to be careful about how often you write to it. However, reads are unlimited. This means you can read from the EEPROM as many times as you want without compromising its life expectancy. To include the EEPROM library: #include <EEPROM.h> Write: To write data into the EEPROM, you use the EEPROM.write() function that takes in two arguments. The first one is the EEPROM location or address where you want to save the data, and the second is the value we want to save: EEPROM.write(address, value); For example, to write 9 on address 0, you’ll have: EEPROM.write(0, 9); Read: To read a byte from the EEPROM, you use the EEPROM.read() function. This function takes the address of the byte has an argument. EEPROM.read(address); For example, to read the byte stored previously in address 0.: EEPROM.read(0); This would return 9, which is the value stored in that location.
  • 24. Lab 4: Reading and Writing EEPROM in Arduino Page 24 Update a Value: The EEPROM.update() function is particularly useful. It only writes on the EEPROM if the value written is different from the one already saved. As the EEPROM has limited life expectancy due to limited write/erase cycles, using the EEPROM.update() function instead of the EEPROM.write() saves cycles. You use this function as follows: EEPROM.update(address, value); At the moment, we had 9 stored in the address 0. So, if we call: EEPROM.update(0, 9); It won’t write on the EEPROM again, as the value currently saved is the same we want to write. Sketch for EEPROM: #include <EEPROM.h> char D3,D2,D1,D0; // variables to store password int Address = 0x100; // EEPROM Address, it's value can be // from 0x0 to 0x3FF for 1K Byte EEPROM void setup() { Serial.begin (9600); } void loop() { D0 = EEPROM.read(Address); //Read Previous State from EEPROM D1 = EEPROM.read(Address + 1); D2 = EEPROM.read(Address + 2); D3 = EEPROM.read(Address + 3); Serial.print ("Current Password is ["); Serial.print (D0); Serial.print (D1); Serial.print (D2); Serial.print (D3); Serial.println ("]"); Serial.println ("Precess C to Change Password" ); while(Serial.available()== 0); if(Serial.available() > 0 ){ int cmd = Serial.read(); // Send the Character Back Serial.println (char(cmd)); if( cmd == 'c' || cmd == 'C'){ Serial.print ("Enter 1st Digit:" ); while(Serial.available()== 0); D0 = Serial.read(); Serial.println (D0);
  • 25. Lab 4: Reading and Writing EEPROM in Arduino Page 25 Lab Task: Write a program to store and modify 6-digits password. Turn ON Built in LED if password is correct and Turn OFF if password is incorrect. Serial.print ("Enter 2nd Digit:" ); while(Serial.available()== 0); D1 = Serial.read(); Serial.println (D1); Serial.print ("Enter 3rd Digit:" ); while(Serial.available()== 0); D2 = Serial.read(); Serial.println (D2); Serial.print ("Enter 4th Digit:" ); while(Serial.available()== 0); D3 = Serial.read(); Serial.println (D3); EEPROM.update(Address , D0); EEPROM.update(Address + 1 , D1); EEPROM.update(Address + 2 , D2); EEPROM.update(Address + 3 , D3); Serial.println ("Password has been Changed"); } } }
  • 26. Lab 4: Reading and Writing EEPROM in Arduino Page 26
  • 27. Lab 4: Reading and Writing EEPROM in Arduino Page 27 Lab 4 Task Solution:
  • 28. Lab 5: LCD Interfacing with Arduino Page 28 International Islamic University Islamabad Faculty of Engineering and Technology Department of Electrical Engineering MICROPROCESSORS AND MICROCONTROLLER LAB Lab 5 : LCD Interfacing with Arduino Name: Reg. No: Date of Experiment: OBE Rubrics Evaluation a) PSYCHOMOTOR (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 1 Practical Implementation/ Arrangement of Equipment 0 1.25 2.5 3.75 5 Absent With several critical errors, incomplete and not neat With few errors, incomplete and not neat With some errors, complete but not neat Without errors, complete and neat 2 Use of Equipment or Simulation/ Programming Tool 0 0.5 1 1.5 2 Absent Limited competence Some competence Considerable competence Competence (b) COGNITIVE (To be judged on the copy of experiment submitted) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 3 Algorithm Design or Data Record, Analysis and Evaluation 0 0.25 0.5 0.75 1 Absent Incorrect Complete with some errors Complete with few errors Complete and Accurate (c) AFFECTIVE (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 4 Level of Participation & Attitude to Achieve Individual/Group Goals 0 0.5 1 1.5 2 Absent Rare sensible interaction Some sensible interaction Good sensible interaction Encouraging sensible interaction 5 Total Marks Obtained (Out of 10):
  • 29. Lab 5: LCD Interfacing with Arduino Page 29 Objectives:  To interface the LCD and program Arduino UNO to show the characters on 16x2 LCD. Introduction: A 16 × 2 LCD display is commonly used as a display device in various circuits. This module is preferred over seven segments as they are economical, easily programmable, and have no limitation of displaying special and even custom characters. A 16 × 2 LCD means that it can display 16 characters per row and there are two rows. In this LCD, each character is displayed in a 5 × 7 pixel matrix. This LCD has two registers: (1) Command register and (2) Data register. The command register stores the instructions that are given to the LCD. An instruction is given to the LCD to do a predefined task such as initializing it, clearing its screen, setting the cursor position, and controlling the display, and so on. The data register stores the data to be displayed on the LCD. A 20 × 4 LCD means that it can display 20 characters per row and there are 4 rows. In this LCD, each character is displayed in a 5×7 pixel matrix. The pin description 16x2 LCD is shown in Table 7.1. Figure 7.1:16X2 LCD Module
  • 30. Lab 5: LCD Interfacing with Arduino Page 30 Table 7.1: 44780 based LCD Pin out PIN SYMBOL I/O DESCRIPTION 1 VSS - Power supply (GND) 2 VCC - Power supply (+5V) (VDD) 3 VEE - Contrast Settings (0 to 2V) (Vo) 4 RS I 0 = Select command reg. 1 = Select data reg. of LCD 5 R/W I 0 = Write to LCD 1 = Read from LCD 6 E I The Enable (E) line allows access to the display through R/W and RS lines. 0 = Access to LCD disabled 1 = Access to LCD enabled 7 DB0 I/O Data bit line 0 (LSB) 8 DB1 I/O Data bit line 1 9 DB2 I/O Data bit line 2 10 DB3 I/O Data bit line 3 11 DB4 I/O Data bit line 4 For 4-bit Mode, only these pins are used as data bits 12 DB5 I/O Data bit line 5 13 DB6 I/O Data bit line 6 14 DB7 I/O Data bit line 7 (MSB) 15 A - Back Light Anode (+5V) 16 K - Back Light Cathode (GND) Schematic:
  • 31. Lab 5: LCD Interfacing with Arduino Page 31 LCD Functions: 1. LiquidCrystal() Description It creates a variable or object of type LiquidCrystal. The display can be controlled using 4 or 8 data lines. For 4 data lines we omit the pin numbers for D0 to D3 and leave those lines unconnected. The RW pin can be tied to ground instead of connected to a pin on the Arduino; if so, omit it from this function's parameters. Syntax LiquidCrystal(RS, E, D4, D5, D6, D7) LiquidCrystal(RS, RW, E, D4, D5, D6, D7) LiquidCrystal(RS, E, D0, D1, D2, D3, D4, D5, D6, D7) LiquidCrystal(RS, RW, E, D0, D1, D2, D3, D4, D5, D6, D7) Parameters RS: The number of the Arduino pin that is connected to the RS pin on the LCD RW: The number of the Arduino pin that is connected to the RW pin on the LCD (optional) E: The number of the Arduino pin that is connected to the enable pin on the LCD D0, D1, D2, D3, D4, D5, D6, D7: The numbers of the Arduino pins which are connected to the corresponding data pins on the LCD. D0, D1, D2, and D3 are optional; if omitted, the LCD will be controlled using only the four data lines (D4, D5, D6, D7). 2. lcd.begin(16, 2); // initialize LCD 16 * 2 3. lcd.print("DEE"); // print a string “DEE” on LCD 4. lcd.setCursor(x, y); // set the cursor of LCD at the desired // location inwhich x is the number of // COLUMN and y is the ROW Number. 5. lcd.print(x); // print a x as an integer on the LCD 6. lcd.Clear(); // clear the contents of the LCD
  • 32. Lab 5: LCD Interfacing with Arduino Page 32 Sketch for LCD Display: Lab Task: Write a sketch to display your registration number in first line and your name in Urdu language using 4 custom characters in second line of LCD. #include <LiquidCrystal.h> const int RS = 13, E = 12, D4 = 11, D5 = 10, D6 = 9, D7 = 8; LiquidCrystal lcd(RS, E, D4, D5, D6, D7); byte k=0; byte Shape0[7]={ 0b01110, 0b01110, 0b00100, 0b01110, 0b10101, 0b00100, 0b01010, }; byte Shape1[7]={ 0x0E,0x0E,0x15,0xE,0x04,0x04,0x0A}; void setup(){ // set up the LCD's number of columns and rows: lcd.begin(16, 2); lcd.createChar(0, Shape0); // create a new character lcd.createChar(1, Shape1); // create a new character lcd.setCursor(0, 0); // Go to Column 0, Row 0 lcd.print("hello, world!"); // Print a message to the LCD. } void loop(){ // set the cursor to column 0, line 1 // note: line 1 is the second row, // since counting begins with 0 lcd.setCursor(0, 1); // print the number of seconds since reset: lcd.print(millis() / 1000); lcd.write(byte(k++%2)); // Show Custom Character 0 and 1 delay(500); }
  • 33. Lab 5: LCD Interfacing with Arduino Page 33 Lab 5 Task Solution:
  • 34. Lab 6: PWM Signal Generation with Arduino Page 34 International Islamic University Islamabad Faculty of Engineering and Technology Department of Electrical Engineering MICROPROCESSORS AND MICROCONTROLLER LAB Lab 6 : PWM Signal Generation with Arduino Name: Reg. No: Date of Experiment: OBE Rubrics Evaluation a) PSYCHOMOTOR (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 1 Practical Implementation/ Arrangement of Equipment 0 1.25 2.5 3.75 5 Absent With several critical errors, incomplete and not neat With few errors, incomplete and not neat With some errors, complete but not neat Without errors, complete and neat 2 Use of Equipment or Simulation/ Programming Tool 0 0.5 1 1.5 2 Absent Limited competence Some competence Considerable competence Competence (b) COGNITIVE (To be judged on the copy of experiment submitted) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 3 Algorithm Design or Data Record, Analysis and Evaluation 0 0.25 0.5 0.75 1 Absent Incorrect Complete with some errors Complete with few errors Complete and Accurate (c) AFFECTIVE (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 4 Level of Participation & Attitude to Achieve Individual/Group Goals 0 0.5 1 1.5 2 Absent Rare sensible interaction Some sensible interaction Good sensible interaction Encouraging sensible interaction 5 Total Marks Obtained (Out of 10):
  • 35. Lab 6: PWM Signal Generation with Arduino Page 35 Objectives:  What is PWM and how you can get the PWM output from the digital pins of Arduino  To program and use the PWM feature of AVR  To generate a square wave of different duty cycles using PWM feature of AVR  To control the brightness of LED through programming and then we will control it manually by adding the potentiometer. Introduction: PWM stands for Pulse Width Modulation and it is a technique used in controlling the brightness of LED, speed control of DC motor, controlling a servo motor or where you have to get analog output with digital means. The Arduino digital pins either gives us 5V (when turned HIGH) or 0V (when turned LOW) and the output is a square wave signal. So if we want to dim a LED, we cannot get the voltage between 0 and 5V from the digital pin but we can change the ON and OFF time of the signal. If we will change the ON and OFF time fast enough then the brightness of the led will be changed. Before going further, let’s discuss some terms associated with PWM. TON (On Time): It is the time when the signal is high. TOFF (Off Time): It is the time when the signal is low. Time Period: It is the sum of on time and off time. Duty Cycle: It is the percentage of time when the signal was high during the time of period. So at 50% duty cycle and 1Hz frequency, the LED will be high for half a second and will be low for the other half second. If we increase the frequency to 50Hz (50 times ON and OFF per second), then the led will be seen glowing at half brightness by the human eye.
  • 36. Lab 6: PWM Signal Generation with Arduino Page 36 Arduino and PWM: The Arduino IDE has a built in function analogWrite() which can be used to generate a PWM signal. The frequency of this generated signal for most pins will be about 490Hz and we can give the value from 0-255 using this function. analogWrite(0) means a signal of 0% duty cycle. analogWrite(127) means a signal of 50% duty cycle. analogWrite(255) means a signal of 100% duty cycle. On Arduino UNO, the PWM pins are labeled with ~ sign. BOARD PWM PINS PWM FREQUENCY UNO, Nano, Mini 3, 5, 6, 9, 10, 11 490 Hz (pins 5 and 6: 980 Hz) Mega 2 - 13, 44 - 46 490 Hz (pins 4 and 13: 980 Hz) Leonardo, Micro, Yún 3, 5, 6, 9, 10, 11, 13 490 Hz (pins 3 and 11: 980 Hz) Uno WiFi Rev.2 3, 5, 6, 9, 10 976 Hz Controlling Brightness of LED through Code: Connect the positive leg of LED which is the longer leg to the Pin No.11 of Arduino UNO. Then connect the 220Ω resistor to the negative leg of LED and connect the other end of resistor to the ground pin of Arduino as shown in Figure 1.
  • 37. Lab 6: PWM Signal Generation with Arduino Page 37 Figure 1: Circuit Diagram to PWM Implementation Now write the following code to change the brightness of the LED using PWM. Arduino Code: PWD Generation Arduino Code to manually control the Brightness of LED: An addition to Figure 1, take a 10KΩ potentiometer and connect its left pin to GND and right pin to 5V of Arduino. and then connect the center pin of potentiometer to the A0 Pin of Arduino as shown in figure 2. int led_pin = 11; // Initializing LED Pin int i; void setup() { pinMode(led_pin, OUTPUT); // Declare LED pin as output } void loop() { for( i=0; i<255; i++) // Fading the LED { analogWrite(led_pin, i); delay(10); } for( i=255; i>0; i--) { analogWrite(led_pin, i); delay(10); } }
  • 38. Lab 6: PWM Signal Generation with Arduino Page 38 Figure 2: Manually Controlling Brightness of LED Sketch: Upload the code in the Arduino IDE and on moving the knob of the potentiometer, the brightness of the LED will change. int led_pin = 11; // Initializing LED Pin int pot_pin = A0; // Initializing LED Pin int data_10_bit, data_8_bit; void setup() { pinMode(led_pin, OUTPUT); // Declare LED pin as output } void loop() { data_10_bit = analogRead(pot_pin); // Reading from potentiometer // Mapping the Values between 0 to 255 because we can give // output from 0-255 using the analogwrite() funtion data_8_bit = data_10_bit >> 2; // data_8_bit = map(data_10_bit, 0, 1023, 0, 255); analogWrite(led_pin, data_8_bit); delay(10); }
  • 39. Lab 6: PWM Signal Generation with Arduino Page 39 Lab Task: Generate a PWM Signal of frequency 490 Hz on Pin No.9 of Arduino UNO Board.  Place an LED with 220 Ω resistor on Pin No.9.  Connect Two Push Buttons on Pin No.2 and Pin No.4. and join their other ends to Ground. o Label one button as Up and Other button as Down. o When we press the Up Button, it should increase the Duty Cycle of PWD Signal o When we press the Down Button, it should decrease the Duty Cycle of PWD Signal.
  • 40. Lab 6: PWM Signal Generation with Arduino Page 40 Lab 6 Task Solution:
  • 41. Lab 7: Timer Mode Programming with Arduino Page 41 International Islamic University Islamabad Faculty of Engineering and Technology Department of Electrical Engineering MICROPROCESSORS AND MICROCONTROLLER LAB Lab 7 : Timer Mode Programming with Arduino Name: Reg. No: Date of Experiment: OBE Rubrics Evaluation a) PSYCHOMOTOR (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 1 Practical Implementation/ Arrangement of Equipment 0 1.25 2.5 3.75 5 Absent With several critical errors, incomplete and not neat With few errors, incomplete and not neat With some errors, complete but not neat Without errors, complete and neat 2 Use of Equipment or Simulation/ Programming Tool 0 0.5 1 1.5 2 Absent Limited competence Some competence Considerable competence Competence (b) COGNITIVE (To be judged on the copy of experiment submitted) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 3 Algorithm Design or Data Record, Analysis and Evaluation 0 0.25 0.5 0.75 1 Absent Incorrect Complete with some errors Complete with few errors Complete and Accurate (c) AFFECTIVE (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 4 Level of Participation & Attitude to Achieve Individual/Group Goals 0 0.5 1 1.5 2 Absent Rare sensible interaction Some sensible interaction Good sensible interaction Encouraging sensible interaction 5 Total Marks Obtained (Out of 10):
  • 42. Lab 7: Timer Mode Programming with Arduino Page 42 Objectives:  To understand the modes and functionality of timers of ATmega328.  To program Timer for event counting. Introduction: There are counter registers in microcontrollers,  to generate time delays  to count an event.  for waveform generation  for input capture. When we connect the external event source to the clock pin of the counter register. This is counter mode. When we connect the oscillator to the clock pin of the counter. This is timer mode. Timers/Counters are essential part of any modern MCU. They are an independent unit inside a micro-controller. They basically run independently of what instruction CPU is executing. They are primarily used for the following:  Internal Timer: As an internal timer the unit, ticks on the oscillator frequency. The oscillator frequency can be directly feed to the timer or it can be pre-scaled. In this mode it used generate precise delays. Or as precise time counting machine.  External Counter: In this mode the unit is used to count events on a specific external pin on a MCU.  Pulse width Modulation (PWM) Generator: PWM is used in speed control of motors and various other applications.  Input Capture Mode: Input capture mode is used to measure time period and pulse width of an external frequency. Arduino UNO has 3 timers and these times count at some frequency derived from the 16MHz system clock:  Timer0 is an 8-bit timer: It is used by millis(), delay() and analogWrite() on pins 5 and 6.  Timer1 is a 16-bit timer: It is used by analogWrite() functions on pins 9 and 10; It is also used for driving servos using the Servo library so you can’t use analogWrite with these pins when using the Servo library.  Timer2 is an 8-bit timer. It is used by analogWrite() functions on pins 3 and 11 and the Tone() library  Clock Divisor: configured to alter the frequency and various counting modes  Timers can be configured to generate interrupts when they overflow or reach a specific count Important Registers and Flags Associated with Timers: Each timer has following registers associated with it, we can change the Timer behavior through the timer register:  TCNTn (Timer/Counter Reg): Upon reset, it has zero value and counts with each timer clock. We can load/read a value into the TCNT0 register
  • 43. Lab 7: Timer Mode Programming with Arduino Page 43  TCCRn (Timer/Counter Control Reg): For setting modes of operation (Timer /Counter) of Timer  OCRn (Output Compare Reg): The OCR0A register is used with CTC mode. In CTC mode timer is incremented with a clock. When contents of TCNT are equal to OCRA, OCF flag is raised and value of TCNTn is reset to zero  TOVn (Timer Overflow Flag): When overflow occurs, this flag is raised /set  OCFn (Output Compare Flag): When contents of TCNT are equal to OCR, OCF flag (located in TIFR register) is raised and value of TCNTn is reset to zero. 7 6 5 4 3 2 1 0 Bit No. COM0A1 COM0A0 COM0B1 COM0B0 - - WGM 01 WGM 00 TCCR0A R/W R/W R/W R/W R R R/W R/W 0 0 0 0 0 0 0 0 Default 7 6 5 4 3 2 1 0 Bit No. FOC0A FOC0B - - WGM02 CS02 CS01 CS00 TCCR0B W W R R R/W R/W R/W R/W 0 0 0 0 0 0 0 0 Default Clock Source Select Description CS02 CS01 CS00 0 0 0 No clock source (Timer/ Counter Stopped) 0 0 1 CLKI/O (No Pre-scaling) 0 1 0 CLKI/O/8 (1:8 Pre-scaling) 0 1 1 CLKI/O/64 (1:64 Pre-scaling) 1 0 0 CLKI/O/256 (1:256 Pre-scaling) 1 0 1 CLKI/O/1024 (1:1024 Pre-scaling) 1 1 0 External clock source on T0 pin. Counting on falling edge 1 1 1 External clock source on T0 pin. Counting on rising edge Mode WGM02 WGM01 WGM00 Timer / Counter Mode of Operation 0 0 0 0 Normal 1 0 0 1 PWM Phase Correct 2 0 1 0 CTC (Clear Timer on Compare Match) 3 0 1 1 Fast PWM (Pulse Width Modulation) 4 1 0 0 Reserved 5 1 0 1 PWM Phase Correct 6 1 1 0 Reserved 7 1 1 1 Fast PWM 7 6 5 4 3 2 1 0 - - - - - OCF0B OCF0A TOV0 TIFR0 R R R R R R/W R/W R/W 0 0 0 0 0 0 0 0
  • 44. Lab 7: Timer Mode Programming with Arduino Page 44 Timer Modes: Normal mode: In this mode, the content of the timer/counter increments with each clock. It counts up until it reaches its max of 0xFF. When it rolls over from 0xFF to 0x00, it sets high a flag bit called TOV0 (Timer0 Overflow). Steps to program Timer0 in Normal mode: 1. Load the TCNT0 register with the initial count value. 2. Load the value into the TCCR0A and TCCR0B register, indicating which mode is to be used and the pre-scaler option. 3. When you select the clock source, the timer/counter starts to count, and each tick causes the content of the timer/counter to increment by 1. 4. Keep monitoring the timer overflow flag (TOV0) to see if it is raised. Get out of the loop when TOV0 becomes high. 5. Stop the timer by disconnecting the clock source 6. Clear the TOV0 flag for the next round. 7. Go back to Step 1 to load TCNT0 again. CTC mode: The OCR0A register is used with CTC mode. In CTC mode timer is incremented with a clock and it counts until the contents of TCNT0 register becomes equal to the contents of OCR0A register (compare match occurs); then the timer will be cleared and the OCF0A flag will be set when the next clock occurs. OCF0A flag is in TIFR register. The difference between Timer0 and Timer2: Last two combinations of CS02-00 bits select the rising and falling edge of external event counter in Timer0. Whereas in Timer2 these two combinations of CS22-20 bits used to select different options of pre-scaler. Timer1 Timer 1 is 16-bit timer and following is the register’s details 7 6 5 4 3 2 1 0 COM1A 1 COM1A 0 COM1B 1 COM1B 0 - - WGM1 1 WGM1 0 TCCR1 A R/W R/W R/W R/W R R R/W R/W 0 0 0 0 0 0 0 0 7 6 5 4 3 2 1 0
  • 45. Lab 7: Timer Mode Programming with Arduino Page 45 ICNC1 ICES1 - WGM13 WGM1 2 CS1 2 CS11 CS10 TCCR1 B R/W R/W R R R/W R/W R/W R/W 0 0 0 0 0 0 0 0 Clock Source Select Description CS12 CS11 CS10 0 0 0 No clock source (Timer/ Counter Stopped) 0 0 1 CLKI/O (No Pre-scaling) 0 1 0 CLKI/O/8 (1:8 Pre-scaling) 0 1 1 CLKI/O/64 (1:64 Pre-scaling) 1 0 0 CLKI/O/256 (1:256 Pre-scaling) 1 0 1 CLKI/O/1024 (1:1024 Pre-scaling) 1 1 0 External clock source on T1 pin. Counting on falling edge 1 1 1 External clock source on T1 pin. Counting on rising edge Mode WGM12 WGM11 WGM10 Timer / Counter Mode of Operation 0 0 0 0 Normal 4 1 0 0 CTC (Clear Timer on Compare Match) Read Data Sheet for Other Modes Assuming XTAL = 16 MHz, write a program to generate a delay of 1ms using CTC and Normal mode. Pre- Scaler Timer Clock Timer Period (Time of One Count) Total Counts None 16 MHz 1/16MHz = 0.0625 µs 1ms / 0.0625 µs = 16,000 8 16 MHz / 8 = 2MHz 1/2MHz = 0.5 µs 1ms / 0.5 µs = 2000 64 16 MHz / 64 = 250KHz 1/250KHz = 4 µs 1ms / 4 µs = 250 256 16 MHz / 256 = 62.5KHz 1/62.5KHz = 16 µs 1ms / 16 µs = 62.5 1024 16 MHz / 1024 = 15.625 KHz 1/15.625 KHz = 64 µs 1ms / 64 µs = 15.625 From the above calculation we can only use the options Pre-scaler = 64 since we cannot use a decimal point and to wait 250 clocks we should load OCR0A with 250-1 = 249 If we are programming for Normal Mode, then we will write TCNT0 = - 250
  • 46. Lab 7: Timer Mode Programming with Arduino Page 46 Timer0 Normal Mode Programing Timer0 CTC Mode Programing void T0_Delay() { TCNT0 = -250; // TCNT0 = 6 = 0x06 = -250 TCCR0A = 0x00; // Normal mode TCCR0B = 0x03; // Run Timer0 with 1:64 Pre-scaler // wait for TOV0 to roll over while ((TIFR0&(1<<TOV0))==0); TCCR0B = 0; // Stop Timer TIFR0 |= 1<<TOV0; // Clear TOV0 } void setup(){ DDRB = DDRB | (1<<5) ; // PB5 as output TIMSK0 &= ~(1<<0); // Disable Timer0 Overflow Interrupt } void loop(){ PORTB = PORTB | (1<<5);T0_Delay(); // Turn ON LED for 1 ms PORTB = PORTB & ~(1<<5);T0_Delay(); // Turn OFF LED for 1 ms } // toggle bits of PB5 continuously with 1ms delay using CTC Mode. void T0_Delay(){ TCNT0 = 0x00; // Start timer from 0x00 OCR0A = 250-1; // initial Value of OCR0A = 249 TCCR0A = 0x02; // CTC mode TCCR0B = 0x03; // Run Timer0 with 1:64 Pre-scaler while ((TIFR0 & (1<<OCF0A))== 0); // wait for Compare Match TCCR0B = 0; // Stop Timer TIFR0 |= 1<<OCF0A; // Clear OCF0A } void setup(){ DDRB = DDRB | (1<<5) ; // PB5 as output TIMSK0 &= ~(1<<0); // Disable Timer0 Overflow Interrupt } void loop(){ PORTB = PORTB | (1<<5);T0_Delay(); // Turn ON LED PORTB = PORTB & ~(1<<5);T0_Delay(); // Turn OFF LED }
  • 47. Lab 7: Timer Mode Programming with Arduino Page 47 Schematic Diagram: Lab Task: Using Timer0 write a program to generate a Frequency 39.06 Hz on PB5 using Normal Mode or CTC Mode.
  • 48. Lab 7: Timer Mode Programming with Arduino Page 48 Lab 7 Task Solution:
  • 49. Lab 8: Counter Mode Programming with Arduino Page 49 International Islamic University Islamabad Faculty of Engineering and Technology Department of Electrical Engineering MICROPROCESSORS AND MICROCONTROLLER LAB Lab 8 : Counter Mode Programming with Arduino Name: Reg. No: Date of Experiment: OBE Rubrics Evaluation a) PSYCHOMOTOR (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 1 Practical Implementation/ Arrangement of Equipment 0 1.25 2.5 3.75 5 Absent With several critical errors, incomplete and not neat With few errors, incomplete and not neat With some errors, complete but not neat Without errors, complete and neat 2 Use of Equipment or Simulation/ Programming Tool 0 0.5 1 1.5 2 Absent Limited competence Some competence Considerable competence Competence (b) COGNITIVE (To be judged on the copy of experiment submitted) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 3 Algorithm Design or Data Record, Analysis and Evaluation 0 0.25 0.5 0.75 1 Absent Incorrect Complete with some errors Complete with few errors Complete and Accurate (c) AFFECTIVE (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 4 Level of Participation & Attitude to Achieve Individual/Group Goals 0 0.5 1 1.5 2 Absent Rare sensible interaction Some sensible interaction Good sensible interaction Encouraging sensible interaction 5 Total Marks Obtained (Out of 10):
  • 50. Lab 8: Counter Mode Programming with Arduino Page 50 Objectives:  To understand the modes and functionality of timers of ATmega328.  To program Timer for event counting. Introduction: There are counter registers in microcontrollers,  to generate time delays  to count an event.  for waveform generation  for input capture. When we connect the external event source to the clock pin of the counter register. This is counter mode. When we connect the oscillator to the clock pin of the counter. This is timer mode. Timers/Counters are essential part of any modern MCU. They are an independent unit inside a micro-controller. They basically run independently of what instruction CPU is executing. They are primarily used for the following:  Internal Timer: As an internal timer the unit, ticks on the oscillator frequency. The oscillator frequency can be directly feed to the timer or it can be pre-scaled. In this mode it used generate precise delays. Or as precise time counting machine.  External Counter: In this mode the unit is used to count events on a specific external pin on a MCU.  Pulse width Modulation (PWM) Generator: PWM is used in speed control of motors and various other applications.  Input Capture Mode: Input capture mode is used to measure time period and pulse width of an external frequency. Arduino UNO has 3 timers and these times count at some frequency derived from the 16MHz system clock:  Timer0 is an 8-bit timer: It is used by millis(), delay() and analogWrite() on pins 5 and 6.  Timer1 is a 16-bit timer: It is used by analogWrite() functions on pins 9 and 10; It is also used for driving servos using the Servo library so you can’t use analogWrite with these pins when using the Servo library.  Timer2 is an 8-bit timer. It is used by analogWrite() functions on pins 3 and 11 and the Tone() library  Clock Divisor: configured to alter the frequency and various counting modes  Timers can be configured to generate interrupts when they overflow or reach a specific count Important Registers and Flags Associated with Timers: Each timer has following registers associated with it, we can change the Timer behavior through the timer register:  TCNTn (Timer/Counter Reg): Upon reset, it has zero value and counts with each timer clock. We can load/read a value into the TCNT0 register
  • 51. Lab 8: Counter Mode Programming with Arduino Page 51  TCCRn (Timer/Counter Control Reg): For setting modes of operation (Timer /Counter) of Timer  OCRn (Output Compare Reg): The OCR0A register is used with CTC mode. In CTC mode timer is incremented with a clock. When contents of TCNT are equal to OCRA, OCF flag is raised and value of TCNTn is reset to zero  TOVn (Timer Overflow Flag): When overflow occurs, this flag is raised /set  OCFn (Output Compare Flag): When contents of TCNT are equal to OCR, OCF flag (located in TIFR register) is raised and value of TCNTn is reset to zero. 7 6 5 4 3 2 1 0 COM0A1 COM0A0 COM0B1 COM0B0 - - WGM 01 WGM 00 TCCR0 A R/W R/W R/W R/W R R R/W R/W 0 0 0 0 0 0 0 0 7 6 5 4 3 2 1 0 FOC0A FOC0B - - WGM 02 CS 02 CS01 CS00 TCCR0 B W W R R R/W R/ W R/W R/W 0 0 0 0 0 0 0 0 Clock Source Select Description CS02 CS01 CS00 0 0 0 No clock source (Timer/ Counter Stopped) 0 0 1 CLKI/O (No Pre-scaling) 0 1 0 CLKI/O/8 (1:8 Pre-scaling) 0 1 1 CLKI/O/64 (1:64 Pre-scaling) 1 0 0 CLKI/O/256 (1:256 Pre-scaling) 1 0 1 CLKI/O/1024 (1:1024 Pre-scaling) 1 1 0 External clock source on T0 pin. Counting on falling edge 1 1 1 External clock source on T0 pin. Counting on rising edge Mode WGM02 WGM01 WGM00 Timer / Counter Mode of Operation 0 0 0 0 Normal 1 0 0 1 PWM Phase Correct 2 0 1 0 CTC (Clear Timer on Compare Match) 3 0 1 1 Fast PWM (Pulse Width Modulation) 4 1 0 0 Reserved 5 1 0 1 PWM Phase Correct 6 1 1 0 Reserved 7 1 1 1 Fast PWM
  • 52. Lab 8: Counter Mode Programming with Arduino Page 52 7 6 5 4 3 2 1 0 - - - - - OCF0B OCF0A TOV0 TIFR0 R R R R R R/W R/W R/W 0 0 0 0 0 0 0 0 Timer Modes: Normal mode: In this mode, the content of the timer/counter increments with each clock. It counts up until it reaches its max of 0xFF. When it rolls over from 0xFF to 0x00, it sets high a flag bit called TOV0 (Timer0 Overflow). Steps to program Timer0 in Normal mode: 8. Load the TCNT0 register with the initial count value. 9. Load the value into the TCCR0A and TCCR0B register, indicating which mode is to be used and the pre-scaler option. 10.When you select the clock source, the timer/counter starts to count, and each tick causes the content of the timer/counter to increment by 1. 11.Keep monitoring the timer overflow flag (TOV0) to see if it is raised. Get out of the loop when TOV0 becomes high. 12.Stop the timer by disconnecting the clock source 13.Clear the TOV0 flag for the next round. 14.Go back to Step 1 to load TCNT0 again. CTC mode: The OCR0A register is used with CTC mode. In CTC mode timer is incremented with a clock and it counts until the contents of TCNT0 register becomes equal to the contents of OCR0A register (compare match occurs); then the timer will be cleared and the OCF0A flag will be set when the next clock occurs. OCF0A flag is in TIFR register. The difference between Timer0 and Timer2: Last two combinations of CS02-00 bits select the rising and falling edge of external event counter in Timer0. Whereas in Timer2 these two combinations of CS22-20 bits used to select different options of pre-scaler. Timer1 Timer 1 is 16-bit timer and following is the register’s details 7 6 5 4 3 2 1 0 COM1A 1 COM1A 0 COM1B 1 COM1B 0 - - WGM1 1 WGM1 0 TCCR1 A R/W R/W R/W R/W R R R/W R/W
  • 53. Lab 8: Counter Mode Programming with Arduino Page 53 0 0 0 0 0 0 0 0 7 6 5 4 3 2 1 0 ICNC1 ICES1 - WGM13 WGM1 2 CS1 2 CS11 CS10 TCCR1 B R/W R/W R R R/W R/W R/W R/W 0 0 0 0 0 0 0 0 Clock Source Select Description CS12 CS11 CS10 0 0 0 No clock source (Timer/ Counter Stopped) 0 0 1 CLKI/O (No Pre-scaling) 0 1 0 CLKI/O/8 (1:8 Pre-scaling) 0 1 1 CLKI/O/64 (1:64 Pre-scaling) 1 0 0 CLKI/O/256 (1:256 Pre-scaling) 1 0 1 CLKI/O/1024 (1:1024 Pre-scaling) 1 1 0 External clock source on T1 pin. Counting on falling edge 1 1 1 External clock source on T1 pin. Counting on rising edge Mode WGM12 WGM11 WGM10 Timer / Counter Mode of Operation 0 0 0 0 Normal 4 1 0 0 CTC (Clear Timer on Compare Match) Read Data Sheet for Other Modes Schematic Diagram:
  • 54. Lab 8: Counter Mode Programming with Arduino Page 54 Sketch for Delay and Event Counting (Frequency Checker): Lab Task: Heart pulses of a patient, in the form of square wave are reaching at Pin T1 (PD5) (Arduino PIN No. 5) of Arduino UNO Board. Write a program to measure the current pulse rate per minute of that patient after each 20 seconds and send this answer via serial port to Computer. void setup() { Serial.begin(9600); pinMode(5,INPUT_PULLUP); // Set Pin No.5 (T1 Pin) as input } void loop(){ TCNT1 = 0x0000; // Start counting from 0 TCCR1A = 0x00; // 16-bit counter, Normal Mode TCCR1B = 0x06; // Start Counting at // Falling Edge using T1 pin // For Rising Edge put 0x07 delay(1000); // delay of One Second TCCR1B = 0x00; // Stop Counting Serial.print("Input Frequency = "); Serial.print(TCNT1); Serial.print(" Hz "); Serial.print("Time Period = "); float tp = 1000.0F / TCNT1; Serial.print(tp); Serial.println(" ms"); }
  • 55. Lab 8: Counter Mode Programming with Arduino Page 55 Lab 8 Task Solution:
  • 56. Lab No. 9: Interrupt Programming with Arduino Page 56 International Islamic University Islamabad Faculty of Engineering and Technology Department of Electrical Engineering MICROPROCESSORS AND MICROCONTROLLER LAB Lab 9 : Interrupt Programming with Arduino Name: Reg. No: Date of Experiment: OBE Rubrics Evaluation a) PSYCHOMOTOR (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 1 Practical Implementation/ Arrangement of Equipment 0 1.25 2.5 3.75 5 Absent With several critical errors, incomplete and not neat With few errors, incomplete and not neat With some errors, complete but not neat Without errors, complete and neat 2 Use of Equipment or Simulation/ Programming Tool 0 0.5 1 1.5 2 Absent Limited competence Some competence Considerable competence Competence (b) COGNITIVE (To be judged on the copy of experiment submitted) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 3 Algorithm Design or Data Record, Analysis and Evaluation 0 0.25 0.5 0.75 1 Absent Incorrect Complete with some errors Complete with few errors Complete and Accurate (c) AFFECTIVE (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 4 Level of Participation & Attitude to Achieve Individual/Group Goals 0 0.5 1 1.5 2 Absent Rare sensible interaction Some sensible interaction Good sensible interaction Encouraging sensible interaction 5 Total Marks Obtained (Out of 10):
  • 57. Lab No. 9: Interrupt Programming with Arduino Page 57 Objectives:  To learn the difference between polling and interrupt based programming.  To use the timer interrupt.  To use external hardware interrupt. Introduction: There are two methods by which a microcontroller can serve a device.  Interrupt: In interrupt method, a device sends an interrupt signal to microcontroller. Upon reception of interrupt, microcontroller stops its working and serves the device. Program executed after receiving an interrupt is called Interrupt Service Routine (ISR).  Polling: In polling, microcontroller continuously monitors the status of device, if the status is met, microcontroller serves the device. In polling method, microcontroller can only check single device at a time. Interrupt Vector Table in ATmega328P: Sr.No. Interrupt Vector Name Address (in Hex) 1 Reset 0000 2 External Interrupt Request 0 INT0_vect 0002 3 External Interrupt Request 1 INT1_vect 0004 4 Pin Change Interrupt Request 0 PCINT0_vect 0006 5 Pin Change Interrupt Request 1 PCINT1_vect 0008 6 Pin Change Interrupt Request 2 PCINT2_vect 000A 7 Watchdog Time-out Interrupt WDT_vect 000C 8 Timer/Counter2 Compare Match A TIMER2_COMPA_vect 000E 9 Timer/Counter2 Compare Match B TIMER2_COMPB_vect 0010 10 Timer/Counter2 Overflow TIMER2_OVF_vect 0012 11 Timer/Counter1 Capture Event TIMER1_CAPT_vect 0014 12 Timer/Counter1 Compare Match A TIMER1_COMPA_vect 0016 13 Timer/Counter1 Compare Match B TIMER1_COMPB_vect 0018 14 Timer/Counter1 Overflow TIMER1_OVF_vect 001A 15 Timer/Counter0 Compare Match A TIMER0_COMPA_vect 001C 16 Timer/Counter0 Compare Match B TIMER0_COMPB_vect 001E 17 Timer/Counter0 Overflow TIMER0_OVF_vect 0020 18 SPI Serial Transfer Complete SPI_STC_vect 0022 19 USART Rx Complete USART_RX_vect 0024 20 USART Data Register Empty USART_UDRE_vect 0026 21 USART Tx Complete USART_TX_vect 0028 22 ADC Conversion Complete ADC_vect 002A
  • 58. Lab No. 11: Bluetooth Programming with Arduino Page 58 Sr.No. Interrupt Vector Name Address (in Hex) 23 EEPROM ready EE_READY_vect 002C 24 Analog Comparator ANALOG_COMP_vect 002E 25 Two-wire Serial Interface TWI_vect 0030 26 Store Program Memory Read SPM_READY_vect 0032 The above table shows the interrupt sources and their interrupt vectors for AVR ATmega328P. Memory locations from 0002 to 0032 locations are reserve for interrupt vectors. Each interrupt has 2 words (4 bytes) of memory space for its ISR. For example, 0012 to 0013 memory space is set aside for Timer2 Overflow ISR. Usually ISR cannot fit into 4-bytes memory space. So a JMP instruction is kept at the vector address from where ISR jumps to another location where rest of the code of ISR can be written. At the end of each ISR, RETI (Return from Interrupt) instruction is placed which gives the control back to the location from where it was interrupted. Steps to enable an Interrupt: To enable any interrupt of AVR, we need to take the following steps: a) Bit D7 (I) of SREG (Status Register) must be set in order to enable the global interrupt. Without enabling global interrupt, no interrupt can happen. This can be done by using SEI (assembly instruction) or sei(); (C instruction). b) After enabling global interrupt, by setting the IE (Interrupt Enable) bit of each interrupt, that specific interrupt can be enabled. For example, to enable Timer0 overflow interrupt, we need to set TOIE0 (Bit0 of TIMSK0 Register). When interrupt is executed, Bit D7 of SREG is cleared by the microcontroller to avoid the occurrence of another interrupt. Moreover, if Timer0 Overflow interrupt is enabled, TOV0 (Timer0 Overflow flag) is automatically cleared when microcontroller jumps to the Timer0 Overflow Interrupt Vector Table. TIMER INTERRUPTS:  Timer Interrupt Flag Registers (TIFRn) holds Overflow flag and Compare Match flag bits related to timers.  Timer Interrupt Mask Registers (TIMSKn) hold the different interrupt enable bits related to timers. - - - - - OCF0B OCF0A TOV0 TIFR0 TIMSK0 - - - - - OCIE0B OCIE0A TOI0E - - ICF1 - - OCF1B OCF1A TOV1 TIFR1 TIMSK1 - - ICIE - - OCIE1B OCIE1A TOI1E - - - - - OCF2B OCF2A TOV2 TIFR2 TIMSK2 - - - - - OCIE2B OCIE2A TOI2E EXTERNAL HARDWARE INTERRUPTS: There are two external hardware interrupts are INT0 and INT1 located on pins PD2 and PD3 respectively. These are enabled and disabled by External Interrupt Mask Register (EIMSK)
  • 59. Lab No. 11: Bluetooth Programming with Arduino Page 59 EIMSK - - - - - - INT1 INT0 INT0 External hardware interrupt request 0 enable INT1 External hardware interrupt request 1 enable Schematic: We can set external interrupt as Edge Triggered or Level Triggered using External Interrupt Control Register A (EICRA). EICRA - - - - ISC11 ISC10 ISC01 ISC00 ISCx1 ISCx0 0 0 Low Level Triggered 0 1 Rising and Falling Edge Triggered 1 0 Falling Edge Triggered 1 0 Rising Edge Triggered INT1 INT0
  • 60. Lab No. 11: Bluetooth Programming with Arduino Page 60 Sketch for Timer difference calculator using Two External Interrupts: Lab Task: Two IR Sensors at distance of 1 meter are placed on a road. Sensor0 is connected to INT0 interrupt pin and Sensor1 is connected to INT1 interrupt pin. A moving car crosses the Sensor0 first and then Sensor1. Calculate the time difference between two sensors detection and then the speed of that Car in Kilometer per Hour Units. Send these two answers via serial port to PC. // Calculates Timer Difference between two External Interrupts unsigned long t1 = 0; unsigned long t2 = 0; unsigned long t3 = 0; void setup() { Serial.begin(9600); DDRD = DDRD & 0b11110011; // Set PD2, PD3 as input pins PORTD = PORTD | 0b00001100; // Enable Pull Ups on PD2 and PD3 EIMSK = EIMSK | 0b00000011; // Enable external Inter. INT0 INT1 EICRA = 0b00001010; // INT0, INT1 is Falling Edge Trig. SREG = SREG | (1 << 7); // Enable Global Interrupts } void loop(){ } ISR(INT0_vect) { // ISR for external interrupt 0 t1 = millis(); // Arduino Pin } ISR(INT1_vect){ // ISR for external interrupt 1 t2 = millis(); t3 = t2 - t1; Serial.print("Time Difference = "); Serial.print(t3); Serial.println(" mili seconds."); }
  • 61. Lab No. 11: Bluetooth Programming with Arduino Page 61 Lab 9 Task Solution:
  • 62. Lab No. 10: Serial Port Programming with Arduino Page 62 International Islamic University Islamabad Faculty of Engineering and Technology Department of Electrical Engineering MICROPROCESSORS AND MICROCONTROLLER LAB Lab 10 : Serial Port Programming with Arduino Name: Reg. No: Date of Experiment: OBE Rubrics Evaluation a) PSYCHOMOTOR (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 1 Practical Implementation/ Arrangement of Equipment 0 1.25 2.5 3.75 5 Absent With several critical errors, incomplete and not neat With few errors, incomplete and not neat With some errors, complete but not neat Without errors, complete and neat 2 Use of Equipment or Simulation/ Programming Tool 0 0.5 1 1.5 2 Absent Limited competence Some competence Considerable competence Competence (b) COGNITIVE (To be judged on the copy of experiment submitted) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 3 Algorithm Design or Data Record, Analysis and Evaluation 0 0.25 0.5 0.75 1 Absent Incorrect Complete with some errors Complete with few errors Complete and Accurate (c) AFFECTIVE (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 4 Level of Participation & Attitude to Achieve Individual/Group Goals 0 0.5 1 1.5 2 Absent Rare sensible interaction Some sensible interaction Good sensible interaction Encouraging sensible interaction 5 Total Marks Obtained (Out of 10):
  • 63. Lab No. 10: Serial Port Programming with Arduino Page 63 Objectives:  To interface the serial port of PC with USART of AVR  To learn that how to program the USART (Universal Synchronous Asynchronous Receiver / Transmitter) of AVR to transmit & receive asynchronously Introduction: AVR has a built in USART (Universal Synchronous Asynchronous Receiver and Transmitter). We are using asynchronous communication for serial data transfer. Baud Rate is the data transfer rate, normally we prefer to use 9600 baud rate. So USART sends Start Bit first then 8 Data bits and then a Stop Bit as shown below. Serial Functions: i. Serial is a serial port object. It is used to access first serial port of Arduino. ii. Serial.begin(baud) Sets the data rate in bits per second (baud) for serial data transmission. An optional second argument configures the data, parity, and stop bits. The default is 8 data bits, no parity and one stop bit. It returns nothing.  Serial.begin(9600); // opens serial port, // sets data rate to 9600 bps  Serial.begin(9600,SERIAL_8N1); // 9600 baud rate, 8-bit data, // No Parity, 1 Stop Bit iii. Serial.available()Gets the number of bytes (characters) available for reading from the serial port. This is data that’s already arrived and stored in the serial receive buffer (which holds 64 bytes). So it returns the number of bytes available to read.  if (Serial.available()){ int inByte = Serial.read(); } // if receive buffer has some data then read first byte. iv. Serial.read()Reads data from serial receive buffer and returns the first byte of incoming serial data available (or -1 if no data is available) v. Serial.println(val) Prints data to the serial port as human-readable ASCII text followed by a carriage return character (ASCII 13, or 'r') and a newline character (ASCII 10, or 'n'). This command takes the same forms as Serial.print() Input Argument: val is any data type as input argument. Return Type: It returns the number of byes written to serial port int analogValue = 100;  Serial.println(analogValue); // print as an ASCII-encoded decimal  Serial.println(analogValue, DEC); // print as an ASCII-encoded decimal  Serial.println(analogValue, HEX); // print as an ASCII-enc hexadecimal
  • 64. Lab No. 11: Bluetooth Programming with Arduino Page 64  Serial.println(analogValue, OCT); // print as an ASCII-encoded octal  Serial.println(analogValue, BIN); // print as an ASCII-encoded binary  Serial.println("Hello World"); // prints “Hello Worldrn” vi. Serial.write() Writes binary data to the serial port. This data is sent as a byte or series of bytes. Note: to send the characters representing the digits of a number use the print() function instead. Syntax:Serial.write(val) Serial.write(str) Serial.write(buf, len) Parameters : val: a value to send as a single byte str: a string to send as a series of bytes buf: an array to send as a series of bytes len: the number of bytes to be sent from the array Returns: it returns size_t, the number of bytes written.  Serial.write(45); // send a byte with the value 45  int bytesSent = Serial.write("hello"); // sends the string “hello” // and returns the length of the string. Notes and Warnings: Serial transmission is asynchronous in Arduino IDE 1.0.  If there is enough empty space in the transmit buffer, Serial.write() will return before any characters are transmitted over serial.  If the transmit buffer is full then Serial.write() will block until there is enough space in the buffer.  To avoid blocking calls to Serial.write(), you can first check the amount of free space in the transmit buffer using availableForWrite(). Schematic:
  • 65. Lab No. 11: Bluetooth Programming with Arduino Page 65 Sketch: Next program turns ON/OFF built in LED based on commands given in the form of string. void setup() { DDRB |= (1<<5); // Set PB5(LED PIN) as Output Pin PORTB |= 1<<5 ; // Turn OFF Relay Switch Serial.begin(9600, SERIAL_8N1); // 9600 baud rate, 8 data bit // No Parity, 1 Stop Bit } void loop(){ if (Serial.available()) { // if some bytes have received int inByte = Serial.read(); // read first byte switch(inByte) { case'0': // if received byte is '0' = 0x30 PORTB |= (1<<5); // Turn OFF Relay Switch Serial.println("0 - Relay Switch is OFF Now"); break; case'1': // if received byte is '1' = 0x31 PORTB = ~(1<<5); // Turn ON Relay Switch Serial.println("1 - Relay Switch is ON Now"); break; case'2': // if received byte is '2' = 0x32 if(PORTB &(1<<5)) Serial.println("2 - Relay Switch Status = OFF"); else Serial.println("2 - Relay Switch Status = ON"); break; case'n': Serial.println("I Got n"); break; case'r': Serial.println("I Got r"); break; default: // if received byte is defferent Serial.write(inByte); Serial.println(" - is Unrecognized Command"); } } }
  • 66. Lab No. 11: Bluetooth Programming with Arduino Page 66 Lab Task: An LED is connected to Arduino Pin No.13(PB5). Write a Program that that receives a String serially and acts according to following table. Received String Action to Perform FAN ON Turns ON Relay Switch FAN OFF Turns OFF Relay Switch STATUS Shows message “FAN is ON” or “FAN is OFF” depending on Relay Status Any other string Shows message “Invalid Command” String cmd; String cmd_on = "on", cmd_off = "off", cmd_status = "status"; void setup() { pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, LOW); Serial.begin(9600, SERIAL_8N1); // 9600 baud rate, 8 data bit // No Parity, 1 Stop Bit } void loop(){ if (Serial.available()) { // if some bytes have received cmd = Serial.readString(); // read the whole string if( cmd == cmd_on){ Serial.println("Turning ON LED"); digitalWrite(LED_BUILTIN, HIGH); } else if( cmd == cmd_off){ Serial.println("Tuurning OFF LED"); digitalWrite(LED_BUILTIN, LOW); } else if( cmd == cmd_status){ if(digitalRead(LED_BUILTIN)) Serial.println("LED is ON"); else Serial.println("LED is OFF"); } else{ Serial.print(cmd); Serial.println(" Command is Invalid"); } } }
  • 67. Lab No. 11: Bluetooth Programming with Arduino Page 67 Lab 10 Task Solution:
  • 68. Lab No. 11: Bluetooth Programming with Arduino Page 68 International Islamic University Islamabad Faculty of Engineering and Technology Department of Electrical Engineering MICROPROCESSORS AND MICROCONTROLLER LAB Lab 11 : Bluetooth Programming with Arduino Name: Reg. No: Date of Experiment: OBE Rubrics Evaluation a) PSYCHOMOTOR (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 1 Practical Implementation/ Arrangement of Equipment 0 1.25 2.5 3.75 5 Absent With several critical errors, incomplete and not neat With few errors, incomplete and not neat With some errors, complete but not neat Without errors, complete and neat 2 Use of Equipment or Simulation/ Programming Tool 0 0.5 1 1.5 2 Absent Limited competence Some competence Considerable competence Competence (b) COGNITIVE (To be judged on the copy of experiment submitted) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 3 Algorithm Design or Data Record, Analysis and Evaluation 0 0.25 0.5 0.75 1 Absent Incorrect Complete with some errors Complete with few errors Complete and Accurate (c) AFFECTIVE (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 4 Level of Participation & Attitude to Achieve Individual/Group Goals 0 0.5 1 1.5 2 Absent Rare sensible interaction Some sensible interaction Good sensible interaction Encouraging sensible interaction 5 Total Marks Obtained (Out of 10):
  • 69. Lab No. 11: Bluetooth Programming with Arduino Page 69 Objectives:  To interface the Bluetooth Module with USART of AVR  To communicate with Mobile App “Bluetooth Buddy” using HC-05 / HC-06 Bluetooth Module. Specifications: Parameter JDY-31 HC-05 HC-06 Working frequency band 2.4 GHz 2.4 GHz 2.4 GHz Bluetooth Version V3.0 SPP V2.0+EDR V2.0+EDR Communication interface UART 3.3V TTL level UART 3.3V TTL level UART 3.3V TTL level Working voltage 3.6~6V 3.6~3.6V 3.6~6V Communication level 3.3V 3.3V 3.3V Transmit power (Max) 8 dBm 6 dBm 6 dBm Receive sensitivity -97dBm -85dBm -85dBm Transmission distance 30 meters 10 meters 10 meters Maximum throughput 128 Kbps 450 Kbps 1350 Kbps Antenna interface built-in PCB antenna built-in PCB antenna built-in PCB antenna Current in Pairing 4.7mA 30~40 mA 30~40 mA Communication current 7.3 mA 20 mA 20 mA Module size 27x13 mm 27x13 mm 27x13 mm Default Baud Rate 9600 38400 9600 Default Password 1234 1234 1234 Master-slave support Slave Master / Slave Slave JDY- 31
  • 70. Lab No. 11: Bluetooth Programming with Arduino Page 70 HC-05 HC-06 HC-05 Connection with Arduino HC-05 Connection with Arduino It can act as both master and slave It functions only as slave Continuously Press button on Bluetooth then Concoct USB Cable with Arduino and PC. Release Button after two Seconds Now LED on Bluetooth device will Switch ON and OFF after two Seconds it means it is in AT command mode. It does not have button. If it not connected to other Bluetooth device then it is in AT Command Mode LED is Fast blinking  It is searching for Paired Device LED is Fast blinking  It is searching for Paired Device No Blinking  It is now connected to a paired device No Blinking  It is now connected to a paired device Arduino Serial Monitor: Select 38400 Baud rate and “Both NL & CR” option Arduino Serial Monitor: Select 9600 Baud rate and “No line ending” option.
  • 71. Lab No. 11: Bluetooth Programming with Arduino Page 71 Circuit for AT Commands Circuit for Bluetooth Communication
  • 72. Lab No. 11: Bluetooth Programming with Arduino Page 72 HC-05 AT Commands Command Reply Purpose AT OK Write in all commands in Capital Letters AT+VERSION? +VERSION:4.0- 20190815 Firmware version. AT+ADDR? +ADDR:0019:10:08C65E See MAC Address AT+NAME? +NAME:HC-05 See Device Name AT+NAME=LAB OK Change name to LAB AT+PIN? 1234 Shows Bluetooth Password AT+PIN=0000 OK Set 0000 as Bluetooth Password AT+UART? +UART:9600,0,0 What is baud rate AT+UART=57600,1,0 OK Baud =57600, 1 stop bit, 0 parity AT+UART=115200,1, 0 OK Baud =115200,1 stop bit,0 parity Other Baud Rates: 4800, 9600, 19200, 38400, 230400, 230400, 460800, 921600, 1382400 AT+ROLE? 0=Salve, 1=Master AT+ROLE=0 OK Sets in Slave Mode AT+ROLE=1 OK Sets in Master Mode AT+RESET Reset and save changes. HC-06 AT Commands Command Reply Purpose AT OK Write in all commands in Capital Letters AT+VERSION OKlinvorV1.8 Firmware version. AT+NAMELAB10 OKsetname Sets the modules name to “LAB10” AT+PIN1234 OKsetPIN Set the PIN to 1234 AT+BAUD1 OK1200 Sets the baud rate to 1200 AT+BAUD2 OK2400 Sets the baud rate to 2400 AT+BAUD3 OK4800 Sets the baud rate to 4800 AT+BAUD4 OK9600 Sets the baud rate to 9600 AT+BAUD5 OK19200 Sets the baud rate to 19200 AT+BAUD6 OK38400 Sets the baud rate to 38400 AT+BAUD7 OK57600 Sets the baud rate to 57600 AT+BAUD8 OK115200 Sets the baud rate to 115200 AT+BAUD9 OK230400 Sets the baud rate to 230400 AT+BAUDA OK460800 Sets the baud rate to 460800 AT+BAUDB OK921600 Sets the baud rate to 921600 AT+BAUDC OK1382400 Sets the baud rate to 1382400
  • 73. Lab No. 11: Bluetooth Programming with Arduino Page 73 JDY-31 AT Commands Command Reply Purpose AT No Response Write in all commands in Capital Letters AT+VERSION +VERSION=JDY-31- V1.35,Bluetooth V3.0 Firmware version. AT+LADDR +LADDR=7E2904147447 Shows MAC address AT+NAMELAB10 +OK Sets the modules name to “LAB10” AT+PIN1234 +OK Set the PIN to 1234 AT+BAUD1 +OK Sets the baud rate to 1200 AT+BAUD2 +OK Sets the baud rate to 2400 AT+BAUD3 +OK Sets the baud rate to 4800 AT+BAUD4 +OK Sets the baud rate to 9600 AT+BAUD5 +OK Sets the baud rate to 19200 AT+BAUD6 +OK Sets the baud rate to 38400 AT+BAUD7 +OK Sets the baud rate to 57600 AT+BAUD8 +OK Sets the baud rate to 115200 AT+BAUD9 +OK Sets the baud rate to 128000  JDY-31 is in AT mode by default until a Bluetooth connection is established.  JDY-31 default rate is 9600 BAUD, 0-stop bits, 0-parity, using both carriage return and new line ending (rn).  JDY-31 has NO RESPONSE to an empty AT command. You should, however, get a response to "AT+VERSION"  Try other BAUD rates if 9600 does not work.  Now its LED on Bluetooth device will Switch ON and OFF after 1 Seconds > it means it is in Searching Mode.  No Blinking > It is now connected to a paired device Now go to google play store from your android phone and search “Bluetooth Buddy”. Download and install this app in your mobile phone. Turn on Bluetooth Search and Add HC-05 or HC-06 Device to your mobile. Arduino Sketch for AT Commands void setup() { } void loop(){ }
  • 74. Lab No. 11: Bluetooth Programming with Arduino Page 74 Arduino Sketch for Bluetooth Communication Lab Task: Download and install "Bluetooth Buddy” app from google play store to your android phone. Make two buttons in this app. Pressing “ON” button should turn ON LED and while pressing OFF Button it should turn OFF LED. String cmd; String cmd_on = "on"; String cmd_off = "off"; String cmd_status = "status"; void setup() { pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, LOW); Serial.begin(9600, SERIAL_8N1); // 9600 baud rate, 8 data bit // No Parity, 1 Stop Bit } void loop(){ if (Serial.available()) { // if some bytes have received cmd = Serial.readString(); // read the whole string if( cmd == cmd_on){ Serial.println("Turning ON LED"); digitalWrite(LED_BUILTIN, HIGH); } else if( cmd == cmd_off){ Serial.println("Tuurning OFF LED"); digitalWrite(LED_BUILTIN, LOW); } else if( cmd == cmd_status){ if(digitalRead(LED_BUILTIN)) Serial.println("LED is ON"); else Serial.println("LED is OFF"); } else{ Serial.print(cmd); Serial.println(" Command is Invalid"); } } }
  • 75. Lab No. 11: Bluetooth Programming with Arduino Page 75 Lab 11 Task Solution:
  • 76. Lab No. 12: ADC Programming with Arduino Page 76 International Islamic University Islamabad Faculty of Engineering and Technology Department of Electrical Engineering MICROPROCESSORS AND MICROCONTROLLER LAB Lab 12 : ADC Programming with Arduino Name: Reg. No: Date of Experiment: OBE Rubrics Evaluation a) PSYCHOMOTOR (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 1 Practical Implementation/ Arrangement of Equipment 0 1.25 2.5 3.75 5 Absent With several critical errors, incomplete and not neat With few errors, incomplete and not neat With some errors, complete but not neat Without errors, complete and neat 2 Use of Equipment or Simulation/ Programming Tool 0 0.5 1 1.5 2 Absent Limited competence Some competence Considerable competence Competence (b) COGNITIVE (To be judged on the copy of experiment submitted) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 3 Algorithm Design or Data Record, Analysis and Evaluation 0 0.25 0.5 0.75 1 Absent Incorrect Complete with some errors Complete with few errors Complete and Accurate (c) AFFECTIVE (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 4 Level of Participation & Attitude to Achieve Individual/Group Goals 0 0.5 1 1.5 2 Absent Rare sensible interaction Some sensible interaction Good sensible interaction Encouraging sensible interaction 5 Total Marks Obtained (Out of 10):
  • 77. Lab No. 12: ADC Programming with Arduino Page 77 Objectives:  To program and use the ADC feature of ATmega328  Show 10 bit value of ADC on Serial Port. Introduction: ADC is used to convert the analog voltages into digital value. ADC is widely used in data acquisition so most of the modern microcontrollers have on-chip ADC peripheral. Arduino UNO has on-chip ADC of 10-bit resolution. It has 6 analog input channels. As the ADC is 10-bit, so the converted digital output is stored in two 8-bit registers ADCL and ADCH. Reference voltages for ADC can be connected to AVCC (Analog Vcc), internal 1.1V reference or external AREF pin. Minimum 0V and maximum Vcc can be converted to a digital value. In ADC, Successive approximation method is used to convert analog voltage into digital value. This circuitry requires a clock frequency between 50 kHz to 100 kHz. Important Registers Associated with ADC: Following registers are associated with the ADC of AVR: ADCL Has 8 LSBs of converted digital result ADCH Has 2 MSBs of converted digital result ADMUX For left / right adjusted result, reference voltage and channel selection ADCSRA ADC control and status register Single ended result can be found from following formula: 𝐴𝐷𝐶 = 𝑉𝑖𝑛 × 1024 𝑉𝑟𝑒𝑓 Where Vin is the voltage on the selected input channel, Vref the selected voltage reference and ADC is the 10-bit converted digital decimal value. ADMUX Register: Bit # 7 6 5 4 3 2 1 0 Bit Name REFS1 REFS0 ADLAR MUX4 MUX3 MUX2 MUX1 MUX0 REF1 REF1 Voltage Reference Selection 0 0 AREF Pin Set Externally 0 1 AVCC Pin Same as VCC 1 0 (Reserved) 1 1 Internal 1.1V Fixed Regardless of VCC value ADLAR = 0  Right Adjust the Result ADCH ADCL 0 0 0 0 0 0 ADC9 ADC8 ADC7 ADC6 ADC5 ADC4 ADC3 ADC2 ADC1 ADC0 ADLAR = 1  Left Adjust the Result ADCH ADCL ADC9 ADC8 ADC7 ADC6 ADC5 ADC4 ADC3 ADC2 ADC1 ADC0 0 0 0 0 0 0
  • 78. Lab No. 12: ADC Programming with Arduino Page 78 Analog Channel Selection Bits MUX3… 0 Input MUX3…0 Input 0000 ADC0 1000 ADC8(1) 0001 ADC1 1001 (Reserved) 0010 ADC2 1010 (Reserved) 0011 ADC3 1011 (Reserved) 0100 ADC4 1100 (Reserved) 0101 ADC5 1101 (Reserved) 0110 ADC6 1110 1.1 V (VBG) 0111 ADC7 1111 0 V (GND) Note: 1. For Temperature Sensor. ADCSRA Register: Bit # 7 6 5 4 3 2 1 0 Bit Name ADEN ADSC ADATE ADIF ADIE ADPS2 ADPS1 ADPS0 ADEN (Bit 7) ADC Enable: 1 = ADC is enabled 0 = ADC is disabled ADSC (Bit 6) ADC Start Conversion: Write this bit to 1 to start each conversion. ADATE (Bit 5) ADC Auto Trigger Enable: Auto Triggering of the ADC is enabled when this bit is set to 1. ADIF (Bit 4) ADC Interrupt Flag: This bit is set when an ADC conversion completes and the Data Registers are updated. ADIE (Bit 3) ADC Interrupt Enable: Writing this bit to 1 enables the ADC Conversion Complete Interrupt. ADPS2:0 (Bits 2:0) ADC Prescaler Select Bits: These bits determine the division factor between the XTAL frequency and the input clock to the ADC ADPS2 ADPS1 ADPS0 Division Factor 0 0 0 2 0 0 1 2 0 1 0 4 0 1 1 8 1 0 0 16
  • 79. Lab No. 12: ADC Programming with Arduino Page 79 1 0 1 32 1 1 0 64 1 1 1 128 Schematic: Sketch: #define STEP_SIZE 5/1024 int ADC_Read(byte An) { DDRC = 0x00; // make Port C an input for ADC input ADCSRA = 0x87; // Enable ADC and select CLK/128 ADMUX = 0x40 | An; // 5V Vref, Select ADCn, right-justified ADCSRA|=(1<<ADSC); // start conversion while(( ADCSRA & (1<< ADIF ))==0); // wait for conversion to finish ADCSRA |= (1<<ADIF); // Clear ADIF Flag return ADC; // return ADC Value } void setup() { Serial.begin(9600); // use 9600 bits per second } void loop() { int A0 = ADC_Read(0); // Read Channel 0 Serial.print("ADC = "); Serial.print(A0); // Send ADC Value Serially Serial.print(" Vin = "); Serial.println(float(ADC) * STEP_SIZE); // Show input Volts delay(1000); }
  • 80. Lab No. 12: ADC Programming with Arduino Page 80 Lab Task: An LM35 temperature sensor is connected to ADC A0 Pin. Write a Program to read analog value of LM35 convert it to Centigrade and Send it to serial port. Use 1.1V Vref and CLK/128 Prescalar.
  • 81. Lab No. 12: ADC Programming with Arduino Page 81 Lab 12 Task Solution:
  • 82. Lab No. 13: SPI Protocol Programming with Arduino Page 82 International Islamic University Islamabad Faculty of Engineering and Technology Department of Electrical Engineering MICROPROCESSORS AND MICROCONTROLLER LAB Lab 13 : SPI Protocol Programming with Arduino Name: Reg. No: Date of Experiment: OBE Rubrics Evaluation a) PSYCHOMOTOR (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 1 Practical Implementation/ Arrangement of Equipment 0 1.25 2.5 3.75 5 Absent With several critical errors, incomplete and not neat With few errors, incomplete and not neat With some errors, complete but not neat Without errors, complete and neat 2 Use of Equipment or Simulation/ Programming Tool 0 0.5 1 1.5 2 Absent Limited competence Some competence Considerable competence Competence (b) COGNITIVE (To be judged on the copy of experiment submitted) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 3 Algorithm Design or Data Record, Analysis and Evaluation 0 0.25 0.5 0.75 1 Absent Incorrect Complete with some errors Complete with few errors Complete and Accurate (c) AFFECTIVE (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 4 Level of Participation & Attitude to Achieve Individual/Group Goals 0 0.5 1 1.5 2 Absent Rare sensible interaction Some sensible interaction Good sensible interaction Encouraging sensible interaction 5 Total Marks Obtained (Out of 10):
  • 83. Lab No. 13: SPI Protocol Programming with Arduino Page 83 Objective:  To set up and use the on-chip Serial Peripheral Interface (SPI) of the Arduino Board. Serial Peripheral Interface (SPI) Overview: A Serial Peripheral Interface (SPI) bus is a system for serial communication, which uses up to four conductors, commonly three. One conductor is used for data receiving, one for data sending, one for synchronization and one alternatively for selecting a device to communicate with. It is a full duplex connection, which means that the data is sent and received simultaneously. The maximum baud rate is higher than that in the I2C communication system. The SPI allows high-speed synchronous data transfer between the AVR and peripheral devices or between several AVR devices. On most parts the SPI has a second purpose where it is used for In System Programming (ISP). The interconnection between two SPI devices always happens between a master device and a slave device. Compared to some peripheral devices like sensors, which can only run in slave mode, the SPI of the AVR can be configured for both master and slave mode. The mode the AVR is running in is specified by the settings of the master bit (MSTR) in the SPI control register (SPCR). Special considerations about the SS pin must be considered for Multi Slave Systems. The master is the active part in this system and must provide the clock signal a serial data transmission is based on. The slave is not capable of generating the clock signal and thus cannot get active on its own. The slave just sends and receives data, if the master generates the necessary clock signal. The master, however, generates the clock signal only while sending data. That means the master must send data to the slave to read data from the slave. SPI uses the following four wires − 1. SCK − This is the serial clock driven by the master. 2. MOSI − This is the master output / slave input driven by the master. 3. MISO − This is the master input / slave output driven by the master. 4. SS − This is the slave-selection wire.
  • 84. Lab No. 13: SPI Protocol Programming with Arduino Page 84 The following functions are used. You have to include the SPI.h. i. SPI.begin() − Initializes the SPI bus by setting SCK, MOSI, and SS to outputs, pulling SCK and MOSI low, and SS high. ii. SPI.setClockDivider(divider) − To set the SPI clock divider relative to the system clock. On AVR based boards, the dividers available are 2, 4, 8, 16, 32, 64 or 128. The default setting is SPI_CLOCK_DIV4, which sets the SPI clock to one-quarter of the frequency of the system clock (5 Mhz for the boards at 20 MHz). iii. Divider − It could be (SPI_CLOCK_DIV2, SPI_CLOCK_DIV4, SPI_CLOCK_DIV8, SPI_CLOCK_DIV16, SPI_CLOCK_DIV32, SPI_CLOCK_DIV64, SPI_CLOCK_DIV128). iv. SPI.transfer(val) − SPI transfer is based on a simultaneous send and receive: the received data is returned in receivedVal. v. SPI.beginTransaction(SPISettings(speedMaximum, dataOrder, dataMode)) − speedMaximum is the clock, dataOrder(MSBFIRST or LSBFIRST), dataMode(SPI_MODE0, SPI_MODE1, SPI_MODE2, or SPI_MODE3). vi. SPI.attachInterrupt(handler) − Function to be called when a slave device receives data from the master. We have four modes of operation in SPI as follows – a. Mode 0 (the default) − Clock is normally low (CPOL = 0), and the data is sampled on the transition from low to high (leading edge) (CPHA = 0). b. Mode 1 − Clock is normally low (CPOL = 0), and the data is sampled on the transition from high to low (trailing edge) (CPHA = 1). c. Mode 2 − Clock is normally high (CPOL = 1), and the data is sampled on the transition from high to low (leading edge) (CPHA = 0). d. Mode 3 − Clock is normally high (CPOL = 1), and the data is sampled on the transition from low to high (trailing edge) (CPHA = 1). CPOL CPHA Data Read and Change Time SPI Mode 0 0 Read on Rising Edge, Changed on a Falling Edge 0 0 1 Read on Falling Edge, Changed on a Rising Edge 1 1 0 Read on Falling Edge, Changed on a Rising Edge 2 1 1 Read on Rising Edge, Changed on a Falling Edge 3
  • 85. Lab No. 13: SPI Protocol Programming with Arduino Page 85 AVR Registers  Control register: SPCR (SPI Control Register)  Status Register: SPSR (SPI Status Register)  Data Register: SPDR (SPI Data Register) SPSR Register: SPIF WCOL - - - - - SPI2X SPSR:  SPIF (SPI Interrupt Flag) A serial transfer is completed. The SS pin is driven low in slave mode WCOL (Write Collision) SPI2X (Double SPI Speed) SPCR Register: SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0 SPCR:  SPIE (SPI Interrupt Enable)  SPE (SPI Enable)  DORD (Data Order)  MSTR (Master)  CPOL (Clock Polarity)  CPHA (Clock Phase)  SPR1, SPR0 :SPI Clock Rate SPI2X SPR1 SPR0 SCK Freq. 0 0 0 Fosc/4 0 0 1 Fosc/16 0 1 0 Fosc/64 0 1 1 Fosc/128 1 0 0 Fosc/2 1 0 1 Fosc/8 1 1 0 Fosc/32 1 1 1 Fosc/64
  • 86. Lab No. 13: SPI Protocol Programming with Arduino Page 86 Now, we will connect two Arduino UNO boards together; one as a master and the other as a slave.  (SS) : pin 10  (MOSI) : pin 11  (MISO) : pin 12  (SCK) : pin 13 Programming for SPI Protocol: Sketch for Master: #define SCK 5 // Shift Clock is PB5 #define MISO 4 // Master In Slave Out is PB4 #define MOSI 3 // Master Out Slave In is PB3 #define SS 2 // Slave Select is PB2 void SPI_Begin(){ // Set MOSI, SCK and SS as Output Pins DDRB |= (1<<MOSI) | (1<<SCK) | (1<<SS) ; DDRB &= ~(1<<MISO); // Set MISO as an Input Pin // Enable SPI, Master mode, Shift Clock = CLK /16 SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0); PORTB &= ~(1<<SS); // Enable Slave Select Pin } byte SPI_Transfer(byte data){ SPDR = data; // Start transmission while(!(SPSR & (1<<SPIF))); // Wait for transmission complete return SPDR; } void setup(){ Serial.begin(9600); SPI_Begin(); Serial.println ("SPI Master"); } void loop(){ static byte R, S = 1; delay(1000); // Call One Sec delay R = SPI_Transfer(S); Serial.print ("Sent "); Serial.print (S,DEC); Serial.print (" Received "); Serial.println (R,DEC); S++; }
  • 87. Lab No. 13: SPI Protocol Programming with Arduino Page 87 Sketch for Slave : #define SCK 5 // Shift Clock is PB5 #define MISO 4 // Master In Slave Out is PB4 #define MOSI 3 // Master Out Slave In is PB3 #define SS 2 // Slave Select is PB2 void SPI_Begin_Slave(){ DDRB |= (1<<MISO); // Set MISO as an Output Pin // Set MOSI, SCK and SS as Input Pins DDRB &= ~(1<<MOSI) & ~(1<<SCK) & ~(1<<SS) ; SPCR = (1<<SPE); // Enable SPI as a Slave Device } byte SPI_Transfer(byte data){ SPDR = data; while(!(SPSR & (1<<SPIF))); // Wait for Reception complete return SPDR; // return the received data } void setup(){ Serial.begin(9600); SPI_Begin_Slave(); Serial.println ("SPI Slave"); } void loop(){ static byte R,S = 100; R = SPI_Transfer(S); Serial.print ("Sent "); Serial.print (S,DEC); Serial.print (" Received "); Serial.println (R,DEC); S++; }
  • 88. Lab No. 13: SPI Protocol Programming with Arduino Page 88 Schematic Diagram: Lab Task: SPI Master unit sends string “SPI is working” to slave unit. SPI Slave waits for data. SPI Slave receives the string and sends it to the serial terminal.
  • 89. Lab No. 13: SPI Protocol Programming with Arduino Page 89 Lab 13 Task Solution:
  • 90. Lab 14: I2C Protocol Programming with Arduino Page 90 International Islamic University Islamabad Faculty of Engineering and Technology Department of Electrical Engineering MICROPROCESSORS AND MICROCONTROLLER LAB Lab 14 : I2C Protocol Programming with Arduino Name: Reg. No: Date of Experiment: OBE Rubrics Evaluation a) PSYCHOMOTOR (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 1 Practical Implementation/ Arrangement of Equipment 0 1.25 2.5 3.75 5 Absent With several critical errors, incomplete and not neat With few errors, incomplete and not neat With some errors, complete but not neat Without errors, complete and neat 2 Use of Equipment or Simulation/ Programming Tool 0 0.5 1 1.5 2 Absent Limited competence Some competence Considerable competence Competence (b) COGNITIVE (To be judged on the copy of experiment submitted) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 3 Algorithm Design or Data Record, Analysis and Evaluation 0 0.25 0.5 0.75 1 Absent Incorrect Complete with some errors Complete with few errors Complete and Accurate (c) AFFECTIVE (To be judged in the field/lab during experiment) Sr. No. Criteria Level 1 (0%) Level 2 (25%) Level 3 (50%) Level 4 (75%) Level 5 (100%) Marks Obtained 4 Level of Participation & Attitude to Achieve Individual/Group Goals 0 0.5 1 1.5 2 Absent Rare sensible interaction Some sensible interaction Good sensible interaction Encouraging sensible interaction 5 Total Marks Obtained (Out of 10):
  • 91. Lab 14: I2C Protocol Programming with Arduino Page 91 Objective:  To program and use the TWI feature of AVR  To transmit a character from Master and receive at Slave using Arduino Introduction: The Two Wire Interface (TWI) protocol allows the systems designer to interconnect up to 128 different devices using only two bi-directional bus lines, one for clock (SCL) and one for data (SDA). An external pull-up resistor is required to be connected for both the TWI pins to keep the line in high state when these are not driven by any TWI device. All devices connected to the bus have individual addresses. In TWI protocol, there are built-in mechanisms to resolve the issues of bus contention. The ATmega16 TWI includes the following features:  Simple, powerful and flexible communication interface with only two bus lines  Master and Slave operation supported  Device can operate as transmitter and receiver  7-bit address space allows 128 different slave addresses  Multi-master arbitration support  Up to 400 kHz data transfer speed  Fully programmable slave address with general call support  Address recognition causes Wake-up when AVR is in Sleep Mode Following figure show the interconnection of different devices connected to Serial Data (SDA) and Serial Clock (SCL) pins. If none of device is driving the lines, pull-up resistors will keep the lines at Vcc potential. Following figure shows the condition for a valid data: