EEE342 MP Lab Manual

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 133

EEE342 Microprocessor Systems & Interfacing

Microprocessor Systems & Interfacing


EEE-342
Lab Manual

Name

Registration Number

Class

Instructor’s Name

COMSATS University Islamabad (CUI) , Islamabad Campus Page 1


EEE342 Microprocessor Systems & Interfacing

Introduction
This Lab Manual is for EEE-342 Microprocessor Systems and Interfacing course.
The labs constitute 25 % of the total marks for this course.

During the labs students will work in groups (no more than three students per
group). You are required to complete the ‘Pre-Lab’ section of the lab before coming
to the lab. You will be graded for this and the ‘In-Lab’ tasks during the in-lab viva.
You will complete the ‘Post-Lab’ section of each lab before coming to the next week’s
lab.

You are not allowed to wander in the lab or consult other groups when performing
experiments. Similarly the lab reports must contain original efforts. CUI has a zero
tolerance anti-plagiarism policy.

Apart from these weekly labs you will complete two projects. One mini-project that
will count towards your Lab Sessional II score and a Final Project which will be
graded as Lab Final Exam. The grading policy is already discussed in the Course
Description File.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 2


EEE342 Microprocessor Systems & Interfacing

Acknowledgement
The labs for EEE-342 Microprocessor Systems and Interfacing were designed by Dr.
Omar Ahmad. The manuals were prepared by Ms. Kiran Nadeem, Mr Raheel
Ahmed, Ms. Asma Ramay and Mr. Ali Raza Shahid. The first version was completed
in Session Spring 2016, The second version was completed during the summer
break of 2016. Typesetting and formatting of this version was supervised by Dr.
Omar Ahmad and was carried out by Mr. Abdul Rehman, Mr Suleman & Mr Baqir
Hussain. The third version was completed in September 2017 in which all the tasks
were updated from ATmega 16 to ATmega 328p microcontroller. The fourth version
was completed in February 2018 in which some lab manuals and lab tasks were
improved.

History of Revision
Version
and Date Team Comments
of Issue

This is the first editable draft of EEE – 342


lab manual. Labs were designed by Dr.
Version 1. Dr. Omar Ahmad Omar Ahmad and this manuscript was
May 2016 Ms. Kiran Nadeem prepared by Ms. Kiran Nadeem.
For comments and suggestions please
contact: omer_ahmed@comsats.edu.pk

Dr. Omar Ahmad This is the second editable draft of EEE –


Version 2.
Mr. Raheel Ahmed 342 lab manual. The manual was remodeled
September
Ms. Asma Ramay according to the new OBE format. Some of
2016
Mr. Ali Raza Shahid the labs were improved.

Version 3. Dr. Omar Ahmad This is the third editable draft of EEE – 342
September Ms. Asma Ramay lab manual. The manual was updated
2017 according to ATmega 328p microcontroller.
Version 4. Dr. Omar Ahmad This is the fourth editable draft of EEE – 342
February Ms. Asma Ramay lab manual. Some of the labs were improved.
2018 Lab tasks were modified and some new tasks
were added.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 3


EEE342 Microprocessor Systems & Interfacing

Safety Precautions
 Be calm and relaxed, while working in lab.

 First check your measuring equipment.

 When working with voltages over 40 V or current over 10 A , there must be at least two

people in the lab at all time.

 Keep the work area neat and clean.

 Be sure about the locations of fire extinguishers and first aid kit.

 No loose wires or metals pieces should be lying on the table or neat the circuit.

 Avoid using long wires, that may get in your way while making adjustments or changing

leads.

 Be aware of bracelets, rings, and metal watch bands (if you are wearing any of them). Do

not wear them near an energized circuit.

 When working with energize circuit use only one hand while keeping rest of your body

away from conducting surfaces.

 Always check your circuit connections before power it ON.

 Always connect connection from load to power supply.

 Never use any faulty or damage equipment and tools.

 If an individual comes in contact with a live electrical conductor.

o Do not touch the equipment, the cord, the person.

o Disconnect the power source from the circuit breaker and pull out the plug using

insulated material.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 4


EEE342 Microprocessor Systems & Interfacing

Table of Contents
Introduction .................................................................................................................................. 2
Acknowledgement ........................................................................................................................ 3
History of Revision ...................................................................................................................... 3
Safety Precautions ........................................................................................................................ 4
Lab # 01 Introduction to Development Tools and Lab Softwares ............................................... 8
Objectives ................................................................................................................................. 8
Pre Lab ..................................................................................................................................... 8
In-Lab ..................................................................................................................................... 11
Critical Analysis / Conclusion ............................................................................................... 21
Lab # 02 Introduction to AVR Microcontroller Hardware Circuitry and Digital I/O Ports ..... 22
Objectives: .............................................................................................................................. 22
Pre-Lab ................................................................................................................................... 22
Pre lab Task: ........................................................................................................................... 26
In Lab: .................................................................................................................................... 27
Critical Analysis / Conclusion ............................................................................................... 29
Lab # 03 Interfacing 7-Segment Display Using Digital I/O Ports ............................................. 30
Objectives: .............................................................................................................................. 30
Pre-Lab ................................................................................................................................... 30
Pre-Lab Task: ......................................................................................................................... 32
In Lab: .................................................................................................................................... 33
Post lab task:........................................................................................................................... 36
Critical Analysis / Conclusion ............................................................................................... 37
Lab # 04 LCD Interfacing with AVR Microcontroller .............................................................. 38
Objectives: .............................................................................................................................. 38
Pre-Lab ................................................................................................................................... 38
In Lab: .................................................................................................................................... 42
Critical Analysis / Conclusion ............................................................................................... 46
Lab # 05 Introduction to Assembly Language Programming of AVR Microcontrollers .......... 47
Objectives ............................................................................................................................... 47
Pre Lab ................................................................................................................................... 47
In-Lab ..................................................................................................................................... 49
COMSATS University Islamabad (CUI) , Islamabad Campus Page 5
EEE342 Microprocessor Systems & Interfacing

Post Lab Task ......................................................................................................................... 57


Critical Analysis / Conclusion ............................................................................................... 55
Lab # 06 Keypad Interfacing Using Digital I/O Ports ............................................................... 57
Objectives: .............................................................................................................................. 57
Pre Lab: .................................................................................................................................. 57
In-Lab: .................................................................................................................................... 59
Critical Analysis / Conclusion ............................................................................................... 63
Lab # 07: Interfacing Analog Sensors using Analog to Digital Converter ................................ 65
Objectives: .............................................................................................................................. 65
Pre-Lab ................................................................................................................................... 65
Pre lab Task: ........................................................................................................................... 70
In Lab: .................................................................................................................................... 70
Critical Analysis / Conclusion ............................................................................................... 76
Lab # 08 External and Internal Interrupts in AVR Microcontrollers ......................................... 77
Objectives ............................................................................................................................... 77
Pre Lab ................................................................................................................................... 77
In Lab ..................................................................................................................................... 78
Post Lab Task ......................................................................................................................... 89
Critical Analysis / Conclusion ............................................................................................... 89
Lab # 09 Using Timers/Counters of AVR MCU for Waveform Generation ............................. 90
Objectives: .............................................................................................................................. 90
Pre-Lab: .................................................................................................................................. 90
In Lab: .................................................................................................................................... 95
Critical Analysis / Conclusion ............................................................................................. 100
Lab # 10 Recording a Periodic Signal using Input Capture Feature of Timers/Counters ........ 101
Objectives: ............................................................................................................................ 101
Pre-Lab: ................................................................................................................................ 101
In Lab: .................................................................................................................................. 103
Post lab Task: ....................................................................................................................... 110
Critical Analysis / Conclusion ............................................................................................. 111
Lab # 11 Serial Communication with UART and Interfacing Bluetooth HC-05..................... 113
Objectives: ............................................................................................................................ 113

COMSATS University Islamabad (CUI) , Islamabad Campus Page 6


EEE342 Microprocessor Systems & Interfacing

Pre Lab ................................................................................................................................. 123


In Lab: .................................................................................................................................. 116
Critical Analysis / Conclusion ............................................................................................. 123
Lab # 12: Interfacing Devices using SPI.................................................................................. 124
Objectives: ............................................................................................................................ 124
Pre Lab ................................................................................................................................. 123
In Lab ................................................................................................................................... 123
Critical Analysis / Conclusion ............................................................................................. 132

COMSATS University Islamabad (CUI) , Islamabad Campus Page 7


Lab # 01 Introduction to Development Tools & Lab Software

Lab # 01 Introduction to Development Tools and Lab


Softwares

Objectives
 Learn to use software development tools such as Arduino, Integrated Development
Environment (IDE) (Atmel Studio, AVR Studio), Compiler (WinAVR), and Simulator
(Proteus) for the AVR ATmega 328P microcontroller.
 Learn to program Arduino and ATmega328P.

Softwares Used

 Arduino
 Atmel Studio (Version 7)
 AVR Studio (Version 4)
 Proteus ISIS
 WinAVR (Version 2010)

Pre Lab
Get the following software installers from MP/VLSI lab and install them in your laptops. The
same software will be available in the Lab PCs.

Arduino:
Arduino is an open-source platform used for building electronics projects. It consists of both a
physical programmable circuit board and an IDE (Integrated Development Environment) that
runs on your computer. Most Arduino boards consist of an Atmel 8-bit AVR microcontroller
with varying amounts of flash memory, pins and features. Arduino is programmed using
the Arduino Software (IDE) which is a cross-platform application for windows, macOS and
Linux. It is connected to a PC via USB cable to upload computer code to the physical board.
This also provides power to the board, as indicated by a LED.

AVR Studio:
AVR Studio is an Integrated Development Environment (IDE) used to develop projects
(software part) for AVR microcontrollers. This IDE consists of a project management tool,
source filer editor, assembler and front-end for C/C++ programming, a debugger and a hardware
(MCU registers) Simulator. With AVR Studio, you can develop code in C as well as in Assembly
Language. Both approaches are different from each other. Each has its own merits as you will
learn during the coursework.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 8


Lab # 01 Introduction to Development Tools & Lab Software

Atmel Studio:
Atmel Studio 7 is the integrated development platform (IDP) for developing and debugging
Atmel Atmel AVR microcontroller (MCU) applications. Atmel Studio 7 supports all AVR
MCUs. It gives you a seamless and easy-to-use environment to write, build and debug your
applications written in C/C++ or assembly code. It also connects seamlessly to Atmel debuggers
and development kits.

WinAVR:
WinAVR is a suite of executable, open source software development tools for the Atmel AVR
series of microprocessors hosted on the Windows platform. It includes the GNU GCC compiler
for C and C++. You will install this software (release 2010) on your PC/Laptop and it will be
used to compile your C/C++ code for the AVR microcontroller. IDEs such as AVR Studio will
automatically detect and use WinAVR installation and you will not need to run this software
yourself.

Proteus:
The Proteus Design Suite is a complete software solution for circuit simulation and PCB
design.Proteus can simulate electric/electronic and microcontroller based circuits. It supports
number of microcontrollers available in the market.

ATmega 328p:
The Atmel AVR ATmega328P is a low-power 8-bit microcontroller architecture.It has 131
Powerful Instructions. Most of them require single clock cycle for execution. It has 32K bytes
of In-System Programmable Flash Program memory with Read-While-Write capabilities, 1K
bytes EEPROM, 2K bytes SRAM, 23 general purpose I/O pins and 32 general purpose working
registers.

ATmega 328P Peripheral Features:

 3 flexible Timer/Counters with compare modes


 Six PWM Channels
 Internal and External Interrupts
 A serial programmable USART
 Two Master/Slave SPI Serial Interface
 8 channel 10-bit ADC

ATmega328P Pin configuration:


The 23 digital I/O pins are grouped into 3 ports named as Port B, C and D. Port B and D have 8
pins each whereas Port C has 7 pins. Pin 4 and 6 are required to connect with +ve (VCC) and

COMSATS University Islamabad (CUI) , Islamabad Campus Page 9


Lab # 01 Introduction to Development Tools & Lab Software

pin 3, 5 and 21 need to connect with ground (GND).Pin 18 is the supply voltage pin for the A/D
Converter. Pin 20 is the analog reference pin for the A/D Converter.
Each of the AVR Digital I/O port i.e Port B, Port C and Port D are associated with three I/O
registers. These resigters are:

 DDRx (Data Direction Register) - Sets the direction of each pin as input or output.
 PORTx - Used to output/write values on a Port.
 PINx - Used to input/ read values from a Port.
Where x is the port B, C or D. All of these registers are 8-bit registers. Figure 1.1 shows the three
registers associated with Port B.

Figure 1.1 Registers Associated with Port B

COMSATS University Islamabad (CUI) , Islamabad Campus Page 10


Lab # 01 Introduction to Development Tools & Lab Software

Pin configuration of ATmega 328P can be seen in Figure 1.1.

Figure1.2 Pin Configuration of ATmega328p

In-Lab
In-Lab Task 1: Arduino Learning Tutorial
1. Launch Arduino IDE.
2. Some built-in examples are included in Arduino software. Click on the toolbar menu: File
> Examples > Basics > Blink. This will turn an LED on Arduino board on and off with
some delay.
3. Compile the sketch. After successful compilation, the code can be uploaded to the
Arduino board.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 11


Lab # 01 Introduction to Development Tools & Lab Software

Figure 1.3 shows a basic Arduino sketch.

Figure 1.3 Compiling a Sketch in Arduino

In-Lab Task 2: AVR Studio Learning Tutorial


1. Launch AVR Studio either by start menu or by selecting desktop icon. Then Select
Project Wizard form menu bar and Select New Project as shown in Figure 1.4.

Figure 1.4: Creating a new project in AVR Studio 4


COMSATS University Islamabad (CUI) , Islamabad Campus Page 12
Lab # 01 Introduction to Development Tools & Lab Software

2. After selecting New Project, two options will be displayed (AVR Assembler and AVR
GCC). AVR Assembler is selected for the assembly code and AVR GCC is selected to
compile C-code. In this tutorial, we will use C-code so select AVR GCC. Write project
name (lab1 for this tutorial) and select the path directory path to save files for this new
project (Select desktop and lab1 as folder name) and Click Next (Figure 1.5).

Figure 1.5: Compiler selection and Project name description with location

3. In the next menu, select AVR Simulator in debug platform and ATmega328P in device
menu. After selection click finish as shown in Figure 1.6.

Figure 1.6: AVR microcontroller Selection

COMSATS University Islamabad (CUI) , Islamabad Campus Page 13


Lab # 01 Introduction to Development Tools & Lab Software

4. Layout shown in Figure 1.7 will appear on the screen. Layout will consist of source
Window, I/O window, message window and I/O toolbar.

Figure 1.7: AVR Studio platform section wise overview


5. Write down the code below in source window.
C-Code:
/*This code will configure Port B for output and then toggle Port B
pin 3 with a delay of 1000ms*/

#include <avr/io.h> /*This header file includes the apropriate

I/O definitions for the device */

#define F_CPU 16000000UL //XTAL Frequency =16MHz

#include <util/delay.h> /*This header file is required for

generating delays*/

int main()

