You are on page 1of 141

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 has been developed for the CPE342 Microprocessor Systems and Interfacing
course offered at the Department of Electrical and Computer Engineering, at COMSATS
University Islamabad (CUI). The work demonstrated by the students in the labs constitute 25 %
of the total marks for this course. During the labs, students will work in groups comprising 2 to
3 students.

This manual comprises 12 laboratory exercises, each exercise comprises sections; a ‘Pre-Lab’,
an ‘In-Lab’ task and a ‘Post Lab’ task. Student are expected to have completed the ‘Pre-Lab’
tasks prior to entering the laboratory. In the lab, they will be required to perform ‘In-Lab’ task.
The ‘Post-Lab’ task is to be completed after the students leave the lab.

Students are graded on the ‘Pre-Lab’ and ‘In-Lab’ tasked via an oral exam and demonstration.
Students are not allowed to copy the work from other groups and must demonstrate original
effort. CUI has a zero tolerance anti-plagiarism policy.

In addition to the exercises in the manual, students will be required to complete two projects. A
‘Mini Lab Project’ and a ‘Final Lab Project’ that counts towards the second Lab Sessional and
Lab Final Exam respectively. The detailed grading policy is available in the Course Description
File (CDF).

COMSATS University Islamabad (CUI) , Islamabad Campus Page 2


EEE342 Microprocessor Systems & Interfacing

Acknowledgement
The labs for EEE-342 Microprocessor Systems and Interfacing were originally designed by Dr.
Omar Ahmad. The first draft of the manual was prepared by Ms. Kiran Nadeem, Mr. Raheel
Ahmed, Ms. Asma Ramay and Mr. Ali Ra-za Shahid. The first version was completed in Spring
2016 session. The sec-ond 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 the ATmega16 to the ATmega328p
microcontroller. The fourth version was completed in February 2018 in which some lab manuals
and lab tasks were improved. The fifth revision has been carried out by Dr. Haroon Ahmed Khan,
Dr. Omar Ahmed and Ms. Asma Ramay. The whole document was reformatted in this version
and all the laboratory tasks have been updated and upgraded. A summary of the revisions is
given in the table below:

History of Revision
Version and
Team Comments
Date of Issue
This is the first editable draft of EEE – 342 lab manual.
Version 1. Dr. Omar Ahmad
Labs were designed by Dr. Omar Ahmad and this
May 2016 Ms. Kiran Nadeem
manuscript was prepared by Ms. Kiran Nadeem.

Dr. Omar Ahmad


Version 2. The manual was remodeled according to the new OBE
Mr. Raheel Ahmed
September format. Some of the labs were improved.
Ms. Asma Ramay
2016
Mr. Ali Raza Shahid
Version 3. Dr. Omar Ahmad The manual was updated according to ATmega 328p
September Ms. Asma Ramay micro-controller.
2017
Version 4. Dr. Omar Ahmad Some of the labs were improved. Lab tasks were
February 2018 Ms. Asma Ramay modified and some new tasks were added.

Version 5. Dr. Haroon Khan The entire document has been reformatted. All the
September Dr. Omer Ahmed laboratory tasks have been revised, with a special
2021 Ms. Asma Ramay emphasis towards show casing the students’ ability to
work independently

For comments and suggestions please contact: haroon.ahmed@comsats.edu.pk / omer_ahmed@comsats.edu.pk

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 ............................................... 7
Objectives ................................................................................................................................. 7
Pre Lab ..................................................................................................................................... 7
In-Lab ..................................................................................................................................... 11
Post Lab .................................................................................................................................. 21
Lab # 02 Introduction to AVR Microcontroller Hardware Circuitry and Digital I/O Ports ..... 22
Objectives: .............................................................................................................................. 22
Pre-Lab ................................................................................................................................... 22
In Lab: .................................................................................................................................... 29
Post Lab .................................................................................................................................. 32
Lab # 03 Interfacing 7-Segment Display Using Digital I/O Ports ............................................. 33
Objectives: .............................................................................................................................. 33
Pre-Lab ................................................................................................................................... 33
Pre-Lab Task: ......................................................................................................................... 35
In Lab: .................................................................................................................................... 36
Post lab task:........................................................................................................................... 39
Critical Analysis / Conclusion ............................................................................................... 40
Lab # 04 LCD Interfacing with AVR Microcontroller .............................................................. 41
Objectives: .............................................................................................................................. 41
Pre-Lab ................................................................................................................................... 41
In Lab: .................................................................................................................................... 45
Post Lab .................................................................................................................................. 47
Lab # 05 Introduction to Assembly Language Programming of AVR Microcontrollers .......... 48
Objectives ............................................................................................................................... 48
Pre Lab ................................................................................................................................... 48
In-Lab ..................................................................................................................................... 51
Post Lab .................................................................................................................................. 57
COMSATS University Islamabad (CUI) , Islamabad Campus Page 5
EEE342 Microprocessor Systems & Interfacing

Lab # 06 Keypad Interfacing Using Digital I/O Ports ............................................................... 58


Objectives: .............................................................................................................................. 58
Pre Lab: .................................................................................................................................. 58
In-Lab: .................................................................................................................................... 61
Post Lab .................................................................................................................................. 65
Lab # 07: Interfacing Analog Sensors using Built-in ADC ....................................................... 67
Objectives: .............................................................................................................................. 67
Pre-Lab ................................................................................................................................... 67
In Lab: .................................................................................................................................... 73
Post Lab .................................................................................................................................. 78
Lab # 08 External and Internal Interrupts in AVR Microcontrollers ......................................... 79
Objectives ............................................................................................................................... 79
Pre Lab ................................................................................................................................... 79
Post Lab .................................................................................................................................. 91
Lab # 09 Using Timers/Counters of AVR MCU for Waveform Generation ............................. 92
Objectives: .............................................................................................................................. 92
Pre-Lab: .................................................................................................................................. 92
In Lab: .................................................................................................................................... 98
Post Lab ................................................................................................................................ 103
Lab # 10 Recording a Periodic Signal using Input Capture Feature of Timers/Counters ........ 104
Objectives: ............................................................................................................................ 104
Pre-Lab: ................................................................................................................................ 104
In Lab: .................................................................................................................................. 107
Post lab Task: ....................................................................................................................... 114
Lab # 11 Serial Communication with UART and Interfacing Bluetooth HC-05..................... 116
Objectives: ............................................................................................................................ 116
In Lab: .................................................................................................................................. 119
Critical Analysis / Conclusion ............................................................................................. 126
Lab # 12: Interfacing Devices using SPI.................................................................................. 128
Objectives: ............................................................................................................................ 128
Critical Analysis / Conclusion ............................................................................................. 140

