0% found this document useful (0 votes)
107 views65 pages

Microcontroller Lab

Uploaded by

idatscribd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
107 views65 pages

Microcontroller Lab

Uploaded by

idatscribd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

REVISION-2015 MICRO CONTROLLER LAB - 6139

E
EG
LL
CO
Lab Manual

IC
For
HN
C
TE
LY

MICRO CONTROLLER LAB


PO

(6139)
N
DI
A'

COMPUTER ENGINEERING
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

Contents

E
EG
1 Installing AVR Studio 3

LL
2 Working with AVR Studio 5
3 Setting up your on ATMEGA kit 10

CO
4 Programming ATMEGA 32 23

IC
5 Programming ATMEGA 32 in C
HN
1 LED Interfacing 37
2 Bit operations in C 39
C
3 PORT pin as input 41
4 Relay Interfacing 44
TE

5 7 Segment Display 47
LY

6 LCD interfacing 50
7 Temperature sensor interfacing 56
PO

6 Assembly language programming


N

8 Port programming in assembly 61


DI

9 Code conversion 63
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

Chapter 1
Installing AVR Studio
Let us look onto the software that is required for programming ATMEGA range of
processors. For that matter, any microcontroller requires software called

E
Integrated Development Environment – IDE for writing program. An IDE is the

EG
handy software that acts as text editor, debugger, assembler and compiler all in
one package. A text editor is simply like note pad software for writing the code.

LL
The text editor comes as a package along with the IDE. Here in this book
whatever program we write for microcontroller will be called as source code or

CO
simply code. An assembler interprets a code written in assembly language to
machine code. The compiler converts codes written in C into machine codes. In
our case, the compiler is called cross compiler. A cross compiler converts

IC
instructions into machine code or low-level code for a computer other than that
HN
on which it is run. Here the target computer is the ATMEGA micro controller. A
debugger assists detection and correction of errors in code.
C
Atmel AVRStudio® is the Integrated Development Environment (IDE) for
TE

developing and debugging embedded Atmel AVR applications. The AVR Studio
IDE gives you a seamless and easy-to-use environment to write, build, and debug
LY

your C/C++ and assembler code. AVR studio can be down loaded from
www.atmel.com.
PO

Three popular versions of AVR studio are available for use with ATMEGA
processors. AVR studio 7 is latest addition into the series.
N


DI

AVR Studio ver. 4


 AVR Studio ver. 5
A'

 AVR studio ver. 6


M

All you have to do is to down load the version that is most suitable for your
computer operating system. For example, for windows XP service pack 2 you
need to install AVR Studio 4. IF you encounter with any error while installing the
Studio, try for the other versions. AVR studio for Linux environment can also be
down loaded. If you are installing AVR Studio 4, you have to install Win AVR - the
compiler separately. Win AVR should be installed only after installation of AVR
REVISION-2015 MICRO CONTROLLER LAB - 6139

studio 4. But for all other versions, the compiler comes along with the package.
Go for the latest version if your operating system supports.

Installations of this software are pretty straightforward. You should not face any
trouble in it. During the installation of AVR Studio 5 or 6, it might need to install
some other stuff before the actual installation begins. These installations will be
initiated by itself.

E
EG
LL
CO
IC
C HN
TE
LY
PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

Chapter 2
Working with AVR Studio

E
EG
In this chapter we will start working with AVR studio 5, the other versions are

LL
similar. AVR studio 5 is taken for no special reason. You may refer to internet
resources if you encounter with any problem using other versions.

CO
AVR Studio 5

IC
Let’s have a look at the features of AVR Studio before we proceed.
HN
 It is an Integrated Development Environment (IDE) for AVR Software.
 It allows chip simulation and in-circuit emulation.
C
 It supports the whole AVR family of Microcontrollers (MCUs).
TE

 It has easy to use User Interface (UI) and gives complete overview.
 It uses same UI for simulation and emulation.
LY
PO
N
DI

Creating your first AVR Project


A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

Here is a step-by-step guide regarding how to create your first AVR Project using

E
EG
LL
CO
IC
HN
AVR Studio 5.
C
TE

 After installation, open AVR Studio 5 from Start → All Programs → Atmel
LY

AVR Tools → AVR Studio 5.0


PO

 After opening, you will see a Start Page like this. Click on “New Project…“

 Then, you will see the following dialog box. Choose AVR GCC from the
N

‘Installed Templates’ pane, and then choose Empty Executable Project.


DI

Now, you can give any name to it, say MyFirstProject and choose an
appropriate location in your hard drive. Check Create directory for
A'

solution. Click on OK.


M
REVISION-2015 MICRO CONTROLLER LAB - 6139

E
EG
LL
CO
IC
C HN
TE

 Now, you will see the Device Selection dialog box. As you can see, AVR
Studio supports all the AVR MCUs! The list is huge! Choose your device
LY

from this list. We choose ATmega32. Click OK.


PO




N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

E
EG
LL
CO
IC
C HN
TE

 Now, you will see the following screen. Note that the basic program
structure is already prepared for you. You simply need to initialize your
LY

variables and place your code inside the while(1) loop.


PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

Now you have successfully created your first AVR Project! Now to further
proceed with it, we need to write a code, which is discussed in the subsequent
chapters.

E
EG
Special Note
AVR Studio 5 installations were discussed. The

LL
procedure is almost the same for Studio 4 and Studio

CO
6. The whole installation process is interactive and you
will be guided through out. Studio 6 installation may
take some time. Be patient enough to enjoy the

IC
power of Studio 6
HN
Chapter 3
C

Setting up your on ATMEGA kit


TE

You may already have ATMEGA kits of some make available in your laboratory.
LY

You can refer to the operation manual for using such kits. For those who do not
own one or who are enthusiastic in becoming a microcontroller wiz, this chapter
PO

is exclusively for you. Others may skip this chapter. Let us call our ATMEGA 32 kit
as target board. Sometimes they are sometimes called as development board
too. We will provide you with PCB layout for making your own board.
N
DI

POWERSUPPLY
A'

We will start with the power supply. Our target board had two options; either it
can be powered from USB programming port or from external power supply
M

which can be a standard 12V SMPS adaptor.