{ // Write your code here

DDRB = 0b11111111; //Configure Port B as Output

while(1) //This loop will run forever

{ PORTB = 0b00001000; /*Send 1 on Port B Pin 3,

rest of the pins are zero*/

_delay_ms(1000); //Delay of 1000ms

PORTB = 0b00000000; //Send 0 on Port B Pin 3

_delay_ms(1000); //Delay of 1000ms } }

COMSATS University Islamabad (CUI) , Islamabad Campus Page 14


Lab # 01 Introduction to Development Tools & Lab Software

Press F7 button to build output files of the project including object file and hex file.

In-Lab Task 3: Atmel Studio Learning Tutorial


1. Launch Atmel Studio either by start menu or by selecting desktop icon. From start page
new projects can be created and recently used projects can be opened. The Start page can
also be accessed from View → Start Page, or Alt V G. Click on new project as shown
in Figure 1.8.

Figure 1.8: How to create new project using Atmel Studio installed in Lab

2. After selecting New Project, the project wizard will appear. AVR Assembler is selected
for the assembly code and C/C++ is selected to compile C-code. In this tutorial, we will
use C-code so select C/C++ and then select GCC C Executable Project. Write project
name, select the path directory path to save files for this new project and Click ok (Figure
1.9).

Figure 1.9: Compiler selection and Project name description with location
COMSATS University Islamabad (CUI) , Islamabad Campus Page 15
Lab # 01 Introduction to Development Tools & Lab Software

3. In the Device Selection window, select ATmega328P. Click OK to create the project as
shown in Figure 1.10.

Figure 1.10: AVR Microcontroller Selection


4. Layout shown in figure 1.11 will appear on the screen. Layout will consist of source code
window and message window. Write a code given in Task 1 in the source window.

Figure 1.11: AVR Studio platform section wise overview

COMSATS University Islamabad (CUI) , Islamabad Campus Page 16


Lab # 01 Introduction to Development Tools & Lab Software

5. Press F7 button to build output files of the project including object file and hex file.

In-Lab Task 4- Proteus Introductory Learning Tutorial


To learn basics about Proteus, we will simulate a microcontroller based circuit in Proteus. We
will use the same program for microcontroller which we simulated in AVR Tutorial.

1. Launch Proteus from start menu or by desktop icon. Proteus layout shown below will
appear on the screen as shown in Figure 1.12. There is a root sheet to draw circuit. The
device window will initially be empty and you need to pick components from library.
Proteus component library is equipped with lots of components and ICs including
microcontrollers. To pick necessary components required for circuit, click on small P in
device window.

Figure 1.12: Proteus ISIS overview of window

2. After Clicking Pick devices menu as in figure 1.13 will appear on the screen. There is a
keyword prompt which can refine your search. Write ATmega328P in keyword prompt
and result window will display components having keyword of ATmega328P. Double
click ATmega328P component in result window to add it to device list.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 17


Lab # 01 Introduction to Development Tools & Lab Software

Figure 1.13: Pick Devices for circuit diagram

3. As described in step 2 add following components needed for this tutorial


i. ATmega328 Microcontroller
ii. Animated LED
iii. 470 ohms resistor
4. To add any component on root sheet, simply select that component from device window
and click anywhere in the root sheet to place that component. To draw wire connection
between two pins of any components, simply move mouse cursor to the tip of the pin and
click. Then click on tip of the other pin you wanted to connect. Draw a circuit shown in
figure 1.14 on Proteus root sheet by using components indicated above.

Figure 1.14: Circuit Diagram for In-Lab Task 3


COMSATS University Islamabad (CUI) , Islamabad Campus Page 18
Lab # 01 Introduction to Development Tools & Lab Software

5. On the left side of Proteus layout, different modes can be selected. To add ground
terminal to the circuit, click terminal mode from buttons on left side of screen and then
select ground terminal. You can change characteristic properties of any component. To
change, simply double click the required component. An edit component menu will
appear for that particular component where you can change the characteristic properties
of that component.
6. You also need to load your required program into the microcontroller memory as shown
in Figure 1.15. Program is loaded into microcontroller memory through hex file. Double
click microcontroller, edit menu will have prompt for load program. Select the hex file
generated from Atmel Studio tutorial. This hex (Lab1.hex) file can be found in the Lab1
directory you created on desktop for the Atmel Studio tutorial.
7. The default frequency of ATmega328p is 1MHz. To change it to 16MHz, we will provide
external clock source of 16MHz. Select CKSEL Fuses (0000) Ext. Clock, In Clock
Frequency, write 16MHz and select CLKDIV8 fuse to be unprogrammed.

Figure 1.15: Edit component menu


8. Now run the simulation from the bottom of Root Sheet and show result to your lab
instructor.
9.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 19


Lab # 01 Introduction to Development Tools & Lab Software

In Lab Task 4:
a. The following code is written to generate fibonacci series output at PortB which is
given as (0, 1, 2, 3, 5, 8, 13, 21, 34, 55).
b. Build the following code in AVR Studio or Atmel Studio. Read the error messages,
identify and correct any syntax errors and rebuild the solution.
c. Use Debugging mode of AVR Studio or Atmel Studio to debug and correct the
code to get the desired output. In debug mode, open watch window to check the
value of the variables.

Code:
//This code will generate fibanocci series.

#include <avrio.h> /*This header file includes the apropriate

I/O definitions for the device */

#define F_CPU 16000000UL //XTAL Frequency =16MHz

#include <util/delay.h> /*This header file is required for

generating delays*/

int main(void)

DDRB = 0b11111111 //Configure Port B as Output

int t1 = 1, t2 = 1, nextTerm = 0, i = 1;

while (i < 10)

PORTB = nextTerm;

//Generate fibanocci series

nextTerm = t1 - t2;

t1 = t2;

t2 = nextTerm;

i = i + 1;

while (1)

return 0; }

COMSATS University Islamabad (CUI) , Islamabad Campus Page 20


Lab # 01 Introduction to Development Tools & Lab Software

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

Lab Assessment

Pre Lab /1

In Lab /5

Data Analysis /4 /10

Data
Post Lab /4 /4
Presentation

Writing Style /4

Instructor Signature and Comments

COMSATS University Islamabad (CUI) , Islamabad Campus Page 21


Lab # 02 Introduction to AVR Microcontroller Hardware Circuitry and Digital I/O Ports

Lab # 02 Introduction to AVR Microcontroller


Hardware Circuitry and Digital I/O Ports

Objectives:
 Understand the minimal circuit required to start using a microcontroller
 Learn to program (download code to program memory of) a microcontroller using
Arduino board.
 To understand and use digital I/O ports of AVR microcontroller

Required Tools:

Software Tools:
 Atmel Studio (Version 7) or AVR Studio (Version 4)
 Proteus ISIS
 Arduino IDE
 AVRDUDESS

Hardware Tools:
Name Value Quantity
Arduino Nano With USB Cable - 1
Breadboard - 1
LEDs - 8
Switches - 8
Resistor 470Ω 8
Table 2.1 List of Components

Pre-Lab
2.1 Arduino Nano

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


hardware and software. Arduino Nano is a surface mount breadboard embedded version with
integrated USB. It is a smallest, complete, and breadboard friendly.Arduino Nano is programmed
using the Arduino Software (IDE).

COMSATS University Islamabad (CUI) , Islamabad Campus Page 22


Lab # 02 Introduction to AVR Microcontroller Hardware Circuitry and Digital I/O Ports

Arduino Nano Specifications:

Microcontroller Atmel ATmega328


Operating Voltage 5V
Input Voltage 7-12 V
Digital I/O Pins 14 (of which 6 provide PWM output)
Analog Input Pins 8
DC Current per I/O Pin 40 mA
Flash Memory 32 KB (of which 2KB used by bootloader)
SRAM 2 KB
EEPROM 1 KB
Clock Speed 16 MHz

Arduino Nano Features:

• Automatic reset during program download


• Power OK LED
• TX, RX, L LED
• Auto sensing/switching power input
• Small mini-B USB for programming and serial monitor
• ICSP header for direct program download
• Standard 0.1” spacing DIP (breadboard friendly)
• Manual reset switch

Figure 2.1 shows pinout of Arduino Nano.

Figure 2.1 Pinout of Arduino Nano

COMSATS University Islamabad (CUI) , Islamabad Campus Page 23


Lab # 02 Introduction to AVR Microcontroller Hardware Circuitry and Digital I/O Ports

Figure 2.2 shows schematics of Arduino Nano.

Figure 2.2 Schematics of Arduino Nano

2.1.1 Hardware Programming AVR Microcontroller using Arduino:

AVRDUDE - AVR Downloader Uploader - can be used to upload the Hex file generated by
software programming in AVR microcontrollers. It is a program for downloading and uploading
the on-chip memories of Atmel's AVR microcontrollers. It can program the Flash and EEPROM,
and when supported by the serial programming protocol, it can program fuse and lock bits.
Avrdude is a command line program, AVRDUDESS is a GUI for AVRDUDE. It supports all
programmers and MCUs that AVRDUDE supports.

2.2 Introduction to AVR Digital Input/Output:


Digital I/O is the most fundamental mode of connecting a microcontroller to the outside world.
Atmel AVR ATMega 328P provides 23 I/O pins to interact with outside world in the form of
logic values. These pins are usually organised in groups and referred to as a port. Port B and Port
D have 8 pins each whereas Port C consists of 7 pins.
In Arduino nano, 20 pins are available for digital I/O. PC6 is connected with reset circuit and
PB6 and PB7 are connected with crystal oscillator. So these 3 pins are not available for digital
I/O in Arduino nano.

Each of the AVR Digital I/O port is associated with three I/O registers.

 DDRx
 PORTx
 PINx

Where x is the port B, C or D.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 24


Lab # 02 Introduction to AVR Microcontroller Hardware Circuitry and Digital I/O Ports

2.2.1 DDRx - Port X Data Direction Register:

DDRx is an 8-bit register which stores configuration information for the pins of Portx. The bits
in this register set the data direction of the individual pins of a port. The direction of each pin
can be input or output. Writing a 1 in the pin location in the DDRx makes the physical pin of
that port an output pin and writing a 0 makes that pin an input pin.

DDRD= 0x00 ; //Configures Port D as input

DDRB=0xFF; //Configures Port B as output

The prefix 0x signifies hexadecimal number. 0xFF means decimal 255 or binary 11111111
which means all the bits in register are at high logic level. 0x00 means all the bits in the register
are at low logic level. Each physical pin of a port is configured independently and thus a port
can have some of its pins configured as input and the others as output pins. For example:

DDRD = (1<<0)|(1<<4)|(1<<5)|(1<<7);

This is equivalent to

DDRD = 0b10110001;

Or

DDRD= 0xB1;

In the above example, port D is initialized such that the pins PD0, PD4, PD5 and PD7 are output
pins whereas pins PD1, PD2, PD3 and PD6 are input pins.

We can change the value of a single bit without disturbing the previous value of all the other bits
of the register. For example:

DDRD |= (1<<5);

This will set bit 5 of DDRD while retaining the values of all other bits.

Similarly,

DDRD &= ~(1<<5);

This will clear bit 5 of DDRD while retaining the values of all other bits.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 25


Lab # 02 Introduction to AVR Microcontroller Hardware Circuitry and Digital I/O Ports

2.2.2 PORTx- Port x Data Register:

PORTx is an 8-bit register which stores the logic values that are to be transferred on the physical
pins of Portx if the pins are configured as output pins. In short, once the direction of DDRx
register is defined as an output pins, we need to set them to give an output of HIGH logic or
LOW logic. So to write values to a port, you need to write the values to the “PORT” register of
that port.

PORTD = (1 << 0)|(1 << 3)|(1 << 6);

This is equivalent to

PORTD = 0b01001001;

Or

PORTD = 0x49;

2.2.3 PINx- PortX Input Pins Register:

PINx is an 8-bit register that stores the logic value, the current state, of the physical pins on
Portx. When you set any port as input you have to read its status using this register.

PINB = (1 << 0)|(1 << 3)|(1 << 6);

This is equivalent to

PINB = 0b01001001;

Or

PINB = 0x49;

Pre lab Task:


Task 1:
Enlist 5 peripherals (Devices) that can be interfaced with Atmega328P Microcontroller

COMSATS University Islamabad (CUI) , Islamabad Campus Page 26


Lab # 02 Introduction to AVR Microcontroller Hardware Circuitry and Digital I/O Ports

In Lab:
Task 1

Write and test following program in AVR Studio/Atmel Studio. Also, simulate it on
Proteus.

/*This code will configure Port B for output and then toggle

Port B pin 3 with a delay of 1000ms*/

#include <avr/io.h> /*This header file includes the apropriate

I/O definitions for the device */

#define F_CPU 16000000UL //XTAL Frequency =16MHz

#include <util/delay.h> /*This header file is required for

generating delays*/

int main()

{ // Write your code here

DDRB = 0b11111111; //Configure Port B as Output

while(1) //This loop will run forever

PORTB = 0b00001000; /*Send 1 on Port B Pin 3,

rest of the pins are zero*/

_delay_ms(1000); //Delay of 1000ms

PORTB = 0b00000000; //Send 0 on Port B Pin 3

_delay_ms(1000); //Delay of 1000ms

} }

Burning .Hex file to ATMega328P:


AVR burning process Using AVRDUDESS

1. AVRDUDE require LibUSB drivers. LibUSB should be installed along with Arduino
IDE or with any LibUSB device but if you don’t have any such devices then you will
need to download this driver.
2. Connect Arduino nano with your PC via USB cable. The power LED on Arduino should
turn on.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 27


Lab # 02 Introduction to AVR Microcontroller Hardware Circuitry and Digital I/O Ports

3. In device manager, a COM Port will be listed under Ports (COM and LPT). If your device
is not detected you can try installing CH340 drivers.
4. Run AVRDUDESS, Select Arduino as programmer and ATMega328P as MCU. Under
Port, select the COM port which was listed under Ports in device manager. Set the baud
rate to 57600 (Fig 2.4).
5. Now select the .hex file generated in Task 1 and click program button, program will be
burned in your ATmega 328P memory.

Figure 2.3: Burning a .hex file using AVRDUDESS

Implement the above task on hardware.

Task 2:
(To be assigned by Lab instructor_

Switches are connected to one port of ATmega328p for input and LEDs are connected to
another port for output. Using these, perform a task assigned by your lab instructor.
Students should write the code for given task, simulate it on proteus and then implement
it on hardware.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 28


Lab # 02 Introduction to AVR Microcontroller Hardware Circuitry and Digital I/O Ports

Post Lab:
Write Arduino code for In lab task 2. Simulate it on Proteus using Arduino nano.

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

Lab Assessment

Pre Lab /1

In Lab /5

Data Analysis /4 /10

Data
Post Lab /4 /4
Presentation

Writing Style /4

Instructor Signature and Comments

COMSATS University Islamabad (CUI) , Islamabad Campus Page 29


Lab # 03 Interfacing 7-Segment Display Using Digital I/O Ports

Lab # 03 Interfacing 7-Segment Display Using Digital


I/O Ports

Objectives:
 Learn to interface components like seven-segment display using digital I/O ports.

Required Tools:

Software Tools:
 AVR Studio/ Atmel Studio
 Proteus ISIS
 AVRDUDESS

Hardware Tools:

Name Value Quantity


Arduino Nano - 1
7-Segment Display - 1
Resistors 470 Ω 8
LED - 1
Wires - -
Table 3.1 List of Components

Pre-Lab

Seven Segment Display:


A seven-segment display is a set of seven bar-shaped LEDs (light-emitting diodes) arranged to
form a squared-off figure 8. If all LEDs are activated, the display shows a numeral 8. When some
of the elements are activated but not others, any single-digit numeral from 0 to 9 is shown. Every
LED is assigned a name from 'a' to 'h' and is identified by its name. Seven LEDs 'a' to 'g' are used
to display the numerals while eighth LED 'h' is used to display the dot/decimal.

Seven-segment displays are commonly used in digital clocks, clock radios, timers, wristwatches,
and calculators. They can also be found in motor-vehicle odometers, speedometers, radio
frequency indicators, and practically any other display that makes use
of alphanumeric characters alone.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 30


Lab # 03 Interfacing 7-Segment Display Using Digital I/O Ports

Figure 3.1 shows the arrangement of LEDs in a Seven Segment Display.

Figure 3.1: Seven Segment Display

Types of Seven segment display:


There are two types of LED 7-segment displays:
 Common Cathode
 Common Anode

Figure 3.2: Common Cathode and Common anode 7- Segment

In Common Cathode configuration, the negative terminals of all LEDs are connected to the
common pin. The common is connected to ground and a particular LED glows when its
corresponding pin is given high.

In Common anode arrangement, the positive terminals of all LEDs are connected to common
pin .The common pin is given a high logic and the LED pins are given low logic to display a
number.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 31


Lab # 03 Interfacing 7-Segment Display Using Digital I/O Ports

Pin configuration of seven segment display:

The figure below shows Pin diagram of a 7- segment display. For common anode, COM pins
are given Vcc and for common cathode, COM pins are given ground.

Figure 3.3 Pin Configuration of different types of 7-Segment Display

Pre-Lab Task:
A seven segment display is connected with Port D. Write a code to toggle all the segments
simultaneously with some delay.

Disabling Tx and Rx on Port D:

The pins PD0 and PD1 are connected to the receiver and transmitter of of USART respectively.
To use these pins for digital I/O, we have to disable the transmitter and receiver. This can be
done by disabling TXEN0 and RXEN0 bits in UCSR0B register.

Disable Tx and Rx in your code as follows:


UCSR0B&=~(1<<TXEN0);

UCSR0B&=~(1<<RXEN0);

Simulate the code on Proteus (Proteus schematic is shown below).

Figure 3.4 Simulation for Pre-Lab Task


COMSATS University Islamabad (CUI) , Islamabad Campus Page 32
Lab # 03 Interfacing 7-Segment Display Using Digital I/O Ports

In Lab:
Task 1:
a. Implement Pre-lab task on hardware to test all segments of a 7-Segment display.
b. Use DMM to test the 7-segment display and identify whether it is common cathode or
common anode (Lab instructor should explain the method of testing a 7-segment with
DMM).
Task 2:
Interfacing of Seven Segment Display with AVR Microcontroller:
In this task a seven segment display is connected to Port D. On Port B a 4 inputs 7-segment
display is connected which takes BCD number and displays it on seven segment. An array is
created which is currently zero. This array will be filled with hexa-decimal numbers after
creating a Look-up table for 7-segment display.

Part a: Look-up Table:

Fill the following table.

Digit to Seven Segment Pin


be
displayed h g f e d c b a Hexadecimal
Value
Atmega 328P Pin

0 0 0 1 1 1 1 1 1 0x3F

Table 3.2: 7-Segment Look-Up Table

COMSATS University Islamabad (CUI) , Islamabad Campus Page 33


Lab # 03 Interfacing 7-Segment Display Using Digital I/O Ports

Part b- Code:
#include <avr/io.h> /*This header file includes the apropriate

I/O definitions for the device */

#define F_CPU 16000000UL //XTAL Frequency =16MHz

#include <util/delay.h> /*This header file is required for

generating delays*/

int main(void)

//Write code to declare PORT B and PORT D as output

/* Write code to Disable Tx and Rx to use PD0 and PD1 as digital

I/O*/

unsigned char
seven_seg_array[10]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
};