COMSATS University Islamabad (CUI) , Islamabad Campus Page 6


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
 Microchip Studio (Version 7)
 AVR Studio (Version 4)
 Proteus ISIS
 WinAVR (Version 2010)

Pre Lab
One of the learning outcomes for the lab work during this semester is for students to gain
proficiency in using microcontrollers while interfacing them with multiple devices and
connecting them to a variety of networks. Microcontrollers are “programmable” chips. Users
can program these chips to do a variety of tasks. The main objective of this course would be to
learn how to effective program microcontrollers make them perform most common kinds of
tasks. The particular chip students will program in these labs is the AVR
ATmega328p microcontroller.
Programming would require the use of Integrated Development Environments (IDEs) with cross
compilers built in. Cross compilers can compile code for platforms in-addition to those they are
installed on. For example, most students will either use Windows (or Apple or Linux) based
computers/laptops. A cross compiler installed on Windows can be used to generate code that
will run on a microcontroller. This code has to be copied/burned on to the microcontroller for it
to run (Figure 1.1).

Figure 1.1 – Running cross compiled code on hardware

COMSATS University Islamabad (CUI) , Islamabad Campus Page 7


Lab # 01 Introduction to Development Tools & Lab Software

In case the actual hardware microcontroller is not available, the hardware can be emulated on
a Modelling and Simulation software. In this software you can model the microcontroller and
then burn/write the program/hex file onto the model and simulate it on the
software (Figure1.2).

Figure 1.2 – Running cross compiled code on a simulator

In the lab we will be using either Microchip Studio or AVR Studio as the cross-compiling IDE
and Proteus for modelling and simulation.

Pre Lab Task


You are strongly recommended to use your own laptop for all the laboratory tasks. In case you
do not have a laptop, you will be able to use AVR Studio and Proteus on the computers provided
in the MP/VLSI laboratory.
If you have a laptop, make sure that you download or acquire the following software from the
MP/VLSI lab and install the following software.

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

COMSATS University Islamabad (CUI) , Islamabad Campus Page 8


Lab # 01 Introduction to Development Tools & Lab Software

Language. Both approaches are different from each other. Each has its own merits as you will
learn during the coursework.

Microchip Studio:
Microchip Studio 7 is the integrated development platform (IDP) for developing and debugging
Atmel SMART ARM-based and Atmel AVR microcontroller (MCU) applications. Studio 7
supports all AVR MCUs. The Microchip Studio 7 IDP 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

COMSATS University Islamabad (CUI) , Islamabad Campus Page 9


Lab # 01 Introduction to Development Tools & Lab Software

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
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.3 shows the three
registers associated with Port B.

Figure 1.3 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.4.

Figure1.4 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.5 shows a basic Arduino sketch.

Figure 1.5 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.6.

Figure 1.6: 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.7).

Figure 1.7: 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.8.

Figure 1.8: 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.9 will appear on the screen. Layout will consist of source
Window, I/O window, message window and I/O toolbar.

Figure 1.9: 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 } }

Press F7 button to build output files of the project including object file and hex file.
COMSATS University Islamabad (CUI) , Islamabad Campus Page 14
Lab # 01 Introduction to Development Tools & Lab Software

In-Lab Task 3: Atmel Studio Learning Tutorial

Note:
As stated in the previous section, you can use either AVR studio or Microchip studio
to compile and debug your code. However, it is recommended that you use
Microchip Studio.

Task-1 (A) – Getting started with Microchip Studio


1. Launch Microchip 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 (figure 1.10).
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.11).

Figure 1.10 – How to create new project using Microchip Studio installed in Lab

Figure 1.11 – 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.12.

Figure 1.12 – AVR microcontroller Selection

4. Layout shown in figure 1.13 will appear on the screen. Layout will consist of
source code window and message window. Write the code given below in
the source window.

Figure 1.13 – Microchip Studio platform section wise overview

5. Press F7 button to build output files of the project including object file and
hex file. Try it out with the code given in task2.

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.14. 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
COMSATS University Islamabad (CUI) , Islamabad Campus Page 16
Lab # 01 Introduction to Development Tools & Lab Software

microcontrollers. To pick necessary components required for circuit, click on small P in


device window.

Figure 1.14: Proteus ISIS overview of window

2. After Clicking Pick devices menu as in figure 1.15 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.

Figure 1.15: Pick Devices for circuit diagram

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

COMSATS University Islamabad (CUI) , Islamabad Campus Page 17


Lab # 01 Introduction to Development Tools & Lab Software

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.16 on Proteus root sheet by using components indicated above.

Figure 1.16: Circuit Diagram for In-Lab Task 3

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.17. 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.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 18


Lab # 01 Introduction to Development Tools & Lab Software

Figure 1.17: Edit component menu


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

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:
 Microchip 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
For this lab, students need to use a microcontroller. A microcontroller is a programmable IC that
has many functionalities built-in the chip itself. Furthermore, microcontrollers have the ability
to send and receive both digital and analogue data via pins. The main outcome of these lab
sessions is that students should be able to program microcontrollers for a variety of tasks by the
end of the semester.
System Clock and Clock Options
The system clock frequency refers to the frequency generated from the system clock pre-scaler.
The AVR microcontroller unit (MCU) sports internal clock as well as external clock source.
System can run on 1MHz internal clock or external crystal oscillator circuits. The device is

COMSATS University Islamabad (CUI) , Islamabad Campus Page 22


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

shipped with internal RC oscillator at 8.0MHz and with the fuse CKDIV8 programmed, resulting
in 1.0MHz system clock.
The ATmega328p can operate up to 20 MIPS at 20-MHz.
On-board Controller
While it is possible to use a chip directly, it is sometimes much easier to use and program them
when the controller is mounted on a board. It so happens, that the ATmega328p comes mounted
on a number of boards. Students are recommended to use one of the two most popular variants
of these boards, namely:
1. Arduino Nano
2. Arduino Uno
The Arduino Uno is more flexible to use with a removable microcontroller, the Nano is a cheaper
alternative that matches most relevant capabilities of the Uno.
Arduino Nano
An Arduino Nano is small, cheap and breadboard friendly platform with the ATmega328p
surface mounted on it. The Arduino Nano is programmed using the Arduino Software (IDE). To
program Arduino Nano in offline mode, you need to install the Arduino Desktop IDE. Arduino
after connecting a PC via USB cable. This also provides power to the board, as indicated by an
LED (On the bottom of the Arduino Nano 2.x and the top of the Arduino Nano 3.0).
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

COMSATS University Islamabad (CUI) , Islamabad Campus Page 23


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

• 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

Figure 2.2 shows schematics of Arduino Nano.

Figure 2.2 Schematics of Arduino Nano