REVISION-2015 MICRO CONTROLLER LAB - 6139

E
EG
LL
CO
The external power supply is connected through terminal block/ barrel connector
(MX27) B1. Diode D2 provide protection against any polarity interchange. The

IC
selections among USB and adaptor are made through a DPDT switch SW1. C15 is
filter capacitor which provide additional filtering. The 12V supply is tapped
directly for the relay and buzzer circuit that will be discussed later. 12V is tapped
HN
before the diode to avoid 0.7V drop that can happen due to diode D2. 5V
regulation is provided with U7 – 7805.
C
TE
LY
PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

THE MICROCONTROLLER

E
EG
LL
CO
IC
C HN
TE
LY

ATMEGA 32 is the microcontroller in our target board. Here we had connected


PO

external crystal oscillator at 12 MHz. You should remember that with default fuse
bit setting, ATMEGA works with internal RC oscillator at 1 MHZ. This is the reason
why you will found crystal missing in subsequent diagrams. For any change
N

required for clock type and frequency, fuse bits need to be set accordingly. There
DI

are three modes for clock oscillator; the first is internal RC oscillator which is by
default, external crystal oscillator or external RC oscillator. You have to be very
A'

care full in setting clock oscillator type. If you set the processor for external RC
oscillator, the target board will cease to work there after as there is no external
M

RC connected in the target board. In that case, you have to remove crystal
manually connect XTL1 to Vcc through pull-up resistor and have to reprogram the
fuse. You will once again found yourselves in trouble in while using PORTC. By
default PORTC is set for JTAG interface. You have to disable JTAG function before
using PORTC. Remember, once fuse bits are burned, the settings are permanent
REVISION-2015 MICRO CONTROLLER LAB - 6139

until you reprogram them. So fuse bits do not need to be programmed every
time.

Bit No. 7 6 5 4 3 2 1 0

Low
BODLEVEL BODEN SUT1 SUT0 CKSEL3 CKSEL2 CKSEL1 CKSEL0
Fuse

E
EG
Default
1 1 1 0 0 0 0 1
Value

LL
Now we will see how to configure lower and higher fuse. For Beginners Fuse bits

CO
will seems to be very confusing but they are not so! Fuse bits are master registers
whose values directly affects functioning of microcontroller. ATmega32
microcontroller has two fuse bytes namely high fuse and low fuse. Both of them

IC
are 8 bits. The default value of ATmega32 fuse bit is 0x99E1 i.e. high fuse =0x99
and low fuse =0xE1
HN
.
Bit No. 7 6 5 4 3 2 1 0
C
TE

EESAV BOOTSZ
High OCDEN JTAGEN SPIEN CKOPT BOOTSZ BOOTRS
Fuse E 1 0 T
LY

Default
1 0 0 1 1 0 0 1
PO

Value
N

OCDEN : This pin is used to enable or disable on chip debugging. On chip


DI

debugging provides a real time emulation of microcontroller when running in


target system. By default it is disabled as 1 means not programmed.
A'

JTAGEN : There is a built in JTAG interfaces for debugging. It is enabled in new


M

microcontroller. This is the reason why some newbies say “PORTC of ATmega32
not working!!” Disable it if you are not using JTAG by making JTAGEN bit 1(high).

SPIEN : 0 value (programmed) means Serial programming of ATmega32 is


enabled. Don’t change this unless you have a parallel programmer! Because once
disabled ATmega32 can’t be programmed using serial programmer.

EESAVE : If programmed (0) it will save EEPROM from erasing during chip erase
else EEPROM would also be erased with flash.
REVISION-2015 MICRO CONTROLLER LAB - 6139

BOOTSZ0 and BOOTSZ1 : These are used to set the boot loader size.

CKSEL [3-0] : These bits are used to select different clock options available.

E
EG
CKSEL
Device clocking options
3..0

LL
External crystal/ceramic 1111-

CO
resonator 1010

External low frequency


1001

IC
crystal HN
1000-
External RC oscillator
0101
C
Calibrated Internal RC 0100-
TE

oscillator 0001
LY

External clock 0000


PO

The default value of CKSEL3..0 is 0001 i.e. internal RC oscillator running at 1 MHz.
If you want to add external crystal you need to change these values according to
the table above. Some common fuse bits values are given in the end of the
N

article.
DI

CKOPT : The CKOPT Fuse Selects between two different oscillator amplifier
A'

modes. When CKOPT is programmed, the oscillator output will oscillate with a
full rail-to-rail swing on the output. When not programmed, the oscillator has a
M

smaller output swing. If you are using external crystal oscillator it is better to
program CKOPT i.e. CKOPT=0.

BODEN : ATmega32 has an On-chip Brown-out Detection (BOD) circuit for


monitoring the VCC level during operation by comparing it to a fixed trigger level.
When the BOD is enabled (BODEN programmed), and VCC decreases to a value
below the trigger level, the Brown-out Reset is immediately activated. When VCC
increases above the trigger level, it starts the microcontroller again.
REVISION-2015 MICRO CONTROLLER LAB - 6139

BODLEVEL : The trigger level for the BOD can be selected by this fuse bit. When
programmed (0) the trigger level is 4V and when not programmed (1) the trigger
level is 2.7V.

BOOTRST : If BOOTRST bit is programmed (0), the device will jump on first
address boot-loader block.

Some fuse bits values are

E
EG
Low High
Comments

LL
Fuse Fuse

CO
0xE1 0x99 Default, Internal 1MHz

0xE2 0x99 Internal 2MHz, rest all default

0xE3 0x99
IC
Internal 4MHz, rest all default
HN
0xE4 0x99 Internal 8MHz, rest all default
C
External 12/16MHz, JTAG
0xEE 0xC9
TE

disabled
LY

0xE1 0xD9 Internal 1MHz, JTAG disabled


PO

0xE2 0xD9 Internal 2MHz, JTAG disabled

0xE3 0xD9 Internal 4MHz, JTAG disabled


N

0xE4 0xD9 Internal 8MHz, JTAG disabled


DI
A'

NOTE: In fuse bits 0 means programmed and 1 means not programmed.