//Fill this array according to LUT

unsigned char counter= 0;

while(1) { // Infinite loop

PORTB=counter; //send value of counter on PORT B

PORTD=~seven_seg_array[counter]; /*Send the array of 7

segment LUT on PORTD. Remove negation sign in case of

Common cathode 7 segment*/

_delay_ms(500);

counter++; //Increment counter till 10

if(counter==10)

counter=0;

return 0;

COMSATS University Islamabad (CUI) , Islamabad Campus Page 34


Lab # 03 Interfacing 7-Segment Display Using Digital I/O Ports

Part c-Simulation:

Figure 3.5: Simulation of Lab Task

Simulation using Arduino Nano:

Figure 3.6: Simulation of lab task using Arduino Nano

Task 1d-Hardware Implementation:

Download the hex file of your project in Atmega328P microcontroller using AVRDUDESS and
implement this task on hardware.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 35


Lab # 03 Interfacing 7-Segment Display Using Digital I/O Ports

In Lab Task 2:
(To be specified by lab instructor)

Switches are connected to Port B for input and a seven segment display is connected to PORT
D of ATmega328p for output. Using these, perform a task assigned by your lab instructor.

Post lab task:


Connect 2 seven segments with Atmega 328P (As shown in schematic below). Write a code to
count from 0-99 on these 7- segments.

Figure 3.7: Simulation for Post Lab Task

Code:

COMSATS University Islamabad (CUI) , Islamabad Campus Page 36


Lab # 03 Interfacing 7-Segment Display Using Digital I/O Ports

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

Lab Assessment

Pre Lab /1

In Lab /5

Data Analysis /4 /10

Data
Post Lab /4 /4
Presentation

Writing Style /4

Instructor Signature and Comments

COMSATS University Islamabad (CUI) , Islamabad Campus Page 37


Lab # 04 LCD Interfacing with AVR Microcontroller

Lab # 04 LCD Interfacing with AVR Microcontroller

Objectives:
 Overview of controller to controller communication
 To understand LCD interfacing with AVR microcontroller

Software Tools:
 Atmel Studio/ AVR Studio
 Proteus ISIS
 AVRDUDESS

Hardware Tools:

Name Value Quantity


Microcontroller ATMega 328P 1
Breadboard - 1
16 x 2 LCD LM016L 1
Variable Resistor 5k Ω 1
Table 4.1 List of Components

Pre-Lab

4.1 Introduction to LCD


LCD provides an output interface to AVR microcontroller. It comes in various configurations
such as 20 x 2, 16 x 1, 40 x 1, 16 x 2 etc. with 5 x 8 or 5 x 11 dots resolution. Out of these, 16 x
2 is widely used.

LCD has a microcontroller in it which is already coded to display characters on the screen.
Therefor to use an LCD a controller to controller interface is required.
LCD controller is responsible for all the operations with in LCD such as movement of curser,
display clear, character printing and special character generation etc. HD44780U and S6A0069
are common examples of LCD control unit.

LCD controller’s internal memory comprises of Character Generator ROM (CGROM),


Character Generator RAM (CGRAM) and Display Data RAM (DDRAM).
 Character Generator ROM (CGROM) contain predefined character fonts table.
 Character Generator RAM (CGRAM) stores customised character table
 Display Data RAM (DDRAM) stores display data represented in 8-bit character codes.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 38


Lab # 04 LCD Interfacing with AVR Microcontroller

4.1.1 LCD Pin Configuration

Figure 4.1 shows the pin configuration of LCD.

Figure 4.2 Basic Pin-out of LM016L LCD

Table 4.2 provides the description of the pins:

Table 4.2: LCD Pin-out Detail

4.1.2 LCD communication modes


The LCD can be used as 8-bit or 4-bit interface with microcontroller.

1. 8-bit communication.
2. 4-bit communication

COMSATS University Islamabad (CUI) , Islamabad Campus Page 39


Lab # 04 LCD Interfacing with AVR Microcontroller

In 8-bit communication 11 pins of MCU reserved as 8 pins for LCD data pins (D0-D7) and 3
pins for LCD Control Pins i.e. Enable (En is pin 6), Read/Write (RW is pin 5) and Register Select
(RS is pin 4). So each instruction executes in 1 cycle for 1byte instruction.

However, in 4-bit mode only 4 data pins (D0-D3) and 3 control pins are used so MCU reserves
7pins for LCD. Each instruction executes in normally 2 cycle for 1 byte instruction i.e. 1 nibble
per cycle

4.2 LCD Interfacing

LCD controller has two 8-bit registers:

 Command Register allows the user to send commands such as clear display, cursor at
home etc.
 Data register allows the user to send the data to be displayed on LCD

Since same pins from D0 to D7 are used for both command and data, RS pin is used to identify
between the command and data.

Following steps are used to send command or data to LCD:

1. Initialize the LCD.


2. Send commands from Table 4.3 to LCD.
3. Send data to be displayed on LCD.

4.2.1 Initializing the LCD

To initialize the LCD for 5x7 matrix and 8 bit communication mode, following commands
should be send to LCD. See Table 5.3 for description of each command.

 Function Set: Select LCD mode to 8-bit interface, 2 line, and character size to 5x7.
 Display On/Off control: Display On, turn on the cursor, No blinking.
 Clear Display
 Entry mode set: Increment Cursor, No display shift

Pre Lab Task:


Find hexa-decimal codes for above mentioned commands using Table 4.3.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 40


Lab # 04 LCD Interfacing with AVR Microcontroller

4.2.2 Sending Commands to LCD:

To send any command from Table 4.3 to LCD, following steps should be followed.

 Set R/S and R/W pins to zero logic.


 Send the command code to pins D0-D07.
 Send a high to low pulse to Enable pin.
Enable pin is used to synchronize the whole operation of sending data or command to LCD. The
LCD will not read any pins for command or data until we give high to low transition level to
enable pin. After each command, add a delay of 100us to to wait for LCD controller to run the
command. After clear LCD and return home commands, wait for 2ms.

4.2.3 Sending Data to LCD:

To send any data to be displayed LCD, following steps should be followed.

 Set R/S =1 and R/W = 0.


 Send the data to pins D0-D07.
 Send a high to low pulse to Enable pin.
After sending the data, wait for 100us to let LCD module write the data on the screen.

Table 4.3 List of LCD Instructions


COMSATS University Islamabad (CUI) , Islamabad Campus Page 41
Lab # 04 LCD Interfacing with AVR Microcontroller

Abbreviations used in Table 4.3:

In Lab:

Task-1

Complete the following code and simulate it on Proteus.

 Complete the LCD initialize function by using the command codes from Pre-Lab task.
 Function to send commands to LCD is given, Write the function to send data on LCD.

Code:
#include <avr/io.h>

#define F_CPU 16000000UL

#include <util/delay.h>

#define RS PB0 //R/S pin is connected to PORTB Pin 0

#define RW PB1 //R/W pin is connected to PORTB Pin 1

#define EN PB2 //En pin is connected to PORTB Pin 1

int LCD_init(void);

void LCD_Send_Command(unsigned char);

void LCD_Send_Data(unsigned char);

int LCD_Send_Array(char * ptr); //This array will be sent to LCD

COMSATS University Islamabad (CUI) , Islamabad Campus Page 42


Lab # 04 LCD Interfacing with AVR Microcontroller

int main(void)

LCD_init();

LCD_Send_Array("Hello World");

/* Replace with your application code */

while (1)

return(0);

int LCD_init()

/* Students have to complete this function */

// set PortD to output

// set PB0 to PB2 to output

// Disable TX and RX of the USART0

_delay_ms(100);

PORTB |= (1<<EN); // Keep EN high at idle state

LCD_Send_Command(0x38); /* Select LCD mode to 8-bit interface, 2


line, and character size to 5x7 /*

_delay_ms(2);

// Turn Display ON, turn ON the cursor, No blinking

_delay_ms(2);

// Clear Display

_delay_ms(2);

// Increment Cursor, No display shift

_delay_ms(2);

return(0);

void LCD_Send_Command(unsigned char comm)

COMSATS University Islamabad (CUI) , Islamabad Campus Page 43


Lab # 04 LCD Interfacing with AVR Microcontroller

PORTB &= ~(1<<RS); // Set RS low for command

PORTB &= ~(1<<RW); // Set RW low for writing

PORTD = comm; // Send comm on port

PORTB &= ~(1<<EN); // Send a short pulse on EN

_delay_ms(1);

PORTB |= (1<<EN);

void LCD_Send_Data(unsigned char data)

/* Students have to complete this function */

// Set RS high for data

// Set RW low for writing

// Send data on port

// Send a short pulse on EN

int LCD_Send_Array(char * ptr)

while(*ptr != '\0')

LCD_Send_Data(*ptr);

ptr++;

COMSATS University Islamabad (CUI) , Islamabad Campus Page 44


Lab # 04 LCD Interfacing with AVR Microcontroller

Simulation:

Figure 4.2: Wiring of Atmega328P with LCD

Implement the above task on hardware.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 45


Lab # 04 LCD Interfacing with AVR Microcontroller

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

Lab Assessment

Pre Lab /1

In Lab /5

Data Analysis /4 /10

Data
Post Lab /4 /4
Presentation

Writing Style /4

Instructor Signature and Comments

COMSATS University Islamabad (CUI) , Islamabad Campus Page 46


Lab # 05 Introduction to Assembly Programming of AVR Microcontrollers

Lab # 05 Introduction to Assembly Language


Programming of AVR Microcontrollers

Objectives
 To get started with assembly language programming for AVR microcontrollers.
 Implementing loops and conditional execution instructions in Assembly language

Required Tools:

Software Tools:
 AVR Studio/ Atmel Studio
 Proteus ISIS
 AVRDUDESS

Hardware Tools:

Name Value Quantity


Arduino Nano - 1
Oscilloscope - 1
Resistors 470 Ω 1
LED - 1
Wires - -
Table 5.1 List of Components

Pre Lab

5.1 Introduction to Assembly Programming


Assembly language is a low-level programming language for a computer or other programmable
devices. It is an alphanumeric representation of machine code. The instructions used in writing
programs in assembly language are not general but specific to the microcontroller. AVR 8-bits
microcontrollers have a common instruction set.

5.1.1 Advantages of Assembly Language:

 Assembly language is fast.


 Program written in assembly take less execution time.
 We know exact time for each instruction.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 47


Lab # 05 Introduction to Assembly Programming of AVR Microcontrollers

 We are able to measure accurate execution time and hence able to generate specific
delays.
 It requires less memory.
 The use of machine codes gives us precise control over microcontroller that we want to
program.
 Assembly is also case insensitive hence commands written in upper or lower case don’t
make any difference.

5.1.2 Processor Registers:

There are 32 general-purpose 8-bit registers, R0–R31. All arithmetic and logic operations operate
on those registers; only load and store instructions access RAM. A limited number of instructions
operate on 16-bit register pairs.
The last three register pairs are used as pointer registers for memory addressing. They are known
as X (R27:R26), Y (R29:R28) and Z (R31:R30). Instructions which allow an immediate value
are limited to registers R16–R31 (8-bit operations) In addition to these 32 general-purpose
registers, the CPU has a few special-purpose registers:
 PC: 16 bit program counter
 SP: 16 bit stack pointer
 SREG: 8 bit status register

5.2 Assembly Language Instructions:


Some common assembly language instructions used for AVR microcontroller programming
are given below:

Instruction Operands Description Operation


IN Rd , A In from I/O location. Loads data from I/O space into Rd ← I/O(A)
destination register.
OUT A, Rr Out to I/O location. Stores data from register Rr in the I/O(A) ←Rr
Register File to I/O Space
NOP This instruction performs a single cycle No Operation.

LDI Rd, k Load Immediate. Loads an 8 bit constant directly to Rd ← K


register 16 to 31.

BRNE k Branch if Not Equal. Conditional relative branch tests If (Z=0), then PC ←
the Zero Flag (Z) and branches relatively to PC if Z is PC+k+1
cleared.

BREQ k Branch if Equal. Conditional relative branch tests Z=1 If (Z=1), then PC ←
PC+k+1

COMSATS University Islamabad (CUI) , Islamabad Campus Page 48


Lab # 05 Introduction to Assembly Programming of AVR Microcontrollers

CALL k Long call to a subroutine. Calls to a subroutine within


the entire program memory. The return address (to the PC ← k
instruction after the CALL) will be stored onto the
stack.
RCALL k Relative call to a subroutine. Relative call to an
address within PC - 2K + 1 and PC + 2K (words). The PC ← PC+k+1
return address (the instruction after the RCALL) is
stored onto the stack.
RET Return from a subroutine. The return address is loaded
from the Stack. PC← Stack
RJMP k Relative Jump
PC ← PC+k+1
ADD Rd, Rr Add without Carry
Rd ← Rd+Rr
Dec Rd
Decrement Rd ← Rd-1
Table 5.2: Frequently used Assembly Language Instructions

Pre-Lab Task:

Understand the operation of all instructions from Atmel AVR 8 bit instruction Set.

In-Lab

Task 1:

Generate a square wave signal of frequency 1 KHz and 40% duty cycle on a digital I/O pin of
ATmega328P.
Steps:
1: Initialize stack pointer.
2: Configure Pin 0 of Port B as output.
3: Send 1 on PB0.
5: Call Delay of 400us.
6: Send 0 on PB0.
7: Call delay of 600us.
8: Repeat forever

Code :
.include "m328Pdef.inc"

;Initialize stack pointer.

ldi r16,HIGH(RAMEND)

out SPH, R16

ldi r16,LOW(RAMEND)

COMSATS University Islamabad (CUI) , Islamabad Campus Page 49


Lab # 05 Introduction to Assembly Programming of AVR Microcontrollers

out SPL, R16

start:

ldi r16,0x01 ;load 0x01 into a register r16

out DDRB,r16 ;configure PB0 as output: DDRB=0x01

forever:

ldi r19,0x01 ;load 0x01 into a register

out PORTB,r19 ;PB0=1

rcall delay_400us

ldi r19,0x00

out PORTB,r19 ;PORTB=0x00

rcall delay_600us

rjmp forever ;keep doing this forever

delay_400us: ;This subroutine will call delay of 100us 4 times

;to generate a delay of 400us

ldi r20,4

loop1:

rcall delay_100us

dec r20

brne loop1

ret

delay_600us: ;This subroutine will call delay of 100us 6 times

;to generate a delay of 600us

ldi r20,6

loop2:

rcall delay_100us

dec r20

brne loop2

ret

COMSATS University Islamabad (CUI) , Islamabad Campus Page 50


Lab # 05 Introduction to Assembly Programming of AVR Microcontrollers

delay_100us: ;This subroutine will generate a delay of 100us

; Inner loop count =4 (Ignoring overhead)

; Delay = (1/16M)*4*4*100

ldi r18, 4

l1: ldi r19,100

l2:

nop

dec r19

brne l2

dec r18

brne l1

ret

Simulation:

Hardware:
Implement the above task on hardware.

In Lab Task 2:

Write a program to toggle all bits of PORT D with some delay (Specified by Lab
Instructor). Simulate it on Proteus and implement it on Hardware.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 51


Lab # 05 Introduction to Assembly Programming of AVR Microcontrollers

Steps:
1: Initialize stack pointer.
2: Make Port B an output port.
3: Load 0x55 in any general purpose register, say R16.
4: Output R16 on Port B.
5: Call Delay.
6: Complement R16.
7: Repeat Forever

Code:

Simulation:

COMSATS University Islamabad (CUI) , Islamabad Campus Page 52


Lab # 05 Introduction to Assembly Programming of AVR Microcontrollers

Post Lab Task:

Blinking LED’s with different frequencies.

Description:

Connect 4 LED’s to PORT B of AT mega 328P.Using loops and conditions write an assembly
program that makes these LED blinks.

LED 0 should blink an ON/OFF time of 200ms

LED 1 should blink an ON/OFF time of 400ms

LED 2 should blink an ON/OFF time of 800ms

LED 3 should blink an ON/OFF time of 1600ms

Simulate on proteus.

CODE:

COMSATS University Islamabad (CUI) , Islamabad Campus Page 53


Lab # 05 Introduction to Assembly Programming of AVR Microcontrollers

Simulation:

COMSATS University Islamabad (CUI) , Islamabad Campus Page 54


Lab # 05 Introduction to Assembly Programming of AVR Microcontrollers

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

Lab Assessment

Pre Lab /1

In Lab /5

Data Analysis /4 /10

Data
Post Lab /4 /4
Presentation

Writing Style /4

Instructor Signature and Comments

COMSATS University Islamabad (CUI) , Islamabad Campus Page 55


Lab # 05 Introduction to Assembly Programming of AVR Microcontrollers

COMSATS University Islamabad (CUI) , Islamabad Campus Page 56


Lab # 06 Keypad Interfacing Using Digital I/O Ports

Lab # 06 Keypad Interfacing Using Digital I/O Ports

Objectives:
 Using digital I/O ports of AVR microcontroller for digital Inputs.
 Use I/O ports To Interface matrix keypad with microcontroller.

Tools:

Software Tools:

 AVR Studio/ Atmel Studio


 Proteus ISIS
 AVRDUDESS

Hardware Tools:

Name Value Quantity


Arduino Nano - 1
4X4 Keypad - -
Resistors 100Ω 8
Table 6.2: List of Components

Pre Lab:

6.1 4x4 Membrane Keypad:

The Keypad 4x4 features 16 push buttons arranged in 4x4 matrix to form standard alphanumeric
keypad. It provides a useful human interface component for microcontroller projects.Matrix
keypads uses a combination of four rows and four columns to provide button states to the
microcontroller. Underneath each key is a pushbutton, with one end connected to one row, and
the other end connected to one column. These connections are shown in figure 6.1.

Key Specifications

 Maximum Rating: 24 VDC, 30 mA


 Interface: 8-pin access to 4x4 matrix
 Operating temperature: 32 to 122 °F (0 to 50°C)
 Dimensions: Keypad, 2.7 x 3.0 in (6.9 x 7.6 cm) Cable: 0.78 x 3.5 in (2.0 x 8.8 cm)

COMSATS University Islamabad (CUI) , Islamabad Campus Page 57


Lab # 06 Keypad Interfacing Using Digital I/O Ports

This keypad can be used in Security systems, Menu selection, Data entry for embedded systems
and various other applications.

Figure 6.1: 4x4 Membrane Keypad

6.2 Working of keypad:

From Figure 6.11 it can be seen that if one of the 16 buttons are pressed, a pair of pins are
connected together. We will used this feature to detect with button was pressed. Under normal
conditions, the switch (key) is open. In order for the microcontroller to determine which button
is pressed, following steps are followed:

1) Create a look-up table filled with 16 entries for all keys of the keypad.
2) Four microcontroller pins should be defined as outputs, and other four pins should be defined
as inputs.
3) Connect columns of the keypad to input port and rows to the output port. Pull up the input
port and then read the value of columns.
4) Now connect rows of the keypad to input port and columns to the output port. Pull up the
input port and then read the value of rows.
5) If no key is pressed, the value of rows and columns will be 0000. If any key is pressed, the
value of rows and columns can be 0000,0001,0010,0100,1000 (1,2,4,8).
6) If no key is pressed, return 0. If a key is pressed, find its location in the keypad look-up table
and return the key pressed.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 58