COMSATS University Islamabad (CUI) , Islamabad Campus Page 24


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

Arduino Uno
Please review figure 2.3 and 2.4 for Arduino Uno. Do note that both boards use the AVR
Atmega328P microcontroller.

Figure 2.3 – An Arduino Uno Board

Figure 2.4 – Basic Pin-out of the Arduino Uno Development Board

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.
COMSATS University Islamabad (CUI) , Islamabad Campus Page 25
Lab # 02 Introduction to AVR Microcontroller Hardware Circuitry and Digital I/O Ports

Avrdude is a command line program, AVRDUDESS is a GUI for AVRDUDE. It supports all
programmers and MCUs that AVRDUDE supports.

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.


Please note it is often a source of confusion with students. The phrase “Port” is used in two
contexts, either in terms of the hardware pins or the registers. Case-in-point, PORTD may imply
the hardware pins (numbers 2-6 & 11-13) or it may imply one of the three registers (8-bit memory
storage element) associated with the pins, as shown in Figure 2.5. Each bit in each register
corresponds to one pin.

Figure 2.5 – Pins and corresponding registers

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

COMSATS University Islamabad (CUI) , Islamabad Campus Page 26


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

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.

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

COMSATS University Islamabad (CUI) , Islamabad Campus Page 27


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

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;

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;

Figure 2.6 – Role of IO Registers in the ATmega328p

COMSATS University Islamabad (CUI) , Islamabad Campus Page 28


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

Pre lab Task:


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

Task 2:
Install AVRDUDESS on to your computer/laptop.

Task 3:
Please download datasheets of ATmega328P and Arduino Uno/ Nano.
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

} }

COMSATS University Islamabad (CUI) , Islamabad Campus Page 29


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

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.
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.7).
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.7: Burning a hex file using AVRDUDESS

COMSATS University Islamabad (CUI) , Islamabad Campus Page 30


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

Set up your Arduino Nano or Uno with a resistor and LED as per the following figure and test
the hardware.

Figure 2.8 – Breadboard View Basic Circuit of ATmega328P


Task 2:
Build the following program on Microchip Studio and add comments against each line of code.
You may simulate it on Proteus with an LED-Bar. Try adding a delay in the loop to be able to
visually register the output.
Assembly Code
; add the value 3 to R20 ten times and passes it on to port B

.INCLUDE <M328PDEF.INC>
LDI R18, 0XFF
OUT DDRB, R18
LDI R21, 3
LOOP:
LDI R16, 10
LDI R20, 0
AGAIN:
ADD R20, R21
OUT PORTB, R20
DEC R16
BRNE AGAIN
RJMP LOOP
Task 3:
(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.

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

COMSATS University Islamabad (CUI) , Islamabad Campus Page 31


Lab # 02 Introduction to AVR Microcontroller Hardware Circuitry and 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 32


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/ Microchip 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 33


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 34


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 35
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 36


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 37


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 38


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 39


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 40


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:
 Microchip 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
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 also has a microcontroller in it. This microcontroller is already coded to display characters
on the screen. Therefor to use an LCD a controller to controller interface is required.
LCD control unit (Controller)
The LCD controller is responsible for all the operations with the LCD. These operations may
include (but are not limited to):
 movement of curser,
 clearing display,
 printing characters,
 special character generation etc.
HD44780U and S6A0069 are common examples of LCD control unit. An LCD controller’s
internal memory comprises of Character Generator ROM (CGROM), Character Generator RAM
(CGRAM) and Display Data RAM (DDRAM).d
 Character Generator ROM (CGROM) contain predefined character fonts table.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 41


Lab # 04 LCD Interfacing with AVR Microcontroller

 Character Generator RAM (CGRAM) stores customized character table


 Display Data RAM (DDRAM) stores display data represented in 8-bit character codes.
LCD Pin Configuration

Figure 4.1 shows the pin configuration of LCD.

Figure 4.1 Basic Pin-out of LM016L LCD

Table 4.2 provides the description of the pins:

Pin Symbol Function Description


1 VSS Ground Keep it at 0 V
Main power
2 VCC Keep it at +5 V
supply
Power supply for
3 VEE Contrast can be adjusted by providing a variable resistor through VCC
contrast control
RS = 0 means that D0-D7 will be interpreted as Command
4 RS Register select
RS = 1 means that D0-D7 will be interpreted as Data
R/W = 0 to write to the LCD register
5 R/W Read/write R/W = 1 to read from the LCD register
Keep it grounded for normal display operation
This should be toggled to High then Low for any data/command to be
6 EN Enable passed to the LCD
This pin should remain high for a minimum of 450ns
7 D0
8 D1
These pins can be used to send both commands and data depending on
9 D2
the value of the RS pin.
10 D3 Data OR
Command pins Data can be sent both in 8-bit mode, utilizing all 8 pins, or in the 4-bit
11 D4
mode, utilizing only pins D0-D3, in case there is a constraint with regards to
12 D5 available number of pins on the producer
13 D6
14 D7
Backlight power
15 LED+ +5 V
supply
16 LED- Backlight ground 0V
Table 4.2: LCD Pin-out Detail

COMSATS University Islamabad (CUI) , Islamabad Campus Page 42


Lab # 04 LCD Interfacing with AVR Microcontroller

LCD communication modes


LCD has 2 communication modes. The LCD can be interfaced using 3 control pins (EN, R/W,
RS) with either 8 pins or 4 pins for commands or data.
1. 8-bit communication
Data and commands can be sent by using 8 data pins simultaneously (D0-D7). Each
instruction executes in 1 cycle for 1-byte instruction.
2. 4-bit communication
Data and commands can be sent by using only 4 data pins (D0-D3). Each instruction
normally executes in 2 cycles for 1-byte instruction i.e. 1 nibble per cycle

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.
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
Sending Commands to LCD:
1. Clear the RS pin (logic zero)
2. Pass the appropriate Command to the data pins (via connected buffer/port)
3. The command should be sent as per command syntax specified in the Datasheet (see
Table 5.2)
4. Set the EN pin (logic one) and hold for at least 450ns

COMSATS University Islamabad (CUI) , Islamabad Campus Page 43


Lab # 04 LCD Interfacing with AVR Microcontroller

5. Clear the EN pin (logic zero)


Sending Data to the LCD:
1. Set the RS pin (logic one)
2. Pass the appropriate Data to the data pins (via connected buffer/port)
3. The data to be displayed should be sent in the form of standard 8-bit ASCII code
4. Set the EN pin (logic one) and hold for at least 450ns
5. Clear the EN pin (logic zero)
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 44


Lab # 04 LCD Interfacing with AVR Microcontroller

Abbreviations used in Table 4.3:

Pre Lab Tasks


Task 1:
Find hexa-decimal codes for commands mentioned in LCD initializing heading using Table 4.3.
Task 2:
Write an assembly language program that is able to display the numbers ‘0’ to ‘9’ on an LCD as
connected in figure 5.2. [hint: look up ASCII table]

In Lab:
Task-1
Consider the basic wiring shown between an ATmega328P chip and an LCD in figure 4.2.
Write and execute a C-program on Proteus that is able print your name on the first row of the
LCD and your roll-number on the second row of the LCD.

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

Task-2
Consider your controller connected to an 8×dipswitch, a push-button and an LCD. Program your
controller in a way that whenever the push-button is pressed, the input from the dipswitch should
be pushed on to the LCD as an ASCII character. Execute your code on Proteus.

Post lab:
Task 1:
Implement the in-lab task 2 for the 4-pin communication mode on Proteus. Additionally, add a
5×dip-switch array at an input. Use the dip switch to pass 8-bit ASCII code, one nibble at a time,
to be displayed on the LCD. Toggle the 5th switch to indicate that one nibble is ready to load.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 46


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 47


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/ MicrochipStudio
 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

Introduction to Assembly Programming

This lab would introduce students to the ATmega328P assembly language comprising 132
instructions. There are various advantages of using assembly, including, but not limited to:
 Program written in assembly is faster to execute
 The execution time can be measured precisely
 It is possible to generate very specific delays
 Code with a small program size can be generated
 Programmers can control the controller directly without abstractions
 Programmers can optimize the code for latency

COMSATS University Islamabad (CUI) , Islamabad Campus Page 48


Lab # 05 Introduction to Assembly Programming of AVR Microcontrollers

Whenever a program for ATmega328P is compiled, a .hex file is generated that comprises
the machine coded version of the program. Assembly language is an English type
representation of machine code. Every line machine code can be represented by a
corresponding line of assembly code, and vice versa.
An assembly language program written by a programmer can be “assembled” into machine
code. Once the machine code (.hex file) is loaded into the program memory of the
microcontroller, the ALU starts executing each instruction 1 at a time. The ATmega328P
operates in a two-stage pipeline.
In every instruction cycle, every instruction is fetched, then it is decoded (to ascertain the
“instruction” and the operands), executed and stored back.
All assembly language instructions are 1 of 7 kinds:
1. Mathematical instructions
2. Logical instructions
3. Bit manipulation instructions
4. Branching instructions
5. Data transfer instructions
6. I/O instructions
7. Configuration and control of MCU components (Timers, ADCs, serial comms etc.)
Invariably, almost all instructions involve movement of data between general purpose
registers (GPRs) and other memory components. This is because all mathematical, logical,
and branching instructions work with general purpose registers (GPRs) only. The types of
movements are illustrated in figure 5.1. and the instructions summarized in table 5.2.

Figure 5.1 – A summary of all possible data movements and their corresponding assembly language instruction

COMSATS University Islamabad (CUI) , Islamabad Campus Page 49


Lab # 05 Introduction to Assembly Programming of AVR Microcontrollers

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

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

COMSATS University Islamabad (CUI) , Islamabad Campus Page 50


Lab # 05 Introduction to Assembly Programming of AVR Microcontrollers

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)

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