M
REVISION-2015 MICRO CONTROLLER LAB - 6139

Bit confused about!

Don’t worry; use D9 for use High fuse and


E4 for low fuse. This will set your

E
microcontroller at internal RC oscillator

EG
8MHz and enabling PORTC.

LL
CO
J10, J11, J12 and J13 are RMC connectors for taking port pins out. The 10 pin
RMC connector is provided with additional VCC and Ground pins for interfacing

IC
any additional boards. We will be discussing about other interfaces as and when
required. If are very curious about refer to schematic given below. Details about
HN
schematics will be discussed in the subsequent chapters.
C
TE
LY
PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

E
EG
LL
CO
IC
CHN
TE
LY
PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

E
EG
LL
CO
IC
CHN
TE
LY
PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

E
EG
LL
CO
IC
CHN
TE
LY
PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

E
EG
LL
CO
IC
CHN
TE
LY
PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

E
EG
LL
CO
IC
CHN
TE
LY
PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

E
EG
LL
CO
IC
CHN
TE
LY
PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

E
EG
LL
CO
IC
CHN
TE
LY
PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

Chapter 4
Programming ATMEGA 32
We had covered the installation and usage of AVR Studio. We will now go for

E
porting the written code into ATMEGA 32. Porting is transferring the machine

EG
code into the code memory of ATMEGA32. Machine codes are now a day’s called
firmware. Transferring the code on to the microcontroller gives a you a visual

LL
clue on to how your code works on real world.

CO
USBasp - USB programmer for Atmel AVR controllers

IC
USBasp is a USB in-circuit programmer for Atmel AVR controllers. It simply
consists of an ATMega88 or an ATMega8 and a couple of passive components.
HN
The programmer uses a firmware-only USB driver, no special USB controller is
needed.
C

Features
TE

 Works under multiple platforms. Linux, Mac OS X and Windows are


LY

tested.
 No special controllers or SMD components are needed.
PO

 Programming speed is up to 5kBytes/sec.


 SCK option to support targets with low clock speed (< 1,5MHz).
 Planned: serial interface to target (e.g. for debugging).
N
DI

Let us see how to install the USB driver for the built in programmer.
A'

Installing driver On Windows XP:


M

Before installing drivers copy the driver folder in the computer

Step 1:

Connect USB Programmer to USB port of your computer. You will see the new
hardware found dialog box.

Here select ‘Install from a list or specific location’ and Click ‘Next’.
REVISION-2015 MICRO CONTROLLER LAB - 6139

E
EG
LL
CO
IC
C HN
TE
LY

Step 2:
PO

Here Select ‘Search for the best driver in these locations’ and brows to the location
where you have copied the driver folder (copy location >\bin\win-driver.) and click ‘OK’.
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

Step 3:

After selecting the location click ‘Next’

E
EG
LL
CO
IC
C HN
TE

Step 4:
LY

Now windows will start installing the given driver.


PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

E
EG
LL
CO
IC
C HN
Step 5: Now click ‘Finish’ to co mplete the installation
TE
LY
PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

Step 6:

Now the programmer is ready to use.

E
EG
LL
CO
After installation user can check the driver in device manager, to do so go

to Mycomputer>Properties>Device manager

IC
C HN
TE
LY
PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

Installing driver On Windows7:


Before installing drivers copy the driver folder in the computer

Step 1:

Connect USB Programmer to USB port of your

E
computer. Now go to Computers device manager

EG
LL
My computer>properties>Device manager

Following window will popup, here in other device you will find

CO
USBasp

IC
C HN
TE
LY
PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

Step 2: Right click on USBasp tab and click on Update Driver Software

E
EG
LL
CO
IC
C HN
Step 3:
TE

Click on Browse my computer for driver software.


LY
PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

Step 3:
Now select the location where you have copied the driver and click ‘Next’.

E
EG
LL
CO
IC
C HN
TE
LY
PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

Step 4:
When following window appears click on ‘Install this driver software any way’

E
EG
LL
CO
IC
C HN
TE
LY

Step 5: Wait until the driver gets installed.


PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

Step 5:
Now the driver is successfully installed and programmer is ready to use

E
EG
LL
CO
IC
C HN
TE
LY
PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

MICRO CONTROLLERS LABORATORY MANUAL

You can use any of the following software for code burning.

• AVRDUDE
• BASCOM-AVR
• eXtreme Burner – AVR.

Any way eXtreme Burner – AVR software is provided in the CD. Other software can be
freely down loaded from the internet.

E
3. Installing eXtreme Burner - AVR

EG
The installation procedure is very simple. Double click the set up icon in Extreme Burner folder
in the CD provided. The installation will complete in few seconds.

LL
Working with eXtreme Burner

CO
To open eXtreme Burner – AVR, double click the icon. You will find an interface similar to the
following opening up.

IC
C HN
TE
LY
PO
N

Now select the processor you want to burn, from the chip menu.
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

Open the hex file from the file open menu. The hex file for the program to be burned will normally
reside in the bin file of the AVR studio project. This will be created on compiling or assembling the
project. Select erase or write operation from the menu. You can also read from the chip with read
menu.
If you need any further details, please go through the extreme burner tutorial in PDF format provided in
the extreme burner directory.

E
4. Installing eXtreme Burner – on Windows 8 or above

EG
USBasp will not working with windows 10 and windows 8 as there is driver restriction for non-
digitally signed drivers to be installed in windows, only digitally signed drivers are allowed in Windows 8

LL
and Windows 10.This is how to install Usbasp Programmer and driver on Windows 10 and Windows 8
and also 8.1.after this, you will be able to use AVR burner USBasp.

CO
 Disable driver signature checking in Windows 8 and Windows 10 by holding Shift key and restart
your computer by clicking on restart button.

IC
C HN
TE
LY
PO
N
DI

 Now you have to click on the option to select Troubleshoot.


A'
M


REVISION-2015 MICRO CONTROLLER LAB - 6139



 Click troubleshoot button you will see a new screen.

E
EG
LL
CO
 Click advanced options button on this screen you will get a new screen that will tell you that your
computer will now restart after restart you will get a bunch of option for yourwindows.