Lab # 06 Keypad Interfacing Using Digital I/O Ports

In-Lab:
Interfacing Atmega 328P with Keypad:
Connect a keypad to the microcontroller. Scan the keypad for key press and display the pressed
key on the serial monitor using serial communication.

Task 1- Code:
Understand the following code and complete the readkeypad function.
/* Module description:

In this lab the students will use the digital I/O Ports to

interface a Keypad. Pressing a key on the keypad should display the


corresponding digit on the virtual terminal*/

#include <inttypes.h> //Used for type casting

#include <avr/io.h> //Basic I/O definitions

#include <util/delay.h> //to generate delays

#define F_CPU 16000000UL //XTAL Frequency

/*************************** Definitions for UART


*******************************/

#include "debug_prints.c"

#define BAUD0 9600 // Baud Rate for UART

#define MYUBRR (F_CPU/8/BAUD0-1) // U2X = 1

//************* Definitions for Keypad Interfacing **********/

//Rows are connected to PORTB, Columns to PORTD

#define KEYPAD_DDR_ROWS DDRB

#define KEYPAD_PORT_ROWS PORTB

#define KEYPAD_PIN_ROWS PINB

#define KEYPAD_DDR_COLS DDRD

#define KEYPAD_PORT_COLS PORTD

#define KEYPAD_PIN_COLS PIND

COMSATS University Islamabad (CUI) , Islamabad Campus Page 59


Lab # 06 Keypad Interfacing Using Digital I/O Ports

/*Lookup table for Keypad*/

unsigned char keypad_tbl1[] = {255,0,1,255,2,255,255,255,3};

//unsigned char keypad_tbl2[] =


{'1','2','3','A','4','5','6','B','7','8','9','C','*','0','#','D'}; //
for Lab Keypad

unsigned char keypad_tbl2[] =


{'7','8','9','/','4','5','6','X','1','2','3','-','C','0','=','+'};
// for proteus model

unsigned char read_keypad(void);

//***********************************************************/

int main()

unsigned char key_pressed = 0;

//Initalizting UART, Print UBRR value and F_CPU

UART0_init(MYUBRR);

printSerialStr("MYUBRR = ");

printSerialInt(MYUBRR);

printSerialStrln("");

printSerialStr("F_CPU = ");

printSerialInt((int)(F_CPU/1000000));

while (1)

key_pressed = read_keypad();

if(key_pressed != 0) //wait for key to be pressed

UART0_send_char(key_pressed);//display pressed key on serial monitor

key_pressed = 0;

COMSATS University Islamabad (CUI) , Islamabad Campus Page 60


Lab # 06 Keypad Interfacing Using Digital I/O Ports

return 0;

unsigned char read_keypad()

unsigned char columns;

unsigned char rows;

unsigned char key,temp;

//COMPLETE THIS SECTION OF CODE//

// Pull-up the columns

// Set columns to Input

//pull down the rows

// Set rows to Output

//give delay of 2ms

// read the value of columns

_delay_us(100);

// Pull-up the rows

// Set rows to Input

//pull down the columns

// Set columns to Output

//give delay of 2ms

// read the value of rows

/* value of columns and rows will be 1,2,4,8

we will convert it to 0,1,2,3 using keypad_tbl1*/

COMSATS University Islamabad (CUI) , Islamabad Campus Page 61


Lab # 06 Keypad Interfacing Using Digital I/O Ports

temp = (keypad_tbl1[columns]) + (keypad_tbl1[rows]<<2);


//multiply rows by 4

if(temp > 15) /*If value is greater than 15,return 0, otherwise


return the key.*/

key = 0;

else

key = keypad_tbl2[temp];

_delay_ms(200);

return key;

Task 1-Simulation:

Figure 6.2: Simulation of In Lab task

Task 1- Hardware Implementation:

Download the hex file of your project in Arduino Nano using AVRDUDESS and implement
this task on hardware. Use serial monitor of Arduino IDE for display.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 62


Lab # 06 Keypad Interfacing Using Digital I/O Ports

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

Lab Assessment

Pre Lab /1

In Lab /5

Data Analysis /4 /10

Data
Post Lab /4 /4
Presentation

Writing Style /4

Instructor Signature and Comments

COMSATS University Islamabad (CUI) , Islamabad Campus Page 63


Lab # 06 Keypad Interfacing Using Digital I/O Ports

COMSATS University Islamabad (CUI) , Islamabad Campus Page 64


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

Lab # 07: Interfacing Analog Sensors using Analog to


Digital Converter

Objectives:
 Understand the function of ADC in microcontroller.
 Learn different mode of operation of ADC
 Interfacing of LM35 temperature sensor with Atmega328p.

Software Tools:
 Atmel Studio/AVR Studio
 Arduino
 Proteus ISIS
 AVR DUDESS

Hardware Tools:

Name Value Quantity


Arduino Nano - 1
Breadboard - 1
LM35 - 1
Table 7.3: List of Components

Pre-Lab
Analog to digital converters are the most widely used devices for data acquisition. Most of the
physical quantities are analog e.g. temperature, humidity, pressure, light, etc. Therefore, we need
an analog to digital converter to convert the data into digital data in order to communicate with
the digital processors like microcontrollers and microprocessors.

7.1 Internal ADC of ATmega328p microcontroller


The ADC in Atmega328p converts an analog input voltage to a 10-bit digital value through
successive approximation. The minimum value represents GND and the maximum value
represents the voltage on the AREF pin minus 1 LSB. Optionally, AVCC or an internal 1.1V
reference voltage may be connected to the AREF pin by writing to the REFSn bits in the
ADMUX Register.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 65


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

The ADC system of Atmega328P has following features


 10 bit ADC
 ±2 LSB absolute accuracy
 13 ADC clock cycle conversion rate
 8 multiplexed single-ended input channels
 Selectable right or left result justification
 0 to Vcc ADC input voltage range

7.2 ADC Register Description

1. ADC Multiplexer Selection Register – ADMUX

Bit 7:6 – REFS1:0: Reference Selection Bits

These bits select the voltage reference for the ADC, as shown in Table 8.2

Table 7.2: ADC Voltage reference selection

Bit 5 – ADLAR: ADC Left Adjust Result

The ADLAR bit affects the presentation of the ADC conversion result in the ADC Data Register.
Write one to ADLAR to left adjust the result. Otherwise, the result is right adjusted.

Bits 4:0 – MUX3:0: Analog Channel Selection Bits

The value of these bits selects which analog input is connected to the ADC. Table 8.3shows these
bit settings for selecting various single ended input channels:

Table 7.3: Mux ADC selection table

COMSATS University Islamabad (CUI) , Islamabad Campus Page 66


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

2. ADC Control and Status Register A – ADCSRA

Bit 7 – ADEN: ADC Enable

Writing this bit to one enables the ADC. By writing it to zero, the ADC is turned off.

Bit 6 – ADSC: ADC Start Conversion

In Single Conversion mode, write this bit to one to start each conversion. ADSC will read as
one as long as a conversion is in progress. When the conversion is complete, it returns to zero.
Writing zero to this bit has no effect.

Bit 5 – ADATE: ADC Auto Trigger Enable

When this bit is written to one, Auto Triggering of the ADC is enabled (This mode is not covered
in this lab).

Bit 4 – ADIF: ADC Interrupt Flag

This bit is set when an ADC conversion completes and the Data Registers are updated. The ADC
Conversion Complete Interrupt is executed if the ADIE bit and the I-bit in SREG are set. ADIF
is cleared by hardware when executing the corresponding interrupt handling vector.
Alternatively, ADIF is cleared by writing a logical one to the flag.

Bit 3 – ADIE: ADC Interrupt Enable

When this bit is written to one and the I-bit in SREG is set, the ADC Conversion Complete
Interrupt is activated.

Bits 2:0 – ADPS2:0: ADC Prescaler Select Bits

These bits determine the division factor between the XTAL frequency and the input clock to the
ADC.

Table 7.4: division factor calculation for frequency


COMSATS University Islamabad (CUI) , Islamabad Campus Page 67
Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

3. The ADC Data Register –ADCL and ADCH


These two registers contain 10 bits of the conversion result. The result is stored in two different
ways depending on the setting of ADLAR bit as shown below:

ADLAR=0:

ADLAR=1

4. Digital Input Disable Register 0-DIDR0


When the respective bits are written to logic one, the digital input buffer on the corresponding
ADC pin is disabled. The corresponding PIN Register bit will always read as zero when this bit
is set. When an analog signal is applied to the ADC7...0 pin and the digital input from this pin is
not needed, this bit should be written logic one to reduce power consumption in the digital input
buffer.

7.3 Configuring the ADC

Following are the steps required to configure the ADC of AVR microcontrollers.

1. Disable digital I/O by writing ones in DIDR0.


2. Select a reference voltage and adjust your result to left/right using ADMUX register.
3. Select a pre-scalar for ADC clock on ADCSRA register. By default, the successive
approximation circuitry requires an input clock frequency between 50 kHz and 200 kHz
to get maximum resolution
4. Enable the ADC by setting the ADC Enable bit, ADEN in ADCSRA. Voltage reference
and input channel selections will not go into effect until ADEN is set. The ADC does not
consume power when ADEN is cleared.
5. A '0' must be written to the Power Reduction ADC bit in the Power Reduction Register
(PRR.PRADC) before the ADC can be used.
6. ADC result is stored in ADCH and ADCL. By default, the result is presented right
adjusted. ADCL must be read first, then ADCH, to ensure that the content of the Data

COMSATS University Islamabad (CUI) , Islamabad Campus Page 68


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

Registers belongs to the same conversion. The ADC has its own interrupt which can be
triggered when a conversion completes.
7. A single conversion is started by writing a '1' to the ADC Start Conversion bit in the ADC
Control and Status Register A (ADCSRA.ADSC). ADCS will stay high as long as the
conversion is in progress, and will be cleared by hardware when the conversion is
completed. If a different data channel is selected while a conversion is in progress, the
ADC will finish the current conversion before performing the channel change.
8. Auto Triggering is enabled by setting the ADC Auto Trigger Enable bit
(ADCSRA.ADATE). The trigger source is selected by setting the ADC Trigger Select
bits in the ADC Control and Status Register B (ADCSRB.ADTS).

7.3.1 ADC Conversion Result


After the conversion is complete (ADCSRA.ADIF is set), the conversion result can be found in
the ADC Result Registers (ADCL, ADCH). For single ended conversion, the result is:

Where VIN is the voltage on the selected input pin, and VREF the selected voltage reference