COMSATS University Islamabad (CUI) , Islamabad Campus Page 51


Lab # 05 Introduction to Assembly Programming of AVR Microcontrollers

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

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

COMSATS University Islamabad (CUI) , Islamabad Campus Page 52


Lab # 05 Introduction to Assembly Programming of AVR Microcontrollers

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.

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

COMSATS University Islamabad (CUI) , Islamabad Campus Page 53


Lab # 05 Introduction to Assembly Programming of AVR Microcontrollers

Code:

Simulation:

COMSATS University Islamabad (CUI) , Islamabad Campus Page 54


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 55


Lab # 05 Introduction to Assembly Programming of AVR Microcontrollers

Simulation:

COMSATS University Islamabad (CUI) , Islamabad Campus Page 56


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 57


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/ Microchip Studio


 Proteus ISIS
 AVRDUDESS

Hardware Tools:

Name Value Quantity


Arduino Nano - 1
4X4 Keypad - -
Resistors 100Ω 8
Table 6.1: 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 58


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:


As can be seen in figure 6.1, the buttons consist of 16 switches that are normally open. When
one button is pressed, a pair of pins are connected, as seen in figure 6.2. As shown in the
figure, the R2 and C2 pins will help determine the button that is pressed.

Figure 6.2 – Standard 4x4 Keypad

To use a keypad with a microcontroller, it should be connected to in a way where either the
rows are the input to the controller and the columns are the output to the microcontroller, or
vice-versa. Suggested connections are shown in figure 6.3.

Figure 6.3 – Button Matrix Connection

COMSATS University Islamabad (CUI) , Islamabad Campus Page 59


Lab # 06 Keypad Interfacing Using Digital I/O Ports

You should remember the role of IO-registers in the ATmega328p as illustrated in figure
6.4. Assume all the 4 rows are initially set as input (by virtue of DDRx register). The
programmer will have to scan the rows to determine if a button is pressed. Normally, the
values on the row would be all 0 i.e. R4-R1 == 0000. When the button is pressed as shown
in figure 5.2, the value would change to R4-R1 == 0010.
The fundamental idea is that the program keeps scanning the rows as long as no button is
pressed. However, as soon as a button is pressed, inverse the rows to outputs and the columns
to input. This would happen so fast that the button will still be pressed. So, on scanning the
columns, C4-C1 == 0010. In this one can identify the button that is pressed, which in this
case is ‘5’. [hint: the sequence 0010-0010 could signify ‘5’, or R1-C4 can be represented by
1000-0001 signifying ‘A’]

Figure 6.4 – ATmega328p port registers roles

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 60


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

/*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

COMSATS University Islamabad (CUI) , Islamabad Campus Page 61


Lab # 06 Keypad Interfacing Using Digital I/O Ports

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;

return 0;

unsigned char read_keypad()

unsigned char columns;

COMSATS University Islamabad (CUI) , Islamabad Campus Page 62


Lab # 06 Keypad Interfacing Using Digital I/O Ports

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*/

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;

COMSATS University Islamabad (CUI) , Islamabad Campus Page 63


Lab # 06 Keypad Interfacing Using Digital I/O Ports

Task 2-Simulation:

Figure 6.5: Simulation of In Lab task

Task 3- 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.

Task 4:

Write a code that passes out the ASCII code of the character that is pressed, on to PORTD
of an ATmega328p.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 64


Lab # 06 Keypad Interfacing Using Digital I/O Ports