IC
C HN
TE
LY
PO
N

 When you see the following screen after your computer restarts, you have to select 7th option(
DI

i.e. the real option that will disable windows driver signature detection on your computer ) so
now click 7 from your keyboard buttons. After disabling your PC will start windows normally but
now with disabled driver signature detection.
A'


M

Now go to Device manager again after restart click on usbasp icon in the devices list and tryto
install USBasp driver using browse for drivers option
REVISION-2015 MICRO CONTROLLER LAB - 6139

E
EG
LL
CO
IC
HN
Chapter 5
C

Interfacing and
TE

Programming ATMEGA 32 in C
LY
PO
N
DI
A'
M
REVISION-2015 MICRO CONTROLLER LAB - 6139

Experiment 1
LED Interfacing
Aim : To send one byte of data on to PORTB of ATMEGA 32 there by understanding the
operation of PORT as output.

E
Objective

EG
After completion of this experiment the student should be able to
understand the operation of ATMEGA PORT as output. The
operations of PORT are visualized by interfacing LEDs to PORT pins. In

LL
addition, this experiment will provide preliminary experience on
programming microcontrollers on Embedded C.

CO
Theory

IC
HN
ATMEGA ports are 8 bit wide. Each port has 3 eight bit registers associated. Each bit in these
registers configures pins of associated port. Bit 0 of these registers is associated with Pin 0 of the
port, Bit1 of these registers is associated with Pin1 and so on.
C
TE

These three registers are


LY

– DDRx register
– PORTx register
PO

– PINx register

X may be replaced by A,B,C or D based on the PORT you are using.


N

DDRx register
DI

DDRx (Data Direction Register) configures data direction of the port pins. Which, writing 0 to a
A'

bit in DDRx makes corresponding port pin as input, while writing 1 to a bit in DDRx makes the
M

corresponding port pin as output.

example:

 to make all pins of port B as input,


DDRA = 0b00000000;
 to make all pins of port A as output pins :
DDRB= 0b11111111;
REVISION-2015 MICRO CONTROLLER LAB - 6139

 to make lower nibble of port B as output and higher nibble as input :


DDRB = 0b00001111; In hexadecimal representation, it can be written as DDRB = 0x0F;

E
EG
LL
CO
IC
C HN
TE
LY

Code:
PO

/*--------------------------------------------------------------------
This program demonstrates the working of port
Author : State Institute of Technical Teachers Training and Research
N

Date : 12.01.2016
DI

Program set LED connected to PORTB alternately on


PB7 -1 PB6-0 PB5-1 PB4-0 PB3 -1 PB4-0 PB1-1 PB0-0
A'

---------------------------------------------------------------------*/
M

#include <avr/io.h> // standard AVR header

int main(void)
{
DDRB = 0xff; // setting PORTB as output
PORTB = 0B01010101; // setting value for PORTB

while (1); // indefinite loop


}

//-------------------------------------------------------------------
REVISION-2015 MICRO CONTROLLER LAB - 6139

Experiment 2
Bit operations in C
Aim : To blink LED connected to PB1 AT 1sec interval while keeping LED on PB7 on using
AND, OR operations and with generalized approach.

E
Objective

EG
After completion of this experiment the student should be able to
understand generalized concept of programming and to use logic

LL
operations for bit manipulation.

CO
Theory

IC
Previous concept of PORT setting by moving values to the entire port cannot be used in
HN
practical cases as moving can change values of pins which are nor desired to be affected Hence
usually AND and OR logic operations are used to manipulate bits.
C
In order to set PB7 in this case
TE

PORTB |= 0B10000000; // setting PB7


LY

In order to clear PB1

PORTB &= 0B11111101; // clear PB1


PO

This can be rewritten as


N

In order to set PB7 in this case


DI

PORTB |= (PORTB <<7); // setting PB7


A'

Or as
M

PORTB |= (PORTB <<PB7); // setting PB7

PORTB &= ~(PORTB <<1); // clear PB1

Or as
PORTB &= ~(PORTB <<PB1); // clear PB1
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

Code:
/*--------------------------------------------------------------------
This program demonstrates the working of port
Author : Aiju Thomas
Date : 12.01.2016

E
Program Blink LED connected to PB1 at 1sec interval while keeping PB7 always high using
AND, OR operations

EG
---------------------------------------------------------------------*/

#include <avr/io.h> // standard AVR header

LL
#include <util/delay.h>

CO
int main(void)
{
DDRB = 0xff; // setting PORTB as output
PORTB |= (PORTB<<PB7); // setting value for PORTB

IC
while (1) // indefinite loop
HN
{
PORTB |= (PORTB<<PB1); // setting value for PORTB
_delay_ms(1000);
C
PORTB &= ~(PORTB<<PB1); // setting value for PORTB
_delay_ms(1000);
TE

}
}
LY

//-------------------------------------------------------------------
PO
N
DI
A'
M
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

Experiment 3
PORT pin as input
Aim : To read switches connected to PORTD and output the contents to LEDs connected to
PORTB.

E
Objective

EG
After completion of this experiment the student will be able to

LL
understand the operation of ATMEGA port as input. The concepts of
functions are introduced in this experiment.

CO
Theory:

IC
HN
PINx register

PINx (Port IN) register is used to read data from port pins. In order to read the data from port
C
pin, first you have to change port’s data direction to input. This is done by setting bits in DDRx
to zero. If port is made output, then reading PINx register will give you data that has been
TE

output on port pins. There are two input modes. Either you can use port pins as tri stated
inputs or you can activate internal pull up. In order to enable internal pull up, you have to write
LY

1 to the corresponding PORTx register.


PO
N
DI

By default fuse bit setting, PORTC is set for JTAG programming. In order to
use PORTC as input or output, you have to set bit 6 of high fuse. This need
A'

not be done every time you use PORTC. Once fuse bits are set, the values
remain as such until you rewrite the settings. So remember if you do not get
M

the expected output while using PORTC, check for fuse bits.
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

E
EG
LL
CO
IC
C HN
TE

Code:
LY

/*----------------------------------------------------------------
This program demonstrates the working of ports as input and output
Author: State Institute of Technical Teachers Training and Research
PO

Date: 12.01.2016

Program reads switches connected to PORTD


and output the values to PORTB
N

----------------------------------------------------------------*/
DI