7.4 Modes of operation:


The ADC has two fundamental operation modes:
1. Single conversion mode
2. Free running mode

7.4.1 Single Conversion Mode:


In Single Conversion mode, you have to initiate each conversion. When it is done, the result is
placed in the ADC Data register pair and no new conversion is started.

7.4.2 Free Running Mode:


It start the conversion only once, and then, the ADC automatically will start the following
conversion as soon as the previous one is finished. Its conversion is continuous. Once initialized
it takes 13 ADC cycles for single conversion. In this mode ADC data register has to be read
before new value is written.

7.5 LM35:
The LM35 is an integrated circuit sensor that can be used to measure temperature with an
electrical output proportional to the temperature (in oC).

COMSATS University Islamabad (CUI) , Islamabad Campus Page 69


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

PIN Configuration:

Figure 7.1 LM35 Pinout

Pre lab Task:


Explain the working of five analog sensors. Explain what physical quantity do they measure and
provide the mapping function for the output voltage.

In Lab:

Task-1
Use LM35 to sense the room temperature. Convert this data into digital using atmega328P ADC and
display temperature value on virtual terminal.
Complete the Code and simulate on Proteus.

Code:
// Module description:

// In this lab the students will learn to use the Analog to Digital
Converter

// present as a peripheral device in Atmega328p MCU.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 70


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

/* Task1: Interface a temperature sensor (LM35) using the ADC of


Atmega328P MCU*/

//********************************************************************
************/

#include <inttypes.h>

#include <stdlib.h>

#include <avr/io.h>

#include <avr/interrupt.h>

#define F_CPU 16000000UL

#include <util/delay.h>

#include <string.h>

#include <math.h>

/****************** Definitions for UART *********************/

#include "debug_prints.c"

#define BAUD0 9600 // Baud Rate for UART

#define MYUBRR (F_CPU/8/BAUD0-1)

/*********************************************************************
************/

#define ADC_CHANNEL0 0

#define ADC_CHANNEL1 1

#define ADC_CHANNEL2 2

#define ADC_VREF 5 // Ref voltage for ADC is 5 Volts

#define ADC_RES 10 // Resoulution of ADC in bits

#define ADC_QLEVELS 1024 // Quantization levels for the ADC

unsigned char ADC_Initialize();

COMSATS University Islamabad (CUI) , Islamabad Campus Page 71


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

unsigned int ADC_Read(unsigned char channel); // Reads the result of


a single conversion from the ADC

float ADC_Convert(unsigned int);

unsigned char VinToTemp(float Vin);

unsigned char read_temp_sensor(unsigned char ADC_channel);

#define TEMP_SENSOR_CHANNEL ADC_CHANNEL0

/*****************************************************************/

int main(void)

ADC_Initialize();

DIDR0=0xFF; //Disable digital I/O

DDRD = 0xFF;

UART0_init(MYUBRR);

printSerialStrln("Lab 8: ");

unsigned char temprature;

while(1)

{ printSerialStr("Temperature is: ");

temprature = read_temp_sensor(TEMP_SENSOR_CHANNEL);

printSerialInt(temprature);

printSerialStr("\r \n");

PORTD = temprature;

// Function Initializes the ADC for 10-Bit Single Conversion mode..

unsigned char ADC_Initialize()

// Left adjust result. Vref = AVCC = 5V

/*** Write Code for this ***/

COMSATS University Islamabad (CUI) , Islamabad Campus Page 72


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

// Here select the prescaler for 16 MHz System Clock

// Prescaler = 128

// Clock for ADC = 125 KHz (should be between 50K to 200K)

return 0;

/* Function reads the result of a single conversion from the ADC

channel given as an argument*/

unsigned int ADC_Read(unsigned char channel)

unsigned char ADC_lo;

unsigned char ADC_hi;

unsigned int result;

ADMUX &= ~(0x07); // clear previous selction of channel

ADMUX |= channel; // Select the new channel

// Delay needed for the stabilization of the ADC input voltage

_delay_us(10);

//wait for ADC to finish any ongoing opeartion

while((ADCSRA & (1<<ADSC)) != 0);

ADCSRA |= (1 << ADSC); //start conversion

while((ADCSRA & (1<<ADIF)) == 0);

ADCSRA |= (1<<ADIF); // clear the flag by writing 1 to it

//result = (ADCH<<8)|(ADCL & 0xC0); // Left adjust result

ADC_lo = ADCL;

ADC_hi = ADCH;

result = (ADC_hi<<2)|(ADC_lo >> 6); // Right adjust result

return result;

/* This function takes an uint16 as input from the ADC.

This uint16 is an unsgined integer result of the ADC

encoded result. The function then converts this result

COMSATS University Islamabad (CUI) , Islamabad Campus Page 73


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

to floating point Voltage using the ADC_RES (resolution)

and ADC_REF (reference voltage) defined earlier*/

float ADC_Convert(unsigned int ADC_value)

float Vin;

Vin = ADC_VREF * ((float)ADC_value/ADC_QLEVELS);

return Vin;

/** This function takes the floating point Voltage value as input and
converts it to corresponding Temprature in Celsius for an LM35 in
Basic Configuration.

The function returns an 8-Bit integer value of the Temprature */

unsigned char VinToTemp(float Vin)

unsigned char temprature=0;

float VoltsPerCentigrade = 0.01; // 10 mv per centigrade

temprature = (unsigned char) floor(Vin/VoltsPerCentigrade);

return temprature; // Temprature value returned

/** This function reads the Value of Temprature Sensor (LM35) from

pre-defined ADC Channel and returns the result in Degree Celsius

as an 8-Bit unsigned int */

unsigned char read_temp_sensor(unsigned char ADC_channel)

unsigned int ADC_value = ADC_Read(ADC_channel); // Read the sensor


Connected at ADC_channel

float Vin = ADC_Convert(ADC_value); // Get the value in


floating point

unsigned char temp_celsius = VinToTemp (Vin); // Convert to


temprature and return

return temp_celsius;

COMSATS University Islamabad (CUI) , Islamabad Campus Page 74


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

Proteus Simulation

Figure 7.2: Task-1 Proteus diagram

Hardware:
Interface a temperature sensor with Arduino Nano and use serial monitor of Arduino IDE to
display temperature.

In Lab Task 2:
Interface any analog sensor assigned by your lab instructor, Find mapping function for its
output and implement ADC for the sensor using ATmega328p.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 75


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

Lab Assessment

Pre Lab
/1

In Lab /10
/5

Post Lab
/4

Instructor Signature and Comments

COMSATS University Islamabad (CUI) , Islamabad Campus Page 76


Lab # 08 External and Internal Interrupts in AVR Microcontrollers

Lab # 08 External and Internal Interrupts in AVR


Microcontrollers

Objectives
 To learn the concepts related to interrupts in AVR microcontroller.
 To configure and use the external interrupt or user input tasks
 To configure and use the internal interrupts
Software Tools

 Atmel Studio or AVR Studio


 Proteus
 AVRDUDESS
Hardware Tools
Name Value Quantity
Arduino Nano - 1
Breadboard - 1
Switches - 2
LEDs - 8
Table 8.4: List of Components

Pre Lab

What is Interrupt?

An interrupt refers to a notification, communicated to the controller, by a hardware device or


software, on receipt of which controller momentarily stops and responds to the interrupt.
Whenever an interrupt occurs the controller completes the execution of the current instruction
and starts the execution of an Interrupt Service Routine (ISR) or Interrupt Handler. ISR is a piece
of code that tells the processor or controller what to do when the interrupt occurs. After the
execution of ISR, controller returns back to the instruction it has jumped from (before the
interrupt was received). The interrupts can be either internal interrupts or external interrupts.

Why need interrupts:


An application built around microcontrollers generally has the following structure. It takes input
from devices like keypad, ADC etc., processes the input using certain algorithm and generates
an output which is either displayed using devices like seven segment, LCD or used further to
operate other devices like motors etc. In such designs, controllers interact with the inbuilt devices

COMSATS University Islamabad (CUI) , Islamabad Campus Page 77


Lab # 08 External and Internal Interrupts in AVR Microcontrollers

like timers and other interfaced peripherals like sensors, serial port etc. The programmer needs
to monitor their status regularly like whether the sensor is giving output, whether a signal has
been received or transmitted, whether timer has finished counting, or if an interfaced device
needs service from the controller, and so on. This state of continuous monitoring is known as
polling.

In polling, the microcontroller keeps checking the status of other devices and while doing so it
does no other operation and consumes all its processing time for monitoring. This problem can
be addressed by using interrupts. In interrupt method, the controller responds to only when an
interruption occurs. Thus in interrupt method, controller is not required to regularly monitor the
status (flags, signals etc.) of interfaced and inbuilt devices.

To understand the difference better, consider the following. The polling method is very much
similar to a salesperson. The salesman goes door-to-door requesting to buy its product or service.
Like controller keeps monitoring the flags or signals one by one for all devices and caters to
whichever needs its service. Interrupt, on the other hand, is very similar to a shopkeeper.
Whosoever needs a service or product goes to him and apprises him of his/her needs. In our case,
when the flags or signals are received, they notify the controller that they need its service.

External Interrupts:
The External Interrupts are triggered by the INT pins or any of the PCINT pins. The Pin Change
Interrupt Request 2 (PCI2) will trigger if any enabled PCINT[23:16] pin toggles. The Pin Change
Interrupt Request 1 (PCI1) will trigger if any enabled PCINT[14:8] pin toggles. The Pin Change
Interrupt Request 0 (PCI0) will trigger if any enabled PCINT[7:0] pin toggles. The PCMSK2,
PCMSK1 and PCMSK0 Registers control which pins contribute to the pin change interrupts. Pin
change interrupts on PCINT are detected asynchronously.
The External Interrupts can be triggered by a falling or rising edge or a low level. This is set up
as indicated in the specification for the External Interrupt Control Register A (EICRA).

Internal Interrupts:
ATmega328p has 20 internal interrupts. These internal interrupts are generated by the internal
peripherals of Microcontroller like Timer, ADC etc. The internal interrupts are used for efficient
operation of the internal peripherals. They can be enabled through the registers of these
peripherals.

In-Lab:

How to use interrupts:


 First we have to configure and enable the global interrupts. The most significant bit of
status register called ‘I’ bit is used for this purpose. If ‘I’ is set 1 using register SREG
this means interrupt is enabled otherwise disabled.
COMSATS University Islamabad (CUI) , Islamabad Campus Page 78
Lab # 08 External and Internal Interrupts in AVR Microcontrollers

 We write functions called Interrupt Service Routine (ISR) to handle interrupts. These
functions are defined outside the main function because the event that causes interrupt is
not known by the programmer; hence the function can’t be called inside the main
function.
 Enable the external interrupts locally in External Interrupt Mask Register (EIMSK). Then
configure the interrupts for falling edge, rising edge, low level or any logical change by
using EICRA register.
 Enable the internal interrupts locally by writing 1 to interrupt enable bit in the registers
of the peripheral under use. For example, ADC system consists of ADIE bit in ADCSRA
register. ADIE bit is enabled to use ADC interrupts.
Advantages of Interrupt method:
 Priority can be assigned.
 Controller does not waste time checking if a device needs service or not.

Steps involved executing an interrupt:


Upon activation of an interrupt the microcontroller goes through the following steps as shown
in figure 7.1:

Figure 8.1: Interrupt Service Routine


1. It finishes the instruction that it is executing and saves the address of next instruction
on the stack.

2. The program branches to the address of corresponding interrupt in the interrupt vector
table. The code starting here is called interrupt handler.

3. Check which source generated the interrupt using interrupt flags.

4. Executes the corresponding interrupt service subroutine.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 79


Lab # 08 External and Internal Interrupts in AVR Microcontrollers

5. Upon executing the last instruction in ISR the microcontroller returns to the place
where it was interrupted using reti instruction. First it gets the program counter
address by popping it from the stack. Then it starts to execute from that address.

Available interrupts in ATMEGA328P micro controller:


There are 26 interrupts in ATmega328P (Table 7.1) with 20 internal and 6 external interrupts.
The external interrupts are RESET, INT0 (pin16) and INT1 (pin17). All 21 interrupts are listed
in table below in descending order of priority. In this lab we will focus on external interrupts.

Table 8.2: Interrupt Vector table available on ATmega328P microcontroller

COMSATS University Islamabad (CUI) , Islamabad Campus Page 80


Lab # 08 External and Internal Interrupts in AVR Microcontrollers

Register Description:
The registers involved in configuring the external interrupts are shown in below.
External Interrupt Control Register A(EICRA):

The External Interrupt Control Register A contains control bits for interrupt sense control.

External Interrupt Mask Register (EIMSK):


In this register if INTn bit is set and the I-bit in the Status Register (SREG) is set, the external
pin interrupt is enabled.

External Interrupt Flag Register (EIFR):


When an edge or logic change on the INTn pin triggers an interrupt request, INTFn will be set.
If the I-bit in SREG and the INTn bit in EIMSK are set, the MCU will jump to the corresponding
Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively, the
flag can be cleared bywriting '1' to it. This flag is always cleared when INTn is configured as a
level interrupt.

In addition to above registers you will need to set Global Interrupt Enable (GIE) bit. GIE is
bit7 of status register SREG.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 81


Lab # 08 External and Internal Interrupts in AVR Microcontrollers

For interrupt handling we need to include following header file into our project:
#include <avr/interrupt.h>
The following format is used to declare interrupt service routine:
ISR(ISR_Vect)
{
//Interrupt handling code goes here…..
}

In-Lab Task 1:
Generate binary counting with the help of LED’s interfaced by MCU and controlled by 2
Switches. One for enabling the circuit and the other is to reset it. Switch pressing is an external
event, that’s why we use external interrupts. Write the C code for Interrupts and simulate in
Proteus.

Registers used in this task:


 EICRA
 EIMSK
 SREG (Status register)

Code:
#include<avr/interrupt.h>

#include<avr/io.h>

#define F_CPU 16000000UL

unsigned char counter=0;

ISR(INT0_vect)

counter++; //Sw1 pressed LED on

PORTB = counter; //counter value displayed on portB

ISR(INT1_vect)

counter= 0x00; //reset counter

PORTB = counter; //counter value displayed on portB

COMSATS University Islamabad (CUI) , Islamabad Campus Page 82


Lab # 08 External and Internal Interrupts in AVR Microcontrollers

int main()

DDRB= 0XFF;

counter=0;

//Enable interrupts globally

//Enable INT0 and INT1 interrupt locally

//configure EICRA for falling edge INT0 and INT1

while(1)

Proteus schematic:

Figure8.2: Proteus Schematic

Hardware:
Implement In Lab task 1 on hardware.

Task 2:
Assume that INT1 pin is connected to a switch that is normally low. Write a program that
toggles PORTC 20 times with some delay whenever INT1 pin goes high.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 83


Lab # 08 External and Internal Interrupts in AVR Microcontrollers

Code:

Simulation:

Task 3
Record a signal using ADC. Use ADC in free running mode. Add 8 bit DAC at Port D and
convert back the signal in analog and display result on oscilloscope for comparison.

Task description:

Implementation of Bus in Proteus.

 To implement 8bit DAC in Proteus use 10 DAC.


 Take “Bus” (Label) from “Terminals Mode” at side bar.
 Placed “Bus” at root sheet.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 84


Lab # 08 External and Internal Interrupts in AVR Microcontrollers

 Connect DAC Bus (Blue line) to “Bus”.


 Double click at “Bus” and change its name to “DAC[0..9]”.
 Connect PD0 to DAC Bus. Right click on wire and select “Place Wire Label”.
 From drop down string menu select “DAC2”.
 Repeat last 2 steps with rest of PD pins.
 Connect DAC0 and DAC1 to ground.

Code:
//Record an analog signal using the ADC and output to a DAC after
processing

//********************************************************************
************/

#include <inttypes.h>

#include <avr/io.h>

#include <avr/interrupt.h>

#define F_CPU 16000000UL

#include <util/delay.h>

/*********************************************************************
************/

#define ADC_CHANNEL0 0

#define ADC_CHANNEL1 1

#define ADC_CHANNEL2 2

unsigned char ADC_Initialize(); // Initialize ADC

unsigned int ADC_Read(unsigned char channel); // Reads the result of


a single conversion from the ADC

#define DAC_DDR DDRD

#define DAC_PORT PORTD

ISR(ADC_vect)

DAC_PORT = ADCH; // ouput the digital value on DAC Port

/*****************************************************************/

COMSATS University Islamabad (CUI) , Islamabad Campus Page 85


Lab # 08 External and Internal Interrupts in AVR Microcontrollers

int main(void)

ADC_Initialize();

DIDR0=0xFF;

DAC_DDR = 0xFF; //Configure port for output

ADMUX &= ~(0x07); // clear previous selction of channel

ADMUX |= ADC_CHANNEL1; // Select the new channel

//write command for this // Enable interrupts globally

// write command for this // Trigger the free running ADC

while(1);

/* Function Initializes the ADC for 10-Bit Free Running mode.

The function returns 0 if initialization successful.

If mode argument is other than 1 or 2, the function returns an error


code 0x02*/

unsigned char ADC_Initialize()

// Left adjust result.

// Set Vref = AVCC = 5V

// select the prescaler for 16 MHz System Clock

// Prescaler should be between 50K to 200K

// Enable ADC

// Enable ADC Interrupts

//Enable Auto-triggered mode

return 0;

/* Function reads the result of a single conversion from the ADC

channel given as an argument*/

unsigned int ADC_Read(unsigned char channel)

unsigned char ADC_lo;

COMSATS University Islamabad (CUI) , Islamabad Campus Page 86


Lab # 08 External and Internal Interrupts in AVR Microcontrollers

unsigned char ADC_hi;

unsigned int result;

ADMUX &= ~(0x07); // clear previous selction of channel

ADMUX |= channel; // Select the new channel

// Delay needed for the stabilization of the ADC input voltage

_delay_us(10);

//wait for ADC to finish any ongoing opeartion

while((ADCSRA & (1<<ADSC)) != 0);

ADCSRA |= (1 << ADSC); //start conversion

while((ADCSRA & (1<<ADIF)) == 0);

ADCSRA |= (1<<ADIF); // clear the flag by writing 1 to it

//result = (ADCH<<8)|(ADCL & 0xC0); // Left adjust result

ADC_lo = ADCL;

ADC_hi = ADCH;

result = (ADC_hi<<2)|(ADC_lo >> 6); // Right adjust result

return result;

Simulation:

Figure 8.3: Simulation for task 3

COMSATS University Islamabad (CUI) , Islamabad Campus Page 87


Lab # 08 External and Internal Interrupts in AVR Microcontrollers

Post Lab Task:


What is switch debouncing? Explain software and hardware methods for switch
debouncing.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 88


Lab # 08 External and Internal Interrupts in AVR Microcontrollers

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

Lab Assessment

Pre Lab
/1

In Lab /10
/5

Post Lab
/4

Instructor Signature and Comments

COMSATS University Islamabad (CUI) , Islamabad Campus Page 89


Lab # 09 Using Timers/Counters of AVR MCU for Waveform Generation

Lab # 09 Using Timers/Counters of AVR MCU for


Waveform Generation

Objectives:
 Introduction to Timers/Counters
 Delay and Waveform generation using timers
 Using PWM signals to control Servo Motors
Tools:

Software Tools:

 AVR Studio/ Atmel Studio


 Proteus ISIS
 AVR DUDESS

Hardware Tools:

Name Value Quantity


Arduino Nano - 1
Potentiometer - 1
Servo Motor - 1
Wires - -
Oscilloscope - 1

Table 9.1: List of Components

Pre-Lab:

9.1 Timers/Counters:
Timers are used to perform any time related task e.g. turning on or off a particular device at a
specific time, generating complex waveforms of particular time period and frequency, generating
delays or counting events. Timer/Counter is a special register that increments/decrements its
value on each clock pulse (rising/falling edge) at its input. In Atmega328p, there are 3 timers
referred to as Timer0, Timer1 and Timer2. Timer0 and Timer2 are 8 bit timers whereas Timer1
is a 16 bit timer/counter. Every timer needs some clock source. The clock source can be internal,
(pre-scaled CPU clock) or external input. The clock source is selected by the clock select logic
which is controlled by the clock select (CS02:0) bits located in the Timer/Counter Control
Registers. In this lab you will be using all three timers for various tasks. Detailed description of
COMSATS University Islamabad (CUI) , Islamabad Campus Page 90
Lab # 09 Using Timers/Counters of AVR MCU for Waveform Generation

Timer0 will be provided. For details about Timer1 and Timer2 refer to the datasheet of
Atmega328p.

9.2 Modes of Operation:

There are four different modes of operation of Timer/Counter0 module.


1. Normal Mode.
2. Clear Timer on Compare Match (CTC) Mode.
3. Fast PWM Mode.
4. Phase Correct PWM Mode.

Timer0 has two signal generation channels (A and B). The mode of operation, i.e., the behavior
of the Timer/Counter and the Output Compare pins, is defined by the combination of the
 Waveform Generation mode (WGM01:0) bits.
 Compare Output mode (COMA01:0, COMB01:0) bits.
Waveform Generation mode bits affect the counting sequence, while the COM0A1:0bits control
whether the PWM output generated should be inverted or not (inverted or non-inverted PWM).
For non-PWM modes the COM0A1:0 bits control whether the output should be set, cleared, or
toggled at a compare match.
Next these modes are discussed in detail one by one.

9.2.1 Normal Mode:

The simplest mode of operation is the normal mode (WGM01:0 = 0). In this mode the counting
direction is always up (incrementing), and no counter clear is performed. The counter simply
overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bottom
(0x00). In normal operation the Timer/Counter Overflow Flag (TOV0) will be set in the same
timer clock cycle as the TCNT0 becomes zero. The TOV0 Flag in this case behaves like a ninth
bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt
that automatically clears the TOV0 Flag, the timer resolution can be increased by software. There
are no special cases to consider in the normal mode, a new counter value can be written anytime.
Using the output compare to generate waveforms in Normal mode is not recommended, since
this will occupy too much of the CPU time.
9.2.2 Clear Timer on Compare Match (CTC) Mode:
In Clear Timer on Compare or CTC mode (WGM01:0 = 2), the OCR0A, OCR0B registers are
used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the
counter value (TCNT0) matches the OCR0A/B. OCR0A/B define the top value for the counter,
hence also its resolution. This mode allows greater control of the compare match output
frequency. It also simplifies the operation of counting external events.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 91


Lab # 09 Using Timers/Counters of AVR MCU for Waveform Generation

The timing diagram for the CTC mode is shown in figure below. The counter value (TCNT0)
increases until a compare match occurs between TCNT0 and OCR0A/B, and then counter
(TCNT0) is cleared.

Figure 9.1: Timing Diagram for CTC Mode

An interrupt can be generated each time the counter value reaches the TOP value by using the
OCF0 Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating the
TOP value.
For generating a waveform output in CTC mode, the OC0A/B output can be set to toggle its
logical level on each compare match by setting the Compare Output mode bits to toggle mode
(COM0A1:0 = 1). The OC0A/B value will not be visible on the port pin unless the data direction
for the pin is set to output. The waveform generated will have a maximum frequency of fOC0A/B
= fclk_io/2 when OCR0A/B is set to zero (0x00). The waveform frequency is defined by the
following equation:

The N variable represents the prescale factor (1, 8, 64, 256, or 1024).

9.2.3 Fast PWM Mode:

The fast Pulse Width Modulation or fast PWM mode (WGM01:0 = 3) provides a high frequency
PWM waveform generation option. The fast PWM differs from the other PWM option by its
single-slope operation. The counter counts from BOTTOM to MAX then restarts from
BOTTOM. In non-inverting Compare Output mode, the Output Compare (OC0A) is cleared on
the compare match between TCNT0 and OCR0A/B, and set at BOTTOM. In inverting Compare
Output mode, the output is set on compare match and cleared at BOTTOM.

In fast PWM mode, the counter is incremented until the counter value matches the MAX value.
The counter is then cleared at the following timer clock cycle. The timing diagram for the fast

COMSATS University Islamabad (CUI) , Islamabad Campus Page 92


Lab # 09 Using Timers/Counters of AVR MCU for Waveform Generation

PWM mode is shown in Figure below. The TCNT0 value is in the timing diagram shown as a
histogram for illustrating the single-slope operation. The diagram includes non-inverted and
inverted PWM outputs. The small horizontal line marks on the TCNT0slopes represent compare
matches between OCR0A and TCNT0.

Figure 9.2: Timing diagram for fast PWM mode

In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC0A/B
pin. Setting the COM0A1:0 bits to 2 will produce a non-inverted PWM and an inverted PWM
output can be generated by setting the COM0A1:0 to 3.
The PWM frequency for the output can be calculated by the following equation:

The N variable represents the prescale factor (1, 8, 64, 256, or 1024).

9.2.4 Phase Correct PWM Mode:

The phase correct PWM mode (WGM01:0 = 1) provides a high resolution phase correct PWM
waveform generation option. The phase correct PWM mode is based on a dual slope operation.
The counter counts repeatedly from BOTTOM to MAX and then from MAX to BOTTOM. In
non-inverting Compare Output mode, the Output Compare (OC0A/B) is cleared on the compare
match between TCNT0 and OCR0A/B while up counting, and set on the compare match while
down counting. In inverting Output Compare mode, the operation is inverted. The dual-slope
operation has lower maximum operation frequency than single slope operation. However, due to
the symmetric feature of the dual-slope PWM modes, these modes are preferred for motor
control applications.
The PWM resolution for the phase correct PWM mode is fixed to eight bits. The counter is
incremented until the counter value matches MAX. When the counter reaches MAX, it changes

COMSATS University Islamabad (CUI) , Islamabad Campus Page 93


Lab # 09 Using Timers/Counters of AVR MCU for Waveform Generation

the count direction. The TCNT0 value will be equal to MAX for one timer clock cycle. The
timing diagram for the phase correct PWM mode is shown on Figure 3. The TCNT0 value is in
the timing diagram shown as a histogram for illustrating the dual-slope operation. The diagram
includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT0
slopes represent compare matches between OCR0A/B and TCNT0.

Figure 9.3: Timing diagram for Phase correct PWM mode

In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the
OC0A/B pins. Setting the COM0A/B1:0 bits to 2 will produce a non-inverted PWM on OC0A/B.
An inverted PWM output can be generated by setting the COM0A/B1:0 to 3.The PWM
frequency for the output when using phase correct PWM can be calculated by the following
equation:

The N variable represents the prescale factor (1, 8, 64, 256, or 1024).

Note: For description of registers related to Timer0, refer to Atmega328p


datasheet pages 138-148.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 94


Lab # 09 Using Timers/Counters of AVR MCU for Waveform Generation

In Lab:
Task 1:

A servomotor is connected to Timer OC0 pin and a potentiometer is connected to ADC


channel 0. Generate a PWM wave at Timer 0. The dutycycle of generated waveform should
vary according to the input voltage at channel 0 of the ADC (The duty cycle should vary as
you rotate the Potentiometer). By varying the On-Time of the signal the servo can be
rotated to different positions.

Figure 9.4: Positions of servo motor W.R.T duty cycle of wave

Complete the code for this task.

Code:

#include <inttypes.h>

#include <stdlib.h>

#include <avr/io.h>

#define F_CPU 16000000UL

#include <util/delay.h>

#include <string.h>

#include <math.h>

//********************************************************************
*

COMSATS University Islamabad (CUI) , Islamabad Campus Page 95


Lab # 09 Using Timers/Counters of AVR MCU for Waveform Generation

#define ADC_CHANNEL0 0

#define ADC_VREF 5 // Ref voltage for ADC is 5 Volts

#define ADC_RES 10 // Resoulution of ADC in bits

#define ADC_QLEVELS 1024 // Quantization levels for the ADC

unsigned char ADC_Initialize(); // Initialize ADC. Mode 1 =


Single Conversion, Mode 2 = Free Running

unsigned int ADC_Read(unsigned char channel); // Reads the result of


a single conversion from the ADC

/******************* Function Prototypes *********************/

void init_timer0(); // Initialize Timer0 for Fast PWM mode

void move_motor(int adc_value); // vlaue = 0 to 1023 for -90 to 90


degrees angle

#define SERVO_OCR OCR0A

#define MIN_ANGLE_OCR 17.0

#define SERVO_OCR_OFFSET 14.0

// ***********************************************************

// Main program

int main(void)

init_timer0(); // timer0 configured for Fast PWM mode

ADC_Initialize();

int adc_value;

while(1)

{ // Infinite loop; define here the

adc_value = ADC_Read(0);

_delay_ms(20);

// Set motor Position

move_motor(adc_value);

}}