Model and simulate the task shown in figure 6.6 on Proteus

Figure 6.6 – In Lab Task 4

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

COMSATS University Islamabad (CUI) , Islamabad Campus Page 65


Lab # 06 Keypad Interfacing Using Digital I/O Ports

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 66


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

Lab # 07: Interfacing Analog Sensors using Built-in


ADC

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

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

Hardware Tools:

Name Value Quantity


Arduino Nano - 1
Breadboard - 1
LM35 - 1
Table 7.1: 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 67


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 68


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 69
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 70


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 explicitly. When the
conversion is complete, the result is placed in the ADC Data register pair and no further
conversion takes place.
7.4.2 Free Running Conversion Mode
Once this mode is initiated, the ADC will start a conversion immediately. It will
automatically start the next conversion as soon as the previous conversion is complete. This
process is continuous. Once started, it takes the ADC 13 cycles to complete a single
conversion. In this mode ADC data register has to be read before new value overwrites it.
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). It has the following main features:
 Calibrated Directly in Celsius (Centigrade)
 Linear + 10-mV/°C Scale Factor
 Rated for Full −55°C to 150°C Range

COMSATS University Islamabad (CUI) , Islamabad Campus Page 71


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

 Operates From 4 V to 30 V
In order to understand the working principle of LM35 temperature sensor we have to
understand the linear scale factor. In the features of LM35 it is given to be +10 mills volt
per degree centigrade. It means that with increase in output of 10 mills volt by the sensor
Vout pin the temperature value increases by one. For example, if the sensor is outputting
100 mills volt at Vout pin the temperature in centigrade will be 10-degree centigrade. The
same goes for the negative temperature reading. If the sensor is outputting -100 mills volt
the temperature will be -10 degrees Celsius.

Figure 7.1 LM35 Pinout

The LM35 can be used in multiple configurations. Each configuration will have different
outcomes. In the configuration shown in figure 7.2, you can only measure the positive
temperature from 2 degrees Celsius to 150 degrees Celsius.

Figure 7.2 – The LM35 Basic Configuration

In this configuration, we simply power the LM35 and connect the output directly to analogue to
the ADC. In this mode, the temperature can be calculated as follows:
𝑉𝑜𝑙𝑡𝑎𝑔𝑒 𝑟𝑒𝑎𝑑 𝑏𝑦 𝐴𝐷𝐶
𝐶𝑒𝑙𝑐𝑖𝑢𝑠 =
10𝑚𝑉
It is recommended that the output is pulled down (or grounded) with an 80KΩ –100KΩ resistor
for stable output as shown in figure 7.3.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 72


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

Pre lab Task:


Investigate and describe 5 analogue sensors that are commonly used in embedded systems.
Explain what physical quantity they measure and provide the mapping function for the output
voltage individually. Please note, all 5 sensors should sense different physical phenomenon.

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.

/* 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)

COMSATS University Islamabad (CUI) , Islamabad Campus Page 73


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

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

#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();

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;

COMSATS University Islamabad (CUI) , Islamabad Campus Page 74


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

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

unsigned char ADC_Initialize()

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

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

// 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;

COMSATS University Islamabad (CUI) , Islamabad Campus Page 75


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

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

to floating point Voltage using the ADC_RES (resolution)

and ADC_REF (reference voltage) defined earlier*/

float ADC_Convert(unsigned int ADC_value)