#include <avr/io.h> // standard AVR header

// lets us introduce the concept of functions here


A'

void InitPort(void)
M

DDRB = 0xFF; // PORTB pins are defined as output


PORTD = 0xFF; // internal pull ups are enabled
DDRD = 0x00; // PORTD pins are defined as input

}
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

int main(void)

{
InitPort (); // calling port initialization function
while (1) // indefinite loop
{
PORTB = PIND; // reading PORTD and writing the value to
// PORTB
}

E
EG
}

//------------------------------------------------------------

LL
Alternatively you can write the program as

CO
/*----------------------------------------------------------------
this program demonstrates the working of ports as input and output

IC
Author: State Institute of Technical Teachers Training abd Research
Date: 12.01.2016
HN
Program reads switches connected to PORTD
and output the values to PORTB
----------------------------------------------------------------*/
C
#include <avr/io.h> // standard AVR header
TE

// lets us introduce the concept of functions here

char x = 0; // variable x declared as char (8bit)


LY

void InitPort(void)
{
PO

DDRB = 0xFF; // PORTB pins are defined as output


PORTD = 0xFF; // internal pull ups are enabled
DDRD = 0x00; // PORTD pins are defined as input
N
DI

}
A'

int main(void)
{
M

InitPort (); // calling port initialization function


while (1) // indefinite loop
{
x = PIND; // reading PORTD
// x = ~x // uncomment and see what happens
PORTB = x; // writing the value to PORTB
// PORTB
}

//------------------------------------------------------------
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

Experiment 4
Relay Interface
Aim : To switch relay connected to PORTC ON/OFF at 1 second interval.

E
EG
Objective

LL
After completion of this experiment the student will be able to
understand the usage of software delay for required interval.

CO
The student will be able to interface relay for controlling high voltage
or high current application especially for driving 230V ac applications.

IC
HN
Theory:
C

In most the microcontroller applications, you may need to control external load. This can be
TE

done using relays. Relays are electromagnetic switches that are available for various voltages
LY

and current ratings. The selection of relays is done based on the current requirement. Usually
relays are available at 5, 12, 24 V DC coil voltage. Micro controller port pins can deliver 5V at a
PO

very low current rating of 10mA. This power is sufficient only to drive an LED. For driving relays
you need to have driver circuit. Drivers are usually transistors in common emitter configuration.
N

A typical 230V, 6A relay can be driven using


DI

the given circuit. For higher current, you


have to decrease base resistance. You
A'

should remember that any transistor can be


driven safely at the rated collector current.
M

For higher current requirement you can


choose power transistors as demanded by
the case. Diode D acts as free wheel diode.

If you have more devices to control, it is advisable to go for open collector transistor array ULN
2004 or ULN 2003. They can be employed for 12V and 5V applications respectively. In our
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

target board we had provided you with an additional 12V buzzer which is connected to PC5 and
relay to PC4 respectively. ULN 2004/3 is provided with inbuilt free wheel diode.

E
EG
LL
CO
IC
C HN
TE

Code
LY

/*---------------------------------------------------------------------
This program will switch relay and buzzer connected to PORTC 4 and 5
respectively at 1 second interval
PO

The program assumes internal RC oscillator at 1Mhz


Author : Aiju Thomas
Date : 12.01.2016
N

---------------------------------------------------------------------*/
DI

#define F_CPU 8000000UL // clock at 8MHz


A'

#include <avr/io.h> // standard AVR header


#include <util/delay.h> // delay loop function
M

void InitPort(void)
{

DDRC = 0xFF; // PORTC pins are defined as output

int main(void)
{
InitPort (); // calling port initialization function

while (1) // indefinite loop


REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

{
_delay_ms(3000); // calling delay function for 1 sec delay
// in this case value 1000 in msec is passed
// to the built in function
PORTC = ~ PORTC; // inverting portC

}
}

E
//-----------------------------------------------------------------------

EG
LL
CO
IC
C HN
TE
LY
PO
N
DI
A'
M
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

Experiment 5
7 Segment Display

Aim : To display ‘0123’ on multiplexed seven segment cathode display with segments

E
EG
connected to PB0 to PBG and digits connected to PD4, PD5,PD6 and PB7 respectively.

LL
Objective

CO
After completion of this experiment the student will be able to
program multiplexed 7 segment display.

IC
He/She will be able to interface 7 segment LED displays to
microcontrollers.
C HN
TE

Theory:
LY

Seven segment displays are available in common anode and common cathode configuration.
They are usually used in multiplexed configuration. Multiplexing LED displays can make them
PO

more efficient by using fewer components, simplifying the printed circuit board, and consuming
less power. One segment from each of the digits is connected to a common line which is
controlled by a single output pin from the microcontroller. This is done for each segment on a
N

digit, so only seven output drive pins are needed for a multi-digit seven-segment display panel
DI

to control all the segments.


A'

One digit is activated at a time using this method, as each digit is enabled one at a time in
sequence by a separate signal which connects to the common cathode (or common anode) pin
M

on a digit. There would be a separate control line from the microcontroller output port for each
digit on the display panel. The segment data lines are updated for each digit as it is selected by
its separate digit select control line. This makes sure that each digit on the panel displays the
intended information, which could be a number.

The brightness of a panel is lower on a multiplexed panel because of this on-off duty cycle, but
the light intensity can be increased to an acceptable level by a small increase in LED current.
LED update frequency can be made high enough so that there wouldn't be any noticeable
flickering.
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

In our prototyping board, the displays are connected to pins as described in the aim. You may
change the pins as required to match your target board specification.

E
EG
LL
CO
IC
C HN
Code:
TE

/*---------------------------------------------------------------
LY

This program display 0123 on 7 segment LED display at internal RC


oscillator at 8Mhz
author: SITTTR Date: 09.01.2016
PO

| | A | | | | | |
N

E | | | | | | | |
DI

D | | B | | | | | |
A'

| | | | | | | |

C
M

DIGIT4 DIGIT3 DIGIT2 DIGIT1

Digit select PD4 PD5 PD6 PB7 segment to PB0 TO PB6


Segments F - PB6 A - PB5 B - PB4 C - PB3 D - PB2 E - PB1 G - PB0
Digit 4 - PD4 Digit 3 - PD5 Digit 2 - PD6 Digit 1 - PB7
-----------------------------------------------------------------*/

#define F_CPU 8000000UL // clock @ 8MHz

#include <avr/io.h> // standard AVR header


#include <util/delay.h> // delay loop function
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

int main(void)
{
DDRB = 0xff; // setting PORTB as output
DDRD= 0xff; // setting PORTD as output
PORTD = 0xff; // all set to deselect digit

while (1) // indefinite loop


{

E
EG
PORTB = 0x00; // clearing all segments
PORTD = PORTD | 0xf0; // disabling all digits
PORTD = PORTD & 0xE0; // selecting digit connected to PD4

LL
PORTB = 0xFE; // display digit as 0

_delay_ms(1); // 1 msec delay

CO
PORTB = 0x00; // clearing all segments
PORTD = PORTD | 0xF0; // disabling all digits
PORTD = PORTD & 0xD0; // selecting digit connected to PD5

IC
PORTB = 0xB0; // display digit as 1
HN
_delay_ms(1);

PORTB = 0x00; // clearing all segments


C
PORTD = PORTD | 0xF0; // disabling all digits
PORTD = PORTD & 0xB0; // selecting digit connected to PD6
TE

PORTB = 0xED; // display digit as 2


_delay_ms(1);
LY

PORTB = 0xFF; // clearing all segments


PO

PORTD = PORTD | 0xF0; // dissabling all digits


PORTB = 0x79; // display digit as 3

_delay_ms(1);
N

PORTB = PORTB | 0xFF; // disabling all digit to PB7


}
DI

//-----------------------------------------------------------
A'
M
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

Experiment 6
LCD interfacing

E
Aim : To interface 16x2 alphanumeric LCD display in 8 bit mode to display “IF YOU CAN READ

EG
THIS, PROGRAM OK”. Use PORTB for D0 to D7 , RS – PD4, RW – PD5 and EN – PD6.

LL
CO
Objective
After completion of this experiment the student will be able to
interface LCD displays to micro controller.

IC
He/She will be able to display any required string.
C HN
TE
LY

Theory
PO

LCD display is an inevitable part in almost all embedded projects. We will look about interfacing
16×2 LCD with ATMEGA. In order to understand the interfacing first you have to know about
the module. It consists of 16 rows and 2 columns of 5×7 or 5×8 LCD dot matrices. They are
N

available in a 16 pin package with back light, contrast adjustment function and each dot matrix
DI

has 5×8 dot resolution. The pin numbers, their name and corresponding functions are shown in
the table below.
A'
M

Pin No: Name Function


1 VSS This pin must be connected to the ground
2 VCC Positive supply voltage pin (5V DC)
3 VEE Contrast adjustment
4 RS Register selection
5 R/W Read or write
6 E Enable
7 DB0 Data
8 DB1 Data
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

9 DB2 Data
10 DB3 Data
11 DB4 Data
12 DB5 Data
13 DB6 Data
14 DB7 Data

E
15 LED+ Back light LED+

EG
16 LED- Back light LED-

LL
VEE pin is meant for adjusting the contrast of the LCD display and the contrast can be adjusted
by varying the voltage at this pin. This is done by connecting one end of a POT to the Vcc (5V),

CO
other end to the Ground and connecting the center terminal (wiper) of the POT to the VEE pin.
You can refer circuit diagram for details.

IC
The display has got two built in registers namely data register and command register. Data
register is for placing the data to be displayed, and the command register is to place the
HN
commands. The module has a set of commands each meant for doing a particular job with the
display. We will discuss in detail about the commands later. High logic at the RS pin will select
the data register and Low logic at the RS pin will select the command register. If we make the
C
RS pin high and the put a data in the 8 bit data line (DB0 to DB7), the LCD module
TE

will recognize it as a data to be displayed. If we make RS pin low and put a data on the data
line, the module will recognize it as a command.
LY

R/W pin is meant for selecting between read and write modes. High level at this pin enables
read mode and low level at this pin enables write mode. E pin is for enabling the module. A high
PO

to low transition at this pin will enable the module. DB0 to DB7 are the data pins. The data to
be displayed and the commands are placed on these pins. LED+ is the anode of the back light
LED and this pin must be connected to Vcc through a suitable series current limiting resistor.
N

LED- is the cathode of the back light LED and this pin must be connected to ground.
DI

LCD COMMANDS
A'

Command Function
M

0F LCD ON, Cursor ON, Cursor blinking ON


01 Clear screen
02 Return home
04 Decrement cursor
06 Increment cursor
0E Display ON ,Cursor blinking OFF
80 Force cursor to the beginning of 1st line
C0 Force cursor to the beginning of 2nd line
38 Use 2 lines and 5×7 matrix
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

83 Cursor line 1 position 3


3C Activate second line
08 Display OFF, Cursor OFF
C1 Jump to second line, position1
OC Display ON, Cursor OFF
C1 Jump to second line, position1

E
C2 Jump to second line, position2

EG
LCD INITIALIZATION.

LL
The steps that have to be done for initializing the LCD display is given below and these steps are
common for almost all applications.

CO
 Send 38H to the 8 bit data line for initialization
 Send 0FH for making LCD ON, cursor ON and cursor blinking ON.

IC
 Send 06H for incrementing cursor position.
 Send 01H for clearing the display and return the cursor.
C HN
TE
LY
PO
N
DI
A'

SENDING DATA TO THE LCD.


M

The steps for sending data to the LCD module are given below. I have already said that the LCD
module has pins namely RS, R/W and E. It is the logic state of these pins that make the module
to determine whether a given data input is a command or data to be displayed.

 Make R/W low.


 Make RS=0 if data byte is a command and make RS=1 if the data byte is a data to be
displayed.
 Place data byte on the data register.
 Pulse E from high to low.
 Repeat above steps for sending another data.
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

E
EG
LL
CO
IC
C HN
TE
LY
PO

Code
/*---------------------------------------------------------
N

This program displays string given. It uses RS - PD4


RW - PD5 AND EN - PD6
DI

Data bus is PORTB


----------------------------------------------------------*/
A'

#define F_CPU 8000000L // 8 mHZ


M

#include <avr/io.h>
#include <util/delay.h>

//-----------LCD Functions declaration ---------------


void LCD_init(void);
void LCD_WriteCommand (unsigned char Command);
void LCD_WriteData (unsigned char Data);
void LCD_DisplayString (char row, char column, char *string);
void LCD_Cursor(char row, char column);
//----------------------------------------------------
// change here to match your target board
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

#define ENABLE_LCD PORTD |= 0x40


#define DISABLE_LCD PORTD &= ~0x40
#define SET_LCD_DATA PORTD |= 0x10
#define SET_LCD_CMD PORTD &= ~0x10
//------------------------------------------------------
void port_init(void)
{

DDRD = 0XFF;

E
DDRB = 0xFF; //display port as output

EG
}

// this routine will initialize port and display

LL
void init_devices(void)
{
port_init();

CO
LCD_init();

IC
//--------------- MAIN FUNCTION ----------------------
HN
int main(void)
{
// change to to strig of your choice
init_devices();
C
LCD_DisplayString (1,1,"IF YOU CAN READ ");
LCD_DisplayString (2,1,"THIS, PROGRAM OK");
TE

while (1);
LY

return 0;
}//end of main()
PO

//-------------------------------------------------------------
//----------------- LCD Functions -----------------------------
//-------------------------------------------------------------
N

// ------------- Initialize the LCD driver -------------------


DI

void LCD_init(void)
{
_delay_ms(100); // wait for 100ms
A'

LCD_WriteCommand (0x38); // 8 data lines


LCD_WriteCommand (0x38); // 8 data lines
M

LCD_WriteCommand (0x08); // display off


LCD_WriteCommand (0x01); // clear LCD memory

_delay_ms (250); // 10ms delay after clearing LCD


LCD_WriteCommand (0x06); // cursor setting
LCD_WriteCommand (0x0f); // display ON
}

// -------------------------------------------------------------
// --------- Write a command instruction to the LCD ------------
// -------------------------------------------------------------
void LCD_WriteCommand (unsigned char Command)
{
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

SET_LCD_CMD; // Set LCD in command mode

PORTB = Command; // Load data to port

ENABLE_LCD; // Write data to LCD

asm("nop"); // assembler instuction for NOP


asm("nop"); // gives 1 machine cycle delay

E
DISABLE_LCD; // Disable LCD

EG
_delay_ms(10); // wait for 10ms
}

LL
// -----------------------------------------------------------
// ------------- Write one byte of data to the LCD -----------

CO
// -----------------------------------------------------------
void LCD_WriteData (unsigned char Data)
{
SET_LCD_DATA; // Set LCD in data mode

IC
PORTB = Data; // Load data to port
ENABLE_LCD; // Write data to LCD
HN
asm("nop");
asm("nop");
C
DISABLE_LCD; // Disable LCD
_delay_ms(10); // wait for 10ms
TE

}
LY

// -------------------------------------------------------
// --- Display a string at the specified row and column
PO

// -------------------------------------------------------
void LCD_DisplayString (char row, char column, char *string)
{
LCD_Cursor (row, column);
N

while (*string)
LCD_WriteData(*string++);
DI

}
A'

// ------------------------------------------------------
// --- Position the LCD cursor at "row", "column".-------
//-------------------------------------------------------
M

void LCD_Cursor (char row, char column)


{
switch (row)
{
case 1: LCD_WriteCommand (0x80 + column - 1); break;
case 2: LCD_WriteCommand (0xc0 + column - 1); break;
default: break;
}
}

//-------------------------------------------------------
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

Experiment 7
Temperature sensor interfacing

E
Aim : To read temperature sensor LM35 connected to AD0 pin of ATMEGA32 and display the

EG
values on LCD display.

LL
Objective

CO
After completion of this experiment the student will be able to
interface analog sensors to ATMEGA32.

IC
C HN
TE

Theory
LY

LM35 series is a low cost and precision Integrated Circuit Temperature Sensor whose output
voltage is proportional to Centigrade temperature scale. Thus LM35 has an advantage over
PO

other temperature sensors calibrated in Kelvin as the users don’t require subtraction of large
constant voltage to obtain the required Centigrade temperature. It doesn’t require any external
calibration. Manufactured by National Semiconductor, it can operate over a -55 °C to 150 °C
N

temperature range. Its output is linearly proportional to Centigrade Temperature Scale and it
DI

output changes by 10 mV per °C.


A'

In this experiment, we will learn How to interface


a LM35 temperature sensor with AVR ATmega32
M

microcontroller and LCD display. Here, we will


measure the temperature of the surrounding or
any other material to which the LM35
temperature sensor is connected for its
temperature measurement and we will display the
temperature value in degree centigrade in a 16X2
alphanumeric LCD.

The output of LM35 temperature sensor is analog in nature and microcontroller cannot process
the analog signal directly. So, first it will convert the analog output of LM35 temperature sensor
to digital values using its analog to digital converter and then it process the digital value to
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

convert the digital value in degree centigrade value. Then the microcontroller will display the
temperature in degree centigrade in the 16X2 alphanumeric LCD. Now, lit a match stick or
lighter near the LM35 temperature sensor and see the changes in its output value in the 16X2
alphanumeric LCD.

E
EG
LL
CO
IC
C HN
TE
LY
PO
N
DI
A'
M
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

Code:
/*-------------------------------------------------------------------
This program will read LM35 connected to ADO
For working of this program, down load lcd.h
and lcd.c from the web.
in solution explorer add both the files
make necessary port changes on LCD.h

E
EG
in our case LCD data bus is connected to PORTB
RS to PD4 RW to PD5 and En to PD6
-------------------------------------------------------------------*/

LL
#define F_CPU 8000000UL

#include <avr/io.h>

CO
#include "lcd.h" // you have to paste lcd.h on your working folder

void InitADC()
{

IC
ADMUX = ADMUX &0B00111111;
//ADMUX=(1<<REFS0); // For Aref=AVcc;
ADCSRA=(1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0); //Prescalar div factor =128
HN
}

uint16_t ReadADC(uint8_t ch)


C
{
//Select ADC Channel ch must be 0-7
TE

ch=ch&0b00000111;
ADMUX|=ch;
LY

//Start Single conversion


ADCSRA|=(1<<ADSC);
PO

//Wait for conversion to complete


while(!(ADCSRA & (1<<ADIF)));
N

//Clear ADIF by writing one to it


//Note you may be wondering why we have write one to clear it
DI

//This is standard way of clearing bits in io as said in data sheets.


//The code writes '1' but it result in setting bit to '0' !!!
A'

ADCSRA|=(1<<ADIF);
M

return(ADC);
}

void Wait()
{
uint8_t i;
for(i=0;i<20;i++)
_delay_loop_2(0);
}

int main(void)
{
uint16_t adc_result;
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

//Initialize LCD
LCDInit(LS_BLINK|LS_ULINE);
LCDClear();

//Initialize ADC
InitADC();

//Put some intro text into LCD


LCDWriteString("Temp =");

E
EG
while(1)
{
adc_result=ReadADC(0); // Read Analog value from channel-0

LL
LCDWriteIntXY(9,0,adc_result,4); //Print the value in 4th column second line

CO
Wait();

}
}

IC
//-------------------------------------------------------------------
C HN
TE

Note
LY

For this program to work you have to down load lcd.h and ldc.c
PO

from the web and paste to your working folder. Add these files on
solution explorer selecting your project.
N
DI
A'
M
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

E
EG
LL
CO
IC
HN
CHAPTER 6
C
Assembly language programming
TE
LY
PO
N
DI
A'
M
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

Experiment 8
Port programming in assembly
Aim : To program LEDs connected to PORTB as required using soft delay in assembly

E
language.

EG
Objective

LL
After completion of this experiment the student will be able to

CO
understand fundamentals of assembly language programming

IC
HN
Theory
C
TE
LY
PO
N
DI
A'
M

Code:
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

/*-------------------------------------------------------------------
This program turns LED connected to PORTB ON
--------------------------------------------------------------------*/
.include "m32def.inc"

.org 00

E
EG
JMP main ; go to main

;------------ initializing PORTB -----------------------------------

LL
; set all pins of PORTB as output

init_portB:

CO
LDI R20, 0xff
OUT DDRB, R20 ; set all pins of PORTB as output
RET

IC
HN
;------------ main program ------------------------------------------
main:
C
CALL init_portB
LDI R16,0x0f
TE

OUT PORTB, R16 ; set all PORTB 0x0f


loop:
LY

RJMP loop ; indefinite loop


PO

; RJMP used here to reduce number of code bytes


; you can also use JMP but add additional 2 bytes as
; JMP is 4 byte instruction
N

;--------------------------------------------------------------------
DI
A'
M
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

Experiment 9
Code conversion

E
Aim : 1. To convert the given binary coded decimal - BCD to ASCII in assembly language.

EG
2. To convert the given ASCII to binary coded decimal in assembly language.

LL
CO
Objective

IC
After completion of this experiment the student will be able to
understand the concept simple code conversion.
C HN
TE

Packed BCD to ASCII conversion


LY

In many systems we have what is called a real-time clock (RTC). The RTC provides the time of day
PO

(hour, minute, second) and the date (year, month, day) continuously, regardless of whether the
power is on or off (see Chapter 16). This data, however, is provided in packed BCD. For this
data to be displayed on a device such as an LCD, or to be printed by the printer, it must be in
N

ASCII format.
To convert packed BCD to ASCII, you must first convert it to unpacked BCD. Then the unpacked
DI

BCD is tagged with 011 0000 (30H). The following demonstrates converting packed BCD to
ASCII.
A'
M

Packed BCD Unpacked BCD ASCII


29H 02H & 09H 32H & 39H
00101001 0000 0010 & 0011 0010 &
0000 1001 0011 1001

Code:
/*------------------------------------------------------------------

* Write a program to convert the packed BCD to two ASCII numbers


* and place them in R21 and R22.
------------------------------------------------------------------*/
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

.INCLUDE "M32DEF.INC"
LDI R20,0x29 ;the packed BCD to be converted is 29
MOV R21,R20 ;R21 = R20 = 29H
ANDI R21,0x0F ;mask the upper nibble (R21 = 09H)
ORI R21,0x30 ;make it ASCII (R21 = 39H)
MOV R22,R20 ;R22 = R20 = 29H
SWAP R22 ;swap nibbles (R22 = 92H)
ANDI R22,0x0F ;mask the upper nibble (R22 = 02)
ORI R22,0x30 ;make it ASCII (R22 = 32H)

E
HERE:

EG
JMP HERE

//--------------------------------------------------------------

LL
ASCII to packed BCD conversion

CO
To convert ASCII to packed BCD, you first convert it to unpacked BCD (tomget rid of the 3), and
then combine it to make packed BCD. For example, for 4 and 7 the keyboard gives 34 and 37,

IC
respectively. The goal is to produce 4711 or "0100 0111", which is packed BCD. This process is
illustrated next.
HN
Key ASCII Unpacked BCD Packed BCD

4 34 0000100
C
TE

7 37 00000111 01000111 which is 47H


/*------------------------------------------------------------------
LY

* Write a program to convert the ASCII to packed BCD


* and place them in R21 and R22.
------------------------------------------------------------------*/
PO

.INCLUDE "M32DEF.INC"

LDI R21, 14' ; load character 4 to R21


N

LDI R22,'7' ; load character 7 to R22


DI

ANDI R21,0x0F ; mask upper nibble of R21


SWAP R21 ; swap nibbles of R21
ANDI R22,0x0F ; to make upper nibble of packed BCD
A'

; mask upper nibble of R22


OR R22,R21 ; join R22 and R21 to make packed BCD
M

MOV R20,R22 ; move the result to R20

HERE:
JMP HERE

//--------------------------------------------------------------
REVISION-2015 [MICROSOFT WORD - EMBEDDED LAB MANUAL]

E
EG
LL
CO
IC
C HN
TE
LY
PO
N
DI
A'
M

You might also like