void init_timer0()

OCR0A = (unsigned char) SERVO_OCR;

COMSATS University Islamabad (CUI) , Islamabad Campus Page 96


Lab # 09 Using Timers/Counters of AVR MCU for Waveform Generation

// Configure OC0A for output(PortD.6)

//Initialize timer0 for Fast PWM Mode, Non inverting,

// Set Prescaler = 1024

/* Function Initializes the ADC for 10-Bit Single Conversion mode*/

unsigned char ADC_Initialize()

// Left adjust result. Vref = AVCC = 5V

// Enable ADC

//Select the prescaler for 16 MHz System Clock

return(0);

/* Function reads the result of a single conversion from the ADC

channel given as an argument*/

unsigned int ADC_Read(unsigned char channel)

unsigned char ADC_lo;

unsigned char ADC_hi;

unsigned int result;

ADMUX &= ~(0x07); // clear previous selction of channel

ADMUX |= channel; // Select the new channel

// Delay needed for the stabilization of the ADC input voltage

_delay_us(10);

//wait for ADC to finish any ongoing opeartion

while((ADCSRA & (1<<ADSC)) != 0);

ADCSRA |= (1 << ADSC); //start conversion

while((ADCSRA & (1<<ADIF)) == 0);

ADCSRA |= (1<<ADIF); // clear the flag by writing 1 to it

//result = (ADCH<<8)|(ADCL & 0xC0); // Left adjust result

ADC_lo = ADCL;

ADC_hi = ADCH;

COMSATS University Islamabad (CUI) , Islamabad Campus Page 97


Lab # 09 Using Timers/Counters of AVR MCU for Waveform Generation

result = (ADC_hi<<2)|(ADC_lo >> 6); // Right adjust result

return result;

void move_motor(int adc_value) // vlaue = 0 to 1023 for -90 to 90


degrees angle

/** if we use 8-bit timer then -90 degree (1 ms) correspond to


OCR value of approximately 14

* and 90 degree (2ms) correspond to OCR value of approximately


31. So we must map the range

*of 0-1023 to 14-31*/ }

Simulation:

Figure 9.5 Simulation for In lab task

Hardware Design:
Implement the above task on hardware.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 98


Lab # 09 Using Timers/Counters of AVR MCU for Waveform Generation

In Lab task 2:
(To be specified by Lab Instructror)
Generate different waveforms using Timer0,1 and 2 as specified by your lab instructor.
View the generated waveforms on oscilloscope.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 99


Lab # 09 Using Timers/Counters of AVR MCU for Waveform Generation

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

Lab Assessment

Pre Lab
/1

In Lab /10
/5

Post Lab
/4

Instructor Signature and Comments

COMSATS University Islamabad (CUI) , Islamabad Campus Page 100


Lab # 10 Recording a Periodic Signal using Input Capture Feature of Timers/Counters

Lab # 10 Recording a Periodic Signal using Input


Capture Feature of Timers/Counters

Objectives:
 To introduce input capture feature of the Timers/Counters in microcontrollers.
 To emphasize preference of interrupt based designs over polling mechanisms.

Tools:

Software Tools:

 AVR Studio/ Atmel Studio


 Proteus ISIS
 AVRDUDESS
 Arduino IDE

Hardware Tools:

Name Value Quantity


Arduino Nano - 1
Resistor 4.7k Ω 1
Push button - 1
Function Generator - 1

Table 10.1: List of Components