{ //Students have to convert ADC value into voltage

/** 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)

{ //Students have to convert voltage to temperature

/** 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 76


Lab # 07 Interfacing Analog Sensors using Analog to Digital Converter

Proteus Simulation

Figure 7.3: 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 77


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 /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 78


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

 MicrochipStudio or AVR Studio


 Proteus
 AVRDUDESS
Hardware Tools
Name Value Quantity
Arduino Nano - 1
Breadboard - 1
Switches - 2
LEDs - 8
Table 8.1: 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 79


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 ATmega328p has two classes of interrupts. 2 are known as external interrupts that can
respond to any kind of change on PD2 and PD3. The associated registers with external interrupts
are:
 EICRA
 EIMSK &
 EIFR
3 interrupts are known as pin-change interrupts that are associated with Ports B, C and D
respectively. They can respond to any change on the pins of all ports on the ATmega328p. the
associated registers are:
 PCMSK0 (associated with PORTB)
 PCMSK1 (associated with PORTC)
 PCMSK2 (associated with PORTD)
 PCICR &
 PCIFR
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.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 80


Lab # 08 External and Internal Interrupts in AVR Microcontrollers

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.
 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.
COMSATS University Islamabad (CUI) , Islamabad Campus Page 81
Lab # 08 External and Internal Interrupts in AVR Microcontrollers

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

4. Executes the corresponding interrupt service subroutine.

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 82


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 83


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 84


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 85


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 86


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 87


Lab # 08 External and Internal Interrupts in AVR Microcontrollers

int main(void)

ADC_Initialize();

//Disable digital IO

//Configure port for output

// clear previous selction of channel

// Select the new channel

// Enable interrupts globally

// 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 88


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 89


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 90


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 /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 91


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 built into the ATmega328p are essentially “Counters” that are independent of the
program cycle. i.e. once the Counter/Timer starts counting, it does not consume any program
cycles. It runs in parallel to the program being executed, incrementing after a fixed time interval,
depending on how it is configured. In the simplest mode of execution, once a timer starts, it will
increment every cycle of the system clock, while the program in the program memory will run
at tandem.
Timer values can be monitored, and automatically compared to other values. Events like timer
overflowing or matching a constant value can be bound to interrupts, i.e. the main program can
be interrupted in case any of these events happens. This capability can be leveraged in a number
of ways, Timers can be used to

COMSATS University Islamabad (CUI) , Islamabad Campus Page 92


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

 Generate delays,
 To produce general timed events (i.e. display of a clock),
 To trigger the ADC,
 To generate PWM signals or
 Analyse incoming signals etc.
At ATMega328p has 3 timers namely:
 Timer0 (8-bit)
 Timer1 (16-bit)
 Timer2 (8-bit)
As mentioned before, the timers are essentially counters, incrementing every clock cycle. The
clock can be the system clock as it is. It can also slow down the system clock by fixed factors.
Additionally, AVR Timers are also capable of using external clock sources.
Each timer construct broadly comprises the following registers:
 TCNTn (The timer/counter)
 TCCRn (Multiple configurations & control registers)
 OCRn (Two comparison registers, to compare constant with the timer)
 TIMSKn (Masking register, to enable interrupts)
 TIFRn (Flag register, to monitor timer events)
Please refer to the ATmega328P Datasheet or your lecture material for detailed working of these
registers for timers 0, 1 & 2, before you proceed. These registers are referred to and used in the
sections that follow.

Figure 9.1 – Timers in the ATMega328p Controller

COMSATS University Islamabad (CUI) , Islamabad Campus Page 93


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

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.
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.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 94


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

Figure 9.2: 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
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.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 95


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

Figure 9.3: 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
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

COMSATS University Islamabad (CUI) , Islamabad Campus Page 96


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

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.4: 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 97


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.5: 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 98


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 99


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 100


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.6 Simulation for In lab task

Hardware Design:
Implement the above task on hardware.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 101


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 102


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 /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 103


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/ Microchip 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:
Timer1 provided in the ATmega328p has an input capture utility. To put it very simply, if you
connect ICP1 pin to a periodic signal source, the microcontroller can detect falling or rising
edges. Therefore, a transition from low to high or high to low is a detectable event. Timer 1 input
capture can be summarised as follows:
1. Timer1 can be configured in way that, whenever either a rising edge or a falling edge on
ICP1 is detected, the value of Timer1 is stored in the 16-bit ICR1 register
2. The running program can detect this event either by pooling the ICF1 flag or by using
interrupts (TIMER1_CAPT). The program should copy the value from the ICR1 register
on to a general-purpose register (GPR) before it is overwritten)

COMSATS University Islamabad (CUI) , Islamabad Campus Page 104


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

Figure 10.1 shows a visual representation of input capture.

Figure 10.1 – Visual representations of Timer1 input capture

Use-Cases
Input capture capability has many potential benefits. The most common use case is to use input
capture to study the nature of an incoming signal. One can use input capture to determine the
period and frequency of some types incoming signals. This may be achieved by capturing two
consecutive rising edges (i.e. timer 1 value at edgen and edgen+1) and measure the period in
terms of number of cycles. If one is aware of the system frequency (i.e. period of one cycle), the
period and frequency of the incoming signal can be calculated.
Furthermore, it may be used to determine the duty cycle of a signal as well by capturing the
consecutive rising, falling, and rising edges, as illustrated in figure 10.2.

Figure 10.2 – Calculating duty cycle of incoming signal with input capture

COMSATS University Islamabad (CUI) , Islamabad Campus Page 105


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

Another example is to use input capture with an ultrasonic sensor as shown in figure 10.3. These
sensors generate a continuous low signal output (on the “Echo” pin). When triggered (on the
“Trig” pin):
1. The output changes from low to high.
2. An ultrasonic sound wave (chirp) is sent out via a transducer
When the wave encounters a solid obstacle, it reflects back the echo. This echo is captured by
the second transducer. At this point the output transitions back to low.

Figure 10.3 – The HC-SR04 Ultra-sonic distance sensor

Input capture can be used to capture the echo-time pulse (the number of cycles the pulse
remained high. This represents the time for the round trip of the sound wave. Half that time
represents time for the one-way travel. We know that the speed of sound at ambient temperatures
is approximately 340 m/s. If the time of the one-way trip is computed (considering the system
clock), the distance of the sensor from the solid object can be calculated.

Working
Timer 1 has to be running for this work. The input capture can be activated by setting the
ICES1 bit in the TCCR1B register. Typical steps for capturing edge arrival time for input
capture function (ICF) can be summarized as follows:
1. Initialize TCCR1 registers for proper mode, enabling/disabling noise canceller,
selection of edge (positive/negative)
2. Monitor the ICF flag in TIFR1
3. Upon arrival of the edge, the TCNT1 value is loaded into the ICR1 register
automatically
4. The value in ICR1 needs to be transferred to a GPR. When the low byte is read form
ICR1L, the high byte is copied into the high byte temporary register (TEMP). When
the CPU reads the ICR1H, I/O location it will access the TEMP Register. Therefore,
always read the low byte first

COMSATS University Islamabad (CUI) , Islamabad Campus Page 106


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

Figure 10.4 – Set the ICIE flag to 1 to enable input capture interrupt

Alternatively, and preferably, interrupts may be used


1. Enable the input capture interrupt in the TIMSK1 register
2. Initialize TCCR1 registers for proper mode, enabling/disabling noise canceller,
selection of edge (positive/negative)
3. Upon arrival of the edge, the TCNT1 value is loaded into the ICR1 register
automatically
4. The program should be directed to the interrupt service routine,
ISR(TIMER1_CAPT_vect)
5. In the ISR, the value in ICR1 needs to be transferred to a GPR. When the low byte is
read form ICR1L, the high byte is copied into the high byte temporary register
(TEMP). When the CPU reads the ICR1H, I/O location it will access the TEMP
Register. Therefore, always read the low byte first
Please refer to the ATmega328P Datasheet or your lecture material for detailed working
of these registers for timers 0, 1 & 2, before you proceed. These registers are referred to
and used in the sections that follow:

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

COMSATS University Islamabad (CUI) , Islamabad Campus Page 107


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

// 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

#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

COMSATS University Islamabad (CUI) , Islamabad Campus Page 108


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

/*************** 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);

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

// Main program

//

int main(void)

// Set PB0 (ICP1) for input

// 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)

COMSATS University Islamabad (CUI) , Islamabad Campus Page 109


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

if(capture_complete == TRUE)

display_signal_parameters(); // display frequency and duty cycle

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. */

COMSATS University Islamabad (CUI) , Islamabad Campus Page 110


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

ISR(INT0_vect)

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

rising1 = 0;

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

COMSATS University Islamabad (CUI) , Islamabad Campus Page 111


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

if(input_capt_counter == 3)

// Record the counter value on second Rising Edge

// 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: ");

COMSATS University Islamabad (CUI) , Islamabad Campus Page 112


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

printSerialLong((long int) falling1);

printSerialStrln("");

/** 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)

//Complete this function

display_counter_values();

display_signal_parameters();

COMSATS University Islamabad (CUI) , Islamabad Campus Page 113


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

Simulation:

Figure 10.5 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 114


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

Data Analysis /4 /10

Data
Post Lab /4 /4
Presentation

Writing Style /4

Instructor Signature and Comments:

COMSATS University Islamabad (CUI) , Islamabad Campus Page 115


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 116


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

Figure 11.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.
The serial communications protocols with built-in support in the ATmega series controllers are
shown in figure 11.2. This lab will cover UART/USART only.

Figure 11.2 – Serial Communication Protocols supported in the ATmega328p

USART/UART in ATmega328p
The UART mode in the ATmega328p has the following features:
 Full Duplex Operation (Independent Serial Receive and Transmit Registers)
 Asynchronous or Synchronous Operation

COMSATS University Islamabad (CUI) , Islamabad Campus Page 117


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

 Master or Slave Clocked Synchronous Operation


 High Resolution Baud Rate Generator
 Supports Serial Frames with 5, 6, 7, 8, or 9 data bits and 1 or 2 stop bits
 Odd or Even Parity Generation and Parity Check Supported by Hardware
 Data Over-Run Detection
 Framing Error Detection
 Noise Filtering Includes False Start Bit Detection and Digital Low Pass Filter
 Three Separate Interrupts on TX Complete, TX Data Register Empty and RX Complete
 Multi-processor Communication Mode
 Double Speed Asynchronous Communication Mode
The ATMega328 supports 4 clock modes for USART:
 Normal Asynchronous: Data is transmitted/received asynchronously at the BAUD rate we
set in the UBBR register.
 Double Speed Asynchronous: The data is transferred at double the baud we set in the
UBBR Register by setting the U2X bit in UCSRA register. However, the Receiver will
only use half the number of samples for data sampling and clock recovery
 Synchronous Master: In this mode, the XCKn pin is used to share clock with whatever
slave is being communicated with.
 Synchronous Slave: In slave mode, the external clock input is received on the XCKn pin.
The value of the frequency compared to the system frequency is limited by the following
relationship:

ATmega328 UART Frame Formats


Since the ATmega Series comprises programmable controllers, their UART frame-format is
programmable and hence, flexible. This allows the ATmega to communicate with a variety of
devices serially using UART even if their frame-formats differs between one another. An example
frame can be seen in figure 11.3.
A serial frame is made up of:
 One character (data)
 Synchronization bits (start and stop)
 Parity bits (optional)
ATMega328 offers 30 combinations. The choice may vary between 5, 6, 7, 8 or 9 data bits, 1 or 2
stop bits, none, even or odd parity bits. However, there is always 1 start bit.

Figure 11.3 – UART Frame Example with start (1-low), 9 bits for data, 1 parity bit and stop bits
(2-high)

COMSATS University Islamabad (CUI) , Islamabad Campus Page 118


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

The USART of the AVR occupies three hardware pins:


 RXD: USART Receiver Pin (Pin 26)
 TXD: USART Transmit Pin (Pin 27)
 XCK: USART Clock Pin (Pin 2):
The XCK pin is used for synchronous communication. In the case of “Master mode”, this would
be the clock output and similarly, in the case of “Slave mode” it will be the clock input.
AVR has 6 registers associated with USART:
 UDR0 (USART Data Register)
 UCSR0A, UCSR0B & UCSR0C (Configuration)
 UBRR0H & UBRR0L (Baud Rate Register)
The USCR0 registers are used to enable the ADC, setup the interrupts, setup operation mode and
most importantly, configure the frame rate.
The UBRR0 registers are used to setup the baud rate for communication. Depending on the mode
of operation, the baud-rate to UBRR0 relation would vary, as illustrated in figure 11.4.

Figure 11.4 – Baud rate to UBBR relationship (source: ATmega328p Datasheet)

Please refer to the ATmega328P Datasheet or your lecture material for detailed working
of these registers for UART/USART communication before you proceed. These registers are
referred to and used in the sections that follow.

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.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 119


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

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

// 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

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

COMSATS University Islamabad (CUI) , Islamabad Campus Page 120


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

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();

_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 */

COMSATS University Islamabad (CUI) , Islamabad Campus Page 121


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

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++)

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');