Pre-Lab:

Input Capture:
In many applications, we are interested in measuring the elapsed time or the frequency of an
external event using a microcontroller. Using the hardware and functional units discussed in the
previous sections, we now present a procedure to accomplish the task of computing the
frequency of an incoming periodic signal. Figure 10.1 shows an incoming periodic signal to our
microcontroller.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 101


Lab # 10 Recording a Periodic Signal using Input Capture Feature of Timers/Counters

Figure 30.1 Use of the timer I/O systems of a microcontroller. The signal on top is fed into a
timer

The first necessary step for the current task is to turn on the timer system. To reduce power
consumption, a microcontroller usually does not turn on all of its functional systems after reset
until they are needed. In addition to a separate timer module, many microcontroller
manufacturers allow a programmer to choose the rate of a separate timer clock that governs the
overall functions of a timer module.
Once the timer is turned on and the clock rate is selected, a programmer must configure the
physical port to which the incoming signal arrives. This step is done using a special input timer
port configuration register. The next step is to program the input event to capture. In our current
example, we should capture two consecutive rising edges or falling edges of the incoming signal.
Again, the programming portion is done by storing an appropriate setup value to a special
register.
Now that the input timer system is configured appropriately, you now have two options to
accomplish the task. The first one is the use of a polling technique; the microcontroller
continuously polls a flag, which holds a logic high signal when a programmed event occurs on
the physical pin. Once the microcontroller detects the flag, it needs to clear the flag and record
the time when the flag was set using another special register that captures the time of the
associated free-running counter value. The program needs to continue to wait for the next flag,
which indicates the end of one period of the incoming signal. A programmer then needs to record
the newly acquired captured time represented in the form of a free-running counter value again.
The period of the signal can now be computed by computing the time difference between the
two captured event times, and based on the clock speed of the microcontroller, the programmer
can compute the actual time changes and consequently the frequency of the signal.
In many cases, a microcontroller cannot afford the time to poll for one event. Such situation
introduces the second method: interrupt systems. Most microcontroller manufacturers have
developed built-in interrupt systems with their timer input modules. Instead of continuously
polling for a flag, a microcontroller performs other tasks and relies on its interrupt system to
detect the programmed event. The task of computing the period and the frequency is the same as
COMSATS University Islamabad (CUI) , Islamabad Campus Page 102
Lab # 10 Recording a Periodic Signal using Input Capture Feature of Timers/Counters

the first method, except that the microcontroller will not be tied down constantly checking the
flag, increasing the efficient use of the microcontroller resources. To use interrupt systems, of
course, we must pay the price by appropriately configuring the interrupt systems to be triggered
when a desired event is detected. Typically, additional registers must be configured, and a special
program called an ISR must be written.
Suppose that for an input capture scenario, the two captured times for the two rising edges are
$1000 and $5000, respectively. Note that these values are not absolute times but the
representations of times reflected as the values of the free-running counter. The period of the
signal is $4000, or 16384 in a decimal form. If we assume that the timer clock runs at 10 MHz,
the period of the signal is 1.6384 ms, and the corresponding frequency of the signal is
approximately 610.35 Hz.

In Lab:

Task 1:
The expected input signal is a periodic pulse train. The task is to find the frequency/time period
and duty cycle of this signal. The frequency of this signal is expected to be less than 4 KHz. The
given code configures Atmega328P interrupt subsystem to work with external interrupts and
input capture of Timer1. It also performs the necessary calculations to find the frequency and
duty cycle of the input signal and displays it on a terminal. You will have to understand the code
and then configure Timer1 for input capture.

Code:
// This program configures the 16-bit Timer1 of Atmega328p for Input
Capture.

// The expected input signal is a periodic pulse train. The task is to


find

// the frequency/time period and duty cycle of this signal. The


frequency of

// this signal is expected to be less than 4 KHz.

//
**********************************************************************
*****/

#include <inttypes.h>

#include <stdlib.h>

#include <avr/io.h>

#include <avr\interrupt.h> // Add the necessary ones

COMSATS University Islamabad (CUI) , Islamabad Campus Page 103


Lab # 10 Recording a Periodic Signal using Input Capture Feature of Timers/Counters

#define F_CPU 16000000UL

#include <util/delay.h>

#include <string.h>

#include <math.h>

/****************** Definitions for UART *********************/

#include "debug_prints.c"

#define BAUD0 9600 // Baud Rate for UART

#define MYUBRR (F_CPU/8/BAUD0-1) // U2X = 1

/*********************************************************************
************/

/****************** Global Variables ************************/

unsigned char icp_low = 0;

unsigned char icp_high = 0;

unsigned int input_capt_counter=0;

unsigned int rising1 = 0;

unsigned int rising2 = 0;

unsigned int falling1 = 0;

unsigned char capture_complete=0;

float sig_freq = 0;

float sig_dc = 0;

/************************************************************/

#define TRUE 1

#define FALSE 0

/*************** Function Prototypes here ********************/

void timer_init(void); // Function to initialize Timer1


for Input Capture

void display_counter_values(void);

void display_signal_parameters(void);

void calculate_signal_param(void);

COMSATS University Islamabad (CUI) , Islamabad Campus Page 104


Lab # 10 Recording a Periodic Signal using Input Capture Feature of Timers/Counters

// ***********************************************************

// Main program

//

int main(void)

DDRB &= (1<<PB0); // Set PB0 (ICP1) for input

PORTB|= (1<<PB0); // Activate internal pull-up

UART0_init(MYUBRR);

printSerialInt(MYUBRR);

printSerialStrln("");

printSerialStr("F_CPU = ");

printSerialInt((int)(F_CPU/1000000));

printSerialStrln("MHz");

printSerialStrln("Lab 10: Input Capture");

timer_init();

//******* Write Code For This ********//

//Set interrupt sense control bits to falling edge for INT0

//Enable INT0 locally

// Enable interrupts globally

int i=0;

while(1)

if(capture_complete == TRUE)

display_signal_parameters(); // display frequency and duty cycle

COMSATS University Islamabad (CUI) , Islamabad Campus Page 105


Lab # 10 Recording a Periodic Signal using Input Capture Feature of Timers/Counters

capture_complete = FALSE;

for(i=0; i<8; i++) // wait for 2 seconds

_delay_ms(250);

printSerialStrln("Press the button ..");

/* This function will setup Timer1 for Input Capture Mode.

if Fclk = 16MHz, and prescaler = 8, then 1 count = 0.5us. 2000

counts will fit a Time period of 1ms (f = 1 KHz). 500 Counts

will fit a Time period of 0.25 ms (f = 4 KHz).

*/

void timer_init(void) // Write code for this function

ACSR &= ~(1<<ACIC); // Disconnect


the Analog Comparator output from the Input Capture Unit

// Normal Mode, OC1A and OC1B disconnected.

// Initially capture rising edge. Prescaler = 8

TCNT1L = 0;

TCNT1H = 0;

// Enable interrupt of Timer 1 input capture

/* Interrupt Service Routine for INT0. When the user presses

the button, the ISR clears TCNT1, capture_complete, rising1,

rising2 and falling1 global variables. Then it turns on the

interrupts for Timer1 Input Capture. */

ISR(INT0_vect)

//printSerialStrln("Processing External Interrupt 0: ");

rising1 = 0;

COMSATS University Islamabad (CUI) , Islamabad Campus Page 106


Lab # 10 Recording a Periodic Signal using Input Capture Feature of Timers/Counters

rising2 = 0;

falling1 = 0;

capture_complete = FALSE;

input_capt_counter = 0;

sig_freq = 0;

sig_dc = 0;

TCCR1B |= (1<<ICES1); // for rising edge on ICP1

TCNT1 = 0; // clear the free running counter of Timer 1

TIMSK1 |= (1<<ICIE1); // Enable interrupt of Timer 1 input


capture

/* ISR for Input Capture of Timer1. You need to write

code and complete this function*/

ISR(TIMER1_CAPT_vect)

//printSerialStrln("Processing Timer Interrupt: ");

icp_low = ICR1L;

icp_high = ICR1H;

input_capt_counter ++;

//printSerialInt((int)input_capt_counter);

//printSerialStrln("");

if(input_capt_counter == 2)

// Record the counter value on first Rising Edge

if(input_capt_counter == 3)

// Record the counter value on second Rising Edge

COMSATS University Islamabad (CUI) , Islamabad Campus Page 107


Lab # 10 Recording a Periodic Signal using Input Capture Feature of Timers/Counters

// Change the polarity of sensing

// Clear ICF flag as prescribed in the Datasheet Page 157


Section 20.9.3

if(input_capt_counter == 4)

// Record the counter value on first Falling Edge

// disable further interrupts of Timer 1 input capture

capture_complete = TRUE; // capture is complete at


this point

calculate_signal_param(); // calculate the Frequency and


Duty Cycle of the Input Signal

/** This function displays the values of the

captured edges 'rising1', 'rising2', and

'falling1'.

*/

void display_counter_values()

printSerialStr("Rising 1: ");

printSerialLong((long int) rising1);

printSerialStrln("");

printSerialStr("Rising 2: ");

printSerialLong((long int) rising2);

printSerialStrln("");

printSerialStr("Falling 1: ");

printSerialLong((long int) falling1);

printSerialStrln("");

COMSATS University Islamabad (CUI) , Islamabad Campus Page 108


Lab # 10 Recording a Periodic Signal using Input Capture Feature of Timers/Counters

/** Function to display the Frequency and Duty Cycle

of the Captured signal.*/

void display_signal_parameters(void)

printSerialStr("Frequency = ");

printSerialFloat(sig_freq);

printSerialStrln(" Hz");

printSerialStr("Duty Cycle = ");

printSerialFloat(sig_dc);

printSerialStrln(" %");

/** This function is called after all the required edges

are captured and saved in global variables 'rising1',

'rising2', and 'falling1'. It calculates the input signal

frequency and its duty cycle and saves them in corresponding

variables.*/

void calculate_signal_param(void)

printSerialStrln("Calculating Signal Parameters ... ");

if((rising2-rising1) != 0) // if denominator is non-zero

sig_freq = F_CPU/(8*(float)(rising2-rising1)); //Here


Prescalar = 8 so Ftimer == F_CPU/8

sig_dc = 100.0 * ((float)(falling1 -


rising2))/((float)(rising2-rising1)); // ON-Time/ Total Time * 100 %

else

sig_freq = 0;

sig_dc = 0;

COMSATS University Islamabad (CUI) , Islamabad Campus Page 109


Lab # 10 Recording a Periodic Signal using Input Capture Feature of Timers/Counters

display_counter_values();

display_signal_parameters();

Simulation:

Figure 10.4 Schematics for the input capture Lab

Hardware Design:
Implement In lab task on hardware. Connect a function generator to supply the input signal, and
a push button for interrupts. Use serial monitor of Arduino IDE to display the values.

Post lab Task:


Find out how input capture feature of microcontrollers can be used to record a signal from a TV
remote control. Submit a report of your findings.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 110


Lab # 10 Recording a Periodic Signal using Input Capture Feature of Timers/Counters

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

Lab Assessment

Pre Lab /1

In Lab /5
/10
Post Lab /4

Instructor Signature and Comments

COMSATS University Islamabad (CUI) , Islamabad Campus Page 111


Lab # 10 Recording a Periodic Signal using Input Capture Feature of Timers/Counters

COMSATS University Islamabad (CUI) , Islamabad Campus Page 112


Lab# 11 Serial Communication with UART and Interfacing Bluetooth HC-05

Lab # 11 Serial Communication with UART and


Interfacing Bluetooth HC-05

Objectives:
 To implement serial communication using UART of Atmega328p
 To establish Bluetooth connectivity between Atmega328p and an Android mobile device.

Tools:

Software Tools:

 AVR Studio/ Atmel Studio


 Proteus ISIS
 AVR DUDESS
 Arduino IDE

Hardware Tools:

Name Value Quantity


Arduino Nano - 1
USB Cable - 1
HC-05 Bluetooth Transceiver 1
Android Phone with Bluetooth 1
Table 11.1: List of Components

Pre-Lab:
Serial Communication:
Microcontrollers must often exchange data with other microcontrollers or devices. Data may be
exchanged by using parallel or serial communication links. With parallel techniques, an entire byte
of data is typically sent simultaneously from the transmitting device to the receiver device.
Although this is efficient from a time point of view, it requires eight separate lines for the data
transfer. In serial transmission, a byte of data is sent a single bit at a time. Once 8 bits have been
received at the receiver, the data byte is reconstructed. Although this is inefficient from a time
point of view, it only requires a line (or two) to transmit the data.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 113


Lab# 11 Serial Communication with UART and Interfacing Bluetooth HC-05

Figure 51.1Parallel vs Serial Communication

The ATmega328P is equipped with a host of different serial communication subsystems, including
the serial USART, SPI, and TWI. What all of these systems have in common is the serial
transmission of data. Before discussing the different serial communication features aboard the
ATmega328P, we review serial communication terminology.

Synchronous Vs Asynchronous Communication


In serial communications, the transmitting and receiving device must be synchronized to one
another and use a common data rate and protocol. Synchronization allows both the transmitter and
receiver to be expecting data transmission/reception at the same time. There are two basic methods
of maintaining ‘‘sync’’ between the transmitter and receiver: asynchronous and synchronous. In
an asynchronous serial communication system, such as the USART aboard the Atmega328p,
framing bits are used at the beginning and end of a data byte. These framing bits alert the receiver
that an incoming data byte has arrived and also signals the completion of the data byte reception.
The data rate for an asynchronous serial system is typically much slower than the synchronous
system, but it only requires a single wire between the transmitter and receiver. A synchronous
serial communication system maintains ‘‘sync’’ between the transmitter and receiver by
employing a common clock between the two devices. Data bits are sent and received on the edge
of the clock. This allows data transfer rates higher than with asynchronous techniques but requires
two lines, data and clock, to connect the receiver and transmitter.
Baud Rate

Data transmission rates are typically specified as a baud or bits per second rate. For example, 9600
baud indicates data are being transferred at 9600 bits per second.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 114


Lab# 11 Serial Communication with UART and Interfacing Bluetooth HC-05

Full Duplex

Often, serial communication systems must both transmit and receive data. To do both transmission
and reception simultaneously requires separate hardware for transmission and reception. A half-
duplex system has a single complement of hardware that must be switched from transmission to
reception configuration. A full duplex serial communication system has separate hardware for
transmission and reception.

Non-return to Zero Coding Format

There are many different coding standards used within serial communications. The important point
is the transmitter and receiver must use a common coding standard so data may be interpreted
correctly at the receiving end. The Atmel ATmega328p uses a non-return to zero coding standard.
In non-return to zero, coding a logic 1 is signaled by a logic high during the entire time slot
allocated for a single bit, whereas a logic 0 is signaled by a logic low during the entire time slot
allocated for a single bit.

Parity

To further enhance data integrity during transmission, parity techniques may be used. Parity is an
additional bit (or bits) that may be transmitted with the data byte. The ATmega16 uses a single
parity bit. With a single parity bit, a single-bit error may be detected. Parity may be even or odd.
In even parity, the parity bit is set to 1 or 0, such that the number of 1’s in the data byte including
the parity bit is even. In odd parity, the parity bit is set to 1 or 0, such that the number of 1’s in the
data byte including the parity bit is odd. At the receiver, the number of bits within a data byte
including the parity bit are counted to ensure that parity has not changed, indicating an error, during
transmission.

Serial USART

The Universal Synchronous and Asynchronous Receiver Transmitter (USART) provides full
duplex (two-way) communication between the MCU and another device. This is accomplished by
equipping the ATmega328P with independent hardware for the transmitter and receiver. The
USART is typically used for asynchronous communication. That is, there is not a common clock
between the transmitter and receiver to keep them synchronized with one another. To maintain
synchronization between the transmitter and receiver, framing start and stop bits are used at the
beginning and end of each data byte in a transmission sequence. The Atmel USART also has
synchronous features. Space does not permit a discussion of these USART enhancements.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 115


Lab# 11 Serial Communication with UART and Interfacing Bluetooth HC-05

Frame Formats
A serial frame is defined to be one character of data bits with synchronization bits (start and stop
bits), and optionally a parity bit for error checking. The USART accepts all 30 combinations of
the following as valid frame formats:

 1 start bit
 5, 6, 7, 8, or 9 data bits
 No, even or odd parity bit
 1 or 2 stop bits

Figure 11.2 UART Frame Format

In Lab:

Task 1:

You will configure (i.e. set baud rate, frame format, parity settings etc ) UART present in
Atmega328P for Asynchronous Serial Communication. The rest of the code implements the
transmit and receive functionality and uses them in an echo back mechanism. This means that the
program waits for any data received on the UART receiver and then transmits it back.

Code:
//*********************** Lab 11 ****************************

// In this code the students will configure the USART of the

// ATMega328P Microcontroller for Asyncronous Coummunication.

// The students will choose appropriate values for UBRRH and

// UBRRL registers for the desired Baud Rate. Then the Trans-

// -mitter and the receiver of the USART will be Enabled. The

// students will verify the correctness of their design on the

// Virtual Terminal in Proteus Simulation. The

COMSATS University Islamabad (CUI) , Islamabad Campus Page 116


Lab# 11 Serial Communication with UART and Interfacing Bluetooth HC-05

// students will also test their design Hardware.

/*************************************************************/

#include <avr\io.h> // Most basic include files

#include <avr\interrupt.h> // Add the necessary ones

#include <util\delay.h>

#include <string.h>

#define F_CPU 16000000UL // a System clock of 16 MHz

// ************** Definistion for USART **********************

#define BAUD 9600.00 // Baud Rate Declared as a


float

#define UBRR_VAL (F_CPU/(16*BAUD))-1 // Corresponding UBRR Value

// ***********************************************************

void USART_Init(unsigned int ubrr); // function to Initialize the USART

void USART_Transmit(unsigned char data); // Transmit Data via USART

unsigned char USART_Receive(void); // Receive Data via USART

void USART_send_str(char * string1); // Transmit a string

void USART_read_str(char * ); // Read the USART buffer

// ***********************************************************

unsigned int data_available = 0; // A flag to indicate that data is


available in the receive buffer

// Main program

int main(void)

USART_Init((unsigned int)UBRR_VAL);

unsigned char data;

while(1)

{ // Infinite loop; define here the

data = USART_Receive();

COMSATS University Islamabad (CUI) , Islamabad Campus Page 117


Lab# 11 Serial Communication with UART and Interfacing Bluetooth HC-05

_delay_ms(20); // a 20 ms Delay between receiving and


sending data

USART_Transmit(data);

void USART_Init(unsigned int ubrr)

/* Set baud rate */

UBRR0H = (unsigned char)(ubrr>>8);

UBRR0L = (unsigned char)ubrr;

/*Complete this code*/

/*set double speed operation to reduce Baudrate Error*/

/* Enable receiver and transmitter */

/* Set frame format: 8data, 1stop bit, odd parity */

void USART_Transmit(unsigned char data)

/* Wait for empty transmit buffer */

/* Put data into buffer, sends the data */

unsigned char USART_Receive(void)

/* Wait for data to be received */

/* Get and return received data from buffer */

void USART_send_str(char * str) // Transmit a string

char i=0;

for(i=0; i<strlen(str); i++)

COMSATS University Islamabad (CUI) , Islamabad Campus Page 118


Lab# 11 Serial Communication with UART and Interfacing Bluetooth HC-05

USART_Transmit(str[i]);

void USART_read_str(char * str) // Read a string from UART

char ch;

char i;

do

ch = USART_Receive();

str[i] = ch;

while(ch != '\0');

Simulation:

Figure 11.3: Serial Communication setup using UART of Atmega328P and a Virtual Terminal

COMSATS University Islamabad (CUI) , Islamabad Campus Page 119


Lab# 11 Serial Communication with UART and Interfacing Bluetooth HC-05

Hardware Design:

Use Serial Monitor of Arduino IDE to test this circuit. The main() function in the program
implements a loop-back. This means that whatever is received by the UART from the Serial
Monitor, it transmits it again to the Monitor. So whenever you type something on the Monitor, it
will get printed twice (once when you type it and once when it loops back).

Task 2: Interfacing HC-05 Bluetooth device and Communicating with an


Android Device

HC-05 is a module that is used to provide Bluetooth wireless connectivity to your microcontrollers.
HC-05 has a close cousin, the HC-06 also available in the market. Both devices are Bluetooth
transceiver modules but HC-05 can operate both as a Master or a Slave device whereas HC-06 can
only operate in the Slave mode. A Bluetooth master device can look for other BT devices and then
make a connection with them (called Paring in BT terminology). It is recommended that you get
an HC-05 device since the price is the same for the two modules. Following figure shows the two
modules side by side. The HC-05 has 6 pins compared to 5 pins of HC-06.

Figure 11.4 HC-05 and HC-06

Once paired with a device, the HC-05 acts as a communication bridge between the microcontroller
and the connected device.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 120


Lab# 11 Serial Communication with UART and Interfacing Bluetooth HC-05

Interfacing HC-05 with Arduino Nano

The following figure shows the electrical interface between the HC-05 and Arduino Nano. HC-05
is powered from the 5V and the GND pins of the Arduino, the TX and RX pins of the module are
connected to D8 and D9 of the Arduino board.

Figure 11.5 Interfacing HC-05 with Arduino Nano

HC-05 Modes of operation:

HC-05 and HC-06 operate in two modes.


1. Command Mode or AT mode
2. Communication Mode
Command mode is used to set configuration of the Bluetooth module (HC-05/06). These
configurations include baud rate, password, role (master/slave), address (unique for different
modules) etc. To start the module in this mode press and hold down the button on the corner of the
module when powering it. You can tell that the module is in communication mode by the blinking
of its LED. In communication mode, the LED will blink with a period of about 4 seconds. The
commands that can be issued to module are listed in the following link.
https://www.itead.cc/wiki/Serial_Port_Bluetooth_Module_(Master/Slave)_:_HC-05
Communication mode is used for normal bridge operation of the module. In this mode the module
sends (via Bluetooth) any data it receives on its UART receiver to the paired device. Similarly it
sends out any data it receives from the paired device to the UART transmitter.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 121


Lab# 11 Serial Communication with UART and Interfacing Bluetooth HC-05

Setting Configuration Parameters for HC-05

Upload the given code (for Arduino IDE) to the Arduino Nano and power up the HC-05 module
in Command mode. Now you can type in the AT commands (given in the link) and start
configuring your module. You have to implement the following sub tasks:
1. Find the configuration of your HC-05 Module
2. Change its password
3. Power the module in Communication mode
4. Connect (pair) it with your Mobile phone’s Bluetooth.
5. Demonstrate wireless communication using an Android App such as
https://play.google.com/store/apps/details?id=de.kai_morich.serial_bluetooth_terminal&
hl=en
6. End

//#define USE_SERIAL1 mySerial.begin(HC_BAUD);


#define HC_CONF_MODE // the HC-05 baud rate
#ifdef HC_CONF_MODE #endif
#define HC_BAUD 38400
#else Serial.begin(9600); // the
#define HC_BAUD 19200 Arduino Baud rate
#endif delay(1000);
#ifndef USE_SERIAL1 Serial.println("System Initialized");
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // (Rx,TX) }
#endif void loop()
void setup() {
{ if(Serial.available())
#ifdef USE_SERIAL1 {
Serial1.begin(HC_BAUD); #ifdef USE_SERIAL1
#else Serial1.print((char)Serial.read());
mySerial.begin(HC_BAUD); #else
// the HC-05 baud rate mySerial.print((char)Serial.read());
#endif #endif
}
Serial.begin(9600); // the Arduino Baud
rate else
delay(1000); {
Serial.println("System Initialized"); #ifdef USE_SERIAL1
if(Serial1.available())
} Serial.print((char)Serial1.read());
#else
void loop() if(mySerial.available())
{ Serial.print((char)mySerial.read());
if(Serial.available()) #endif
{ }
#ifdef USE_SERIAL1 }
Serial1.print((char)Serial.read());
#else

COMSATS University Islamabad (CUI) , Islamabad Campus Page 122


Lab# 11 Serial Communication with UART and Interfacing Bluetooth HC-05

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

Lab Assessment

Pre Lab
/1

/10
In Lab /5

Post Lab /4

Instructor Signature and Comments

COMSATS University Islamabad (CUI) , Islamabad Campus Page 123


Lab# 12: Interfacing Devices using SPI

Lab # 12: Interfacing Devices using SPI

Objectives:
 To learn about Serial Peripheral Interfacing (SPI) and SPI programming
 Implementation of SPI using microcontroller (ATmega328P) in proteus.

Tools:
Software Tools:
 Atmel Studio/ AVR Studio
 Proteus ISIS
 AVR DUDESS

Hardware Tools:

Name Value Quantity


Arduino Nano - 1
Breadboard - 1
MCP4821 - 1
Table 12.5: List of Components

Pre Lab:
Introduction to Serial Peripheral Interfacing (SPI)
Serial Peripheral Interface (SPI) is an interface bus commonly used to send data between
microcontrollers and small peripherals such as shift registers, sensors, and SD cards. It uses
separate clock and data lines, along with a select line to choose the device you wish to talk to.

A common serial port, the kind with TX and RX lines, is called “asynchronous” because there is
no control over when data is sent or any guarantee that both sides are running at precisely the same
rate. To work around this problem, asynchronous serial connections add extra start and stop bits
to each byte help the receiver sync up to data as it arrives. Both sides must also agree on the
transmission speed (such as 9600 bits per second) in advance

SPI works in a slightly different manner. It’s a “synchronous” data bus, which means that it uses
separate lines for data and a “clock” that keeps both sides in perfect sync. The clock is an oscillating
signal that tells the receiver exactly when to sample the bits on the data line. This could be the
rising (low to high) or falling (high to low) edge of the clock signal; the datasheet will specify
which one to use. When the receiver detects that edge, it will immediately look at the data line to
read the next bit.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 124


Lab# 12: Interfacing Devices using SPI

HOW SPI WORKS:


SPI consists of two shift or more registers. One at master side, others at slave side.In SPI, only one
side generates the clock signal .The side that generates the clock is called the “master”, and the
other side is called the “slave”. There is always only one master (which is almost always your
microcontroller), but there can be multiple slaves.When data is sent from the master to a slave, it’s
sent on a data line called MOSI, for “Master Out / Slave In”. If the slave needs to send a response
back to the master, the master will continue to generate a prearranged number of clock cycles, and
the slave will put the data onto a third data line called MISO, for “Master In / Slave Out”.

Slave Select (SS)

Slave select line tells the slave that it should wake up and receive / send data and is also used when
multiple slaves are present to select the one you’d like to talk to.

The SS line is normally held high, which disconnects the slave from the SPI bus just before data
is sent to the slave, the line is brought low, which activates the slave. When you’re done using the
slave, the line is made high again.

SPI Read and Write:


In connecting a device with SPI bus to a microcontroller, we use microcontroller as master and
SPI device as slave. Microcontroller generates SCLK which is SCLK pin of SPI. The information
address and data) is transferred between microcontroller and SPI device in group of 8 bits, where
address byte is followed immediately by data byte. To distinguish between the read and write
operations, the D7 bit of address byte is always 1 for write, while for read, D7 bit is low.

Figure 12.1 SPI Pins

In Lab:
SPI Programming in AVR:
In AVR, three Registers are associated with SPI. They are SPSR (SPI Status Register), SPCR (SPI
Control Register) and SPDR (SPI Data Register).

COMSATS University Islamabad (CUI) , Islamabad Campus Page 125


Lab# 12: Interfacing Devices using SPI

Figure 12.2 shows working of SPI.

Figure 12.2: Working of SPI

SPI Control Register 0:

SPI Control Register 0 is shown below.

SPI Status Register 0:


SPI Status Register 0 is shown below:

COMSATS University Islamabad (CUI) , Islamabad Campus Page 126


Lab# 12: Interfacing Devices using SPI

SPI Data Register 0:

The SPI Data register is a Read/write register. It contains data to be transmitted or received data.
Writing to SPDR register initiates data transmission.

Clock Polarity and phase in SPI:


In SPI communication, the master and slaves must agree on clock polarity and phase. Table 12.3
shows options of clock polarity and phase.

Table 12.6: SPI clock polarity and phase

MCP4821 DAC:

MCP4821 is a single channel 12-bit Digital-to-Analog converter (DAC) with internal voltage
reference. This device offers high accuracy and low power consumption, and is available in various
packages. Communication with the device is accomplished via a simple serial interface using SPI
protocols.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 127


Lab# 12: Interfacing Devices using SPI

Some of DAC features are:

 12-bit Resolution
 Single Channel Voltage Output
 2.7V to 5.5V Operation
 Operating Current 330 µA (typ)
 Internal Voltage Reference 2.048V
 Selectable Unity or 2x Gain Output
 works with SPI mode 0

Figure12.6: Pin diagram of MCP4821

(where 𝐺 is gain)

MCP4821 DAC SPI Register

Some features of MCP4821 DAC SPI Register are:

 Only one 16-bit data register


a) Bit 15 should always be written with zero
b) Gain 𝐺 = 2 if 𝐺𝐴 = and Gain 𝐺 = 1 if 𝐺𝐴 = 1
c) 𝑆𝐻𝐷𝑁 = 1 to activate device, otherwise shutdown
d) D11 down to D0 the digital input

Fig 12.7 16 bit data register

 MSB is shifted in first then LSB is shifted

COMSATS University Islamabad (CUI) , Islamabad Campus Page 128


Lab# 12: Interfacing Devices using SPI

 AVR has SPI module with 8-bit shift register


a) So AVR need to send 16-bit data in two portions
b) First send upper byte, then lower byte

Fig 12.8: Sending data from AVR to MCP 4821 Data register

In Lab Task:
The given code contains functions to write bytes to SPI and writing to DAC. Your task is to
write code to send a sequence of numbers to the DAC to generate a saw-tooth wave. Use gain
=2x

Code:
Complete and build the given code.

#include <avr\io.h> // Most basic include files

#include <avr\interrupt.h> // Add the necessary ones

#include <avr\signal.h> // here

#define F_CPU 16000000

#define MOSI 3

#define SCK 5

#define SS 2

void SPI_byte_send(char ebyte);

void write_SPI_DAC(unsigned int val);

void SPI_Init(void);

int main(void)

COMSATS University Islamabad (CUI) , Islamabad Campus Page 129


Lab# 12: Interfacing Devices using SPI

unsigned int val = 0;

DDRC=0xFF;

SPI_Init();

while (1)

// write code to generate a sawtooth waveform on DAC

void SPI_byte_send(char ebyte)

//This function send one byte through AVR SPI module

//This function should ensure that existing communication is


complete

//PORTC = SPSR;

SPDR = ebyte;

while(!(SPSR & (1<<SPIF)));

void write_SPI_DAC(unsigned int val)

//clear SS

PORTB &= ~(1<<SS);

//Send upper byte (0b0000xxxx) where xxxx is upper four bits of


Digital data

//Upper nible zero suggest GA'=0 SHDN'=0

SPI_byte_send(0b00110000 | ( (val>>8) & 0x0F )); //send


upper byte

//Send lower 8 bits of digital data

SPI_byte_send( val & 0xFF ); //send lower byte

COMSATS University Islamabad (CUI) , Islamabad Campus Page 130


Lab# 12: Interfacing Devices using SPI

//Set SS

PORTB |= (1<<SS);

//_delay_us(50);

void SPI_Init()

// Write code to initialize SPI

Simulation:

Figure 16.8: Schematic for In Lab task

COMSATS University Islamabad (CUI) , Islamabad Campus Page 131


Lab# 12: Interfacing Devices using SPI

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

Lab Assessment

Pre Lab
/1

/10
In Lab /5

Post Lab
/4

Instructor Signature and Comments

COMSATS University Islamabad (CUI) , Islamabad Campus Page 132


Lab# 12: Interfacing Devices using SPI

COMSATS University Islamabad (CUI) , Islamabad Campus Page 133

You might also like