COMSATS University Islamabad (CUI) , Islamabad Campus Page 122


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

Simulation:

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

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.6 HC-05 and HC-06

COMSATS University Islamabad (CUI) , Islamabad Campus Page 123


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

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

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.7 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 124


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
Code:
#include<SoftwareSerial.h>

SoftwareSerial myserial(10,11); //(Rx,Tx)

void setup() {

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

Serial.begin(9600); // the Arduino Baud Rate

delay(500);

myserial.begin(9600);

delay(500);

void loop() {

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

if(myserial.available())

Serial.print((char)myserial.read());

//Similarly complete for Serial.available()

COMSATS University Islamabad (CUI) , Islamabad Campus Page 125


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

Post Lab:
Program your ATmega328 on Proteus so that it is connected to an LCD and 8-switch panel and a
virtual terminal
Whenever the AVR starts, it must send a “YES” to the virtual terminal screen once. After that the
initial status of the switches should be transferred to the virtual terminal once. Thereafter, the
values should be updated on the virtual terminal only if any of the switch is changed.
At the same time, any character typed & entered on the virtual terminal should be displayed on
the connected LCD panel.

Critical Analysis / Conclusion


(By Student about Learning from the Lab)

COMSATS University Islamabad (CUI) , Islamabad Campus Page 126


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

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 127


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:
 Microchip Studio/ AVR Studio
 Proteus ISIS
 AVR DUDESS

Hardware Tools:

Name Value Quantity


Arduino Nano - 1
Breadboard - 1
MCP4821 - 1
Table 12.1: 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.
Some of the features of SPI are as follows:
 A Single Master – Multiple Slave topology
 Four-wire protocol (developed by Motorola)
 Synchronous communication
 Full Duplex
 Flexible number of bits
 4 modes of operation
 High Speed (supports up to 32MHz)
SPI is a “synchronous” data bus, which means that it uses a dedicated line for “clock” (in addition
to data) that keeps all connected devices 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, depending upon the mode of operation.
When the receiver detects that edge, it will immediately look at the data line to read bits on one

COMSATS University Islamabad (CUI) , Islamabad Campus Page 128


Lab# 12: Interfacing Devices using SPI

the SDI line while at the same time passing bits from the SDO on to the MISO (as shown in Figure
12.1.
HOW SPI WORKS:
SPI consists of two shift or more registers. One in the “Master” device and the others in the “Slave”
device. In SPI, only the Master generates the clock signal.

Figure 12.1 – SPI Master connected to an SPI slave device (in a peer-to-peer topology)

An SPI network can only contain one Master but 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”.

Figure 12.2 – Shift registers in the Master and the Slave. Bits move simultaneously from Master to Slave, and
Slave to Master

Slave Select (SS)


Slave select line informs a particular slave to wake up and receive / send data. The slave select
lines are used to access one particular slave in case of multiple slaves in the network, as show in
figure 12.3.
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.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 129


Lab# 12: Interfacing Devices using SPI

SPI Read and Write:


In a conventional SPI network, a microcontroller is the Master. The microcontroller
generates CLK which is the SCLK pin in the ATmega328p, that drives all slave devices.
When the slaves start receiving the clock signal, they all become aware of an on-going
communication. Any device that will have a (typically) LOW on the SS pin will process any
data that it receives is coming from the MOSI pin. Simultaneously, the slave starts
transmitting data to MISO (refer to figure 12.2)

Figure 12.3 – Topologies for Multiple Slaves in SPI

COMSATS University Islamabad (CUI) , Islamabad Campus Page 130


Lab# 12: Interfacing Devices using SPI

SPI Modes of Operation


SPI is generally very flexible in terms of frame size and format (which must be consistent
between the Master and the Slave). However, SPI is available in 4 different modes of clock
operation. The Master needs to use the same mode that the slave understands. The four
modes of SPI operation are illustrated in figure 12.4.

Figure 12.4 – SPI Modes of Operation

Figure 12.5 – SPI Modes of Operation Illustrated

Where CPOL denotes the clock polarity, while CPHA denotes the clock phase. The clock
polarity indicates the leading signal of the clock that would indicate the start of a
communication, while the clock phase dictates the point in the clock cycle when the data
will be sampled from the data line.
SPI in ATmega328p
The ATmega328p controller offers SPI with the following features:
 Full-duplex, Three-wire Synchronous Data Transfer
 Master or Slave Operation
 LSB First or MSB First Data Transfer
 Seven Programmable Bit Rates
 End of Transmission Interrupt Flag
The ATmega328p can be programmed to communicate using SPI by leveraging the
following three registers:
 SPDR0 (Data Register)
 SPDSR0 (Status Register)
 SPCR0 (Control Registers)

COMSATS University Islamabad (CUI) , Islamabad Campus Page 131


Lab# 12: Interfacing Devices using SPI

Figure 12.6 – SPI Control Register (SPCR0) in ATmega328p

The bits in the control register are summarized as follows (refer to figure 12.6):
 SPIE0: To enable SPI interrupt
 SPE0: To enable SPI and all relevant operations
 DORD0 (Data Order): When set, the LSB of the data word is transmitted first. When
clear, the MSB of the data word is transmitted first.
 MSTR0 (Master/Slave Select): This bit selects Master SPI mode when set and Slave
SPI mode when clear.
 CPOL0: for clock polarity
 CPHA0: for clock phase
 SPR01 – SPR00: To control clock rate for MASTER mode only:
Please refer to the ATmega328P Datasheet or your lecture material for detailed working of
these registers for SPI before you proceed. These registers are referred to and used in the
sections that follow.

Introduction to 25AA128:
The Microchip Technology Inc. 25AA128 (25XX128* series) is a 128k-bit Serial
Electrically Erasable PROMs. The memory is accessed via a simple Serial Peripheral
Interface (SPI) compatible serial bus. The bus signals required are a clock input (SCK) plus
separate data in (SI) and data out (SO) lines. Access to the device is controlled through a
Chip Select (CS) input. Some of its features are:
 Max. Clock 10 MHz

COMSATS University Islamabad (CUI) , Islamabad Campus Page 132


Lab# 12: Interfacing Devices using SPI

 Low-power CMOS Technology


o Max. Write Current: 5 mA at 5.5V, 10 MHz
o Read Current: 5 mA at 5.5V, 10 MHz
o Standby Current: 5 µA at 5.5V
 16,384 x 8-bit Organization
 64 Byte Page
 Sequential Read
 High Reliability
o Endurance: 1,000,000 erase/write cycles
o Data retention: > 200 years
o ESD protection: > 4000V

Figure 12.7 – SPI Pins and Instructions

Principals of Operation
The 25AA128 operates at SPI Mode0. The leading edge of the clock is rising, and data is
sampled on the first rising edge of the SCK after slave select.
Read Sequence:
The device is selected by pulling CS low. The 8-bit READ instruction is transmitted to the
25XX128 followed by the 16-bit address, with two MSBs of the address being “don’t care”
bits. After the correct READ instruction and address are sent, the data stored in the memory
at the selected address is shifted out on the SO pin. The data stored in the memory at the next
address can be read sequentially by continuing to provide clock pulses. The internal Address
Pointer is automatically incremented to the next higher address after each byte of data is
shifted out.

COMSATS University Islamabad (CUI) , Islamabad Campus Page 133


Lab# 12: Interfacing Devices using SPI

Write Sequence:
Prior to any attempt to write data to the 25XX128, the write enable latch must be set by
issuing the WREN instruction. This is done by setting CS low and then clocking out the
proper instruction into the 25XX128. After all, eight bits of the instruction are transmitted,
the CS must be brought high to set the write enable latch. If the write operation is initiated
immediately after the WREN instruction without CS being brought high, the data will not be
written to the array because the write enable latch will not have been properly set.
Once the write enable latch is set, the user may proceed by setting the CS low, issuing a
WRITE instruction, followed by the 16-bit address, with two MSBs of the address being
“don’t care” bits, and then the data to be written. Up to 64 bytes of data can be sent to the
device before a write cycle is necessary. The only restriction is that all of the bytes must
reside in the same page.

Figure 12.8 – READ Sequence timing diagram

Figure 12.9 – WREN sequence timing diagram

COMSATS University Islamabad (CUI) , Islamabad Campus Page 134


Lab# 12: Interfacing Devices using SPI

Figure 12.10 – WRITE sequence timing diagram

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.

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.11: Pin diagram of MCP4821

COMSATS University Islamabad (CUI) , Islamabad Campus Page 135


Lab# 12: Interfacing Devices using SPI

(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.12 16 bit data register

 MSB is shifted in first then LSB is shifted

 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.13: Sending data from AVR to MCP 4821 Data register

COMSATS University Islamabad (CUI) , Islamabad Campus Page 136


Lab# 12: Interfacing Devices using SPI

In Lab:

Task 1:
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)

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)

COMSATS University Islamabad (CUI) , Islamabad Campus Page 137


Lab# 12: Interfacing Devices using SPI

//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

//Set SS

PORTB |= (1<<SS);

//_delay_us(50);

void SPI_Init()

// Write code to initialize SPI

COMSATS University Islamabad (CUI) , Islamabad Campus Page 138


Lab# 12: Interfacing Devices using SPI

Simulation:

Figure 12.14: Schematic for In Lab task

Task-2
Please configure the ATmega328 on proteus as connected to 25AAXXX EEPROM as shown
in figure 12.8. Also connect an oscillator and monitor the signals on SCK, MOSI and MISO.
Write a program that stores your complete first name at consecutive elements of main
memory starting from the address equal to 0x(128 + “your_roll_number”)
Your program should then, pick up your name, character, by character from the main
memory, and stores it on to the external EEPROM via SPI.
Document some instances of the oscillator output during write operation.

Figure 12.15 – SPI communication on Proteus

COMSATS University Islamabad (CUI) , Islamabad Campus Page 139


Lab# 12: Interfacing Devices using SPI

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 140


Lab# 12: Interfacing Devices using SPI

COMSATS University Islamabad (CUI) , Islamabad Campus Page 141

You might also like