Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Unit-5 8051 Programming in C_Technical

The document outlines the syllabus and content for programming in C for the 8051 microcontroller, covering data types, control statements, time delays, and various programming techniques. It includes example programs and explanations of key concepts such as accessing ROM space and data serialization. Additionally, it emphasizes the importance of selecting appropriate data types and provides review questions for assessment.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Unit-5 8051 Programming in C_Technical

The document outlines the syllabus and content for programming in C for the 8051 microcontroller, covering data types, control statements, time delays, and various programming techniques. It includes example programs and explanations of key concepts such as accessing ROM space and data serialization. Additionally, it emphasizes the importance of selecting appropriate data types and provides review questions for assessment.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

8 8051 Programmingin C

Syllabus
Data types in 8057C, programming for time delay, VO
in 8051 C, Control statements and programming in 8051 C, Logic operations
loops in embeddedC,
Data conversion programs in 8051C, Accessing code Functions and Arrays in embedded C,
using 8051 C. ROM space using 8051C, Data serialization

Contents
8.1 Introduction
8.2 Data Types in 8051 C Summer-16,18,19, Marks 7
Winter-13,17,
Summer-16, 17, 18, 19, . Marks 7
8.3 Time Delays in 8051 C
8.4 VO Programming in 8051 C
Winter-18, Marks 6
8.5 Logical Operations in 8051 C
8.6 Data Conversion Programs in 8051 C
Summer-12, Marks 7
8.7 Accessing Code ROM Space
8.8 Data Serialization using 8051 C
8.9 More Examples Winter-11,
Summer-12, 14, 18, 19, "Marks 7

(8- 1)
portable
ishardwate
definitions, the size flewrk availabie
7Marks 18,19 rai
Programming
in
c GTU:
Summer-16,18,19 of
use all
can
that thehex
assemblh Summer-16,17,
the contains for topics. types value
many via file note
thatthe
reasonsthan 9,18,1
register hex than data
programfileproduces libraries. related
other Summer-16. its and or
+32767
to
-32768
across smaller C the 127
as
This toimportant
many in range
255
to
0
to+127
programs are 17, typical
variable 0 +
1to
such reg51.h. to
function and Winter-13, to
our compiler
muchare portable assembly.What Value -128 128
features
to 8051 :GTU
in
available is there update. data
?programming available -
file is write the
microcontroller.
It language
thatspecific theCinformation fact,
in is
available
microcontroller
of
instead GTU: the
for
language
made include this
to and
consumning programming of
C thatsize
are
8-2 architecture assembly modify
from code
in
program
assembly
the Bytes or
2
programming
be to
must need this the Apart assembly:to use to
program.
dataabout
types 1
With the timeeasierto one modifications.
C 8051 preferred 8051C
Microprocessors thatcode we ofROM compiler.less allows
Microcontrollers
and by for the writting information
Bits 8/16
registers.
microcontroller study C
and is
8 8
up files.
means producedof it
C 8051 is
programming the
8.2.1
lists
8.1 level startinclude the instead
Introduction flexible;
easier C
in for of in
in written we
no
8051into C Programming size
reasons Types signedchar
unsigned
or chapter,
This the Questions
Review the Data
type char
high and downloaded
file C muchmore on
architectures.
initialization
and of by Program
little the Comment gives bit enum
8051definitions in programs
hexproduced State WhyC?
C
in Data Table
The
a libraries is is with this 8.2.1
is the It C
For In 1. 2. 3.
C 1. 2. 3. 4. 8.2 Table
be of
Microprocessors and Microcontrollere 8-3 8051 Programming in C

signed short 16 2 -32768 to +32767


unsigned short 16 2 0to 65535
signed int 16 -32768 to +32767

unsigned int 16 2 0 to 65535

signed long 32 4 - 2147483648 to 2147483647

unsigned long 32 4 0to 4294967295

float 32 t 1.175494E-38 to ± 3.402823E+38

sbit 1 0 to l

sfr 8 0to 255

sfr16 16 2 0 to 65535

Table 8.2.1 Data types

8.2.1 Using the Appropriate Data Type


for the 8051 is limited to 64
It is necessary to keep in mind that the code space
necessary to look at the size of the
kbytes and it has limited on-chip ROM. Thus, it is appropriate
created hex file. One way to keep the size of data file optimum is to use
considered while selecting the data type.
data type. The following points must be value
data type. Thus, it must be used to store the
The unsigned char is an 8-bit
8051 is an 8-bit microcontroller, it is one
in the range of 0-255 (00-FFH). Since the
of the most widely used data type.
is no need for signed data.
" Use unsigned data type when there use
uses the signed data type as the default. Thus when we want to
Ccompiler
keyword.
unsigned data type, we must use unsigned use to
used to access bit addressable registers. It allows
" S bit data type should be
access single bits of the SFR registers.
registers.
to access the byte size SFR
SFR data type should be used

B2.2 Example Programs values from 00-FFH to port


Write an 8051 C program to send binary counter
e Þ.2.1
P1.

Solution:
#include <reg51.b>
void main(void)
knowledge
GAL PUBLICATIONS An up thrust for
c
in
PI rport
Programming 1 58H, and
0 to
of 43H, PO
characters 15
8051 42H, port and
12
ASCII 41H, of
bitg values
33H, the vice-versa.
for
values 321, all of
sum
and
hex 30H, toggle
31H,
mychar(]="0123ABCXYZ;
char
unsigned */ */
the
00 continuously
in
send data */ send
to = PO
/
8-4 some some
to program indicates to
program values
displays FPH,
for for program
repeat */ hex
/ /time) time]
//*
= (wait (wait
c++)
c<=255;
for(c=0; c++)
c<=10;
for(c=0; C PO [OX
Microcontrollers
and
Microprocessors C 8051 when /* /* C
8051 / J
c;char
unsigned c;char
unsigned 8051numbers).
andZ. P1=mychar
[cl:
Program
: an that
an P0=0x00
P1=0xFF P0=0xFF an
WriteY <reg51.h>
#nclude P1. Writesuch Pl=0x00
P1=c;
$******
<reg51.b> Write
X, (void)
main
void
port continuouslyvold for(;:) NOPNOP NOPNOP signed
main(void)
8.2.2 C, Comment
on 8.2.3 8.2.4
B, }
A, Solution:
Example 5AHExample Solution
#include of
(Use
Example
3, and
MicroproCeSsors and Microcontrollers 8-5
8051 Programming in C

Solution:
#include <ng51.h>
vold maln(void)

igned char i, j:
i= -12;
j= 15;
P1 = i+ j;

Example 8.2.5 Write an 8051 C program to toggle bit 0 of the port P1 (P1.0) 20,000 times.
Solution:
#include <reg51.b>
sbit PORTBIT = P1^0: /* sbit is declared outside of main function */
void mairn(void)

unsigned int i;
for(i = 0; i<=20000; i+ +)

PORTBIT = 0;
PORTBIT = 1;

Comment : P1^0 represents bit 0 of port 1.


to find number of posittve and
Example 8.2.6 Write an EmbeddedC progtam for 8051
among five byte of aray. Send number of positive data to port P1 and
negative data GTU :Winter- 13, Marks 7
negative data to port P2.
Solution :
# include <reg51.h>
void main (void)
5A,0xF0,0x 80, 0x 12 }
unsigned char data [ ] = {0x 18,0x
unsigned char i, val ;
for (i = 0; 1<5; it+)
{
val = data [i];
val = val & 0x 80;
if (val 0)
P1 = data (i];

P2 = data [i]:

up thrust for knowledge


AL PUBLICA TIONS-An
8051
Microprocessors and Microcontrollers 8-6
Programming in C
Review Questions

compiler.
1. State the data types that are available in typical 8051 C
2. State the commonly used data type for 8051 C programming.
the data type.
3. State the points that must be considered while selecting
What are the data types availabl. :
4. Why C programming is preferred to assembly programming ? GTU : Summer-16, Marks 7
C?
GTU :Summer-17,
5. Mention the data types in C programming languages for 8051.
Marks 3
GTU : Winter-17,Summer-18, 19, Marks A
6. Write data types available in embedded C.

8.3 Time Delays in 8051 C


We can create time delay in 8051 Cby two ways :
Using for loop statement
Using the 8051 timers
We cannot get the exact delays using simple for loops because of following reasons :
1. The instruction execution speed varies according to the number of clock periods
per machine cycle. The different variants of 8051 microcontroller use different clock
periods per machine cycle.
2. The crystal frequency connected to the Xj -X input pins. The duration of the
clock period for the machine cycle is a function of this crystal frequency.
3.In case of C programs, it is the C compiler that converts the C statements and
functions to assembly language instructions. As a result different compilers
produce different code and hence instructions executed in a loop may vary witn
different compilers.
Example 8.3.1 Write an 8051 Cprogram totoggle bits of port 1 to turn OFF and ON LEUS
connected to the port,
Solution:
#nclude <reg51.h>
Repeat the
void DELAY(void); statements in the loop indefinitely
vold main(void)

forl:)

P1=0xFF /Turn ALL LEDs ON /


DELAY() /Wait for some time*/
P1=0x00 /Tum all LEDs OFF"/
TECHNICAL PUBLICATIONS - An up thrust for
Microprocessors and Microcontrollers 8-7 8051 Programming in C

DELAY() /*Wait for some time*/

void DELAY (vold)


{
unsigned char i,j:
for(i=0; i<=255; i=i+1)
{
for(j=0; j<=255; j=j+1)
{

}
Comment : Here we don't know the exact delay produced by the
However, if we see the equivalent assembly language delay loop.
program
calculate exact delay by calculating the delay produced by loop given below, we can
crystal frequency and microcontroller used. instructions with given
Equlvalent assembly language program
ORG O
SJMP MAIN
ORG 30H
MAIN: MOVP1, #0FFH
CALL DELAY
MOV P1, #00H
CALL DELAY
SJMP MAIN
END

DELAY: MOVR0, #00H


LOOP1: MOV R1, #00H
LOOP2: INC R1
CJNE R1, #255, LOOP2
INC RO
CJNE RO, #255, LOOP1
RET
When we use functions like DELAY in the above Cprogram we need to
know the
following points :
Before the main function, the declaration :
void DELAY (void)
Informs the compiler that there will be a function called DELAY, requiring no
parameters and returns no parameters. This is called 'function prototype'. Every
function in a C program must be declared as above.
The functions are normally defined immediately after the main program ends as
above. The first line of the function declaration must be exactly the same as its
function prototype otherwise, the compiler will generate an error message during
TECHNICAL PUBLICATIONS - An up thrust for knowledge
DELAY(vold)
vold DELAY(void);
main(void) #include
void<reg51.h>
voldSolution: Example
Microprocessors
Microcontrollersand
nt "
" above. its
Functions
requires To
function The used
function function.
8.3.2 DELAY(): use compilation
i<=255;
for(i=0;
i=i+1)
unsigned do
N=0; char N; name
: j<=265;
for(j=0:
j=j+1) whlle(N<10); } { unigned the within
N=N+1; Pl=0x00;
DELAY(); P1=0xFF;
DELAY(); Write less name is
make furnction, of An
space implemented. the
char an may a function,
open
s 8051 programs function function process.
i, in
j; /* /* / /
the not curly
C the
Wait Tum Wait Tum name have
progTam
memory The are A
the to must bracket
for all for all spaces, t function
se be of
some LEDs some LEDs to the follow function hen
to
and 8-8
of time OFF time ON flash shorter function or declaredmarks
therefore is
/ LEDs any the ends
/ */ / and defined
the
punctuation. rules in
is
. 10
readable. used with the
beginning
tmes. better tor anext in
as the closed the
efficiency. line
Afollows name of
same
hart
Fi.3g.1. shorter curlybefore the
No
: of way 8051
LEDs
TumOFF LEDs
Tum ON a bracket the Programming
10?N> N=N1
program variable. as
End Is Wait Wait N=0 Start body
Yes as th
shown variables,
alee The of in
the c
#define
main(void)
<reg51.b>LEDSolution:
P2
void#include Question
Review LOOP2:
LOOP1:
Example better type 8.4.1 84 DELAY: MicroprocOSSOrs
Microcontrolersand
MAIN:START: Equlvalent
the know
that,We
variables 1.
understanding
count /O State
8.4.1 Byte
LED=0;
} for(::)
LED++; Programming RETCJNE INCCJNE R1
RO INC#00FH
MOVR1,#00H
MOVRO, ENDCJNE DELAY CALL
#0FFH
MOVP1,
from the INC CALL
A DELAY
#00H
MOVP1, MOV#00 A,
Eight to Size factors ORG
3OHGssembly
START
SJMP ORG 0
0
commnicate RO, R1, A,
/* to
LEDs ports VO #10,
L of that #255, #255,
define FFH
/*increment P2
continuously
/*repeat
*/ /clear/ the can MAIN language
are P0-P3 LOOP1 LOOP2
(0000 program.
This is
P2 in afect
port as
connected
- 0000 with are 8051 the
LED
P2 byte delay program
*/ to ports.
*/ to
1111
C size.
accessible. 8-9
port We
********illustrated
1111 P2.
An
can
up in
rust binary)
Write assign So
in we
for an the
*******************
dge on 8051 different can
the
following
C use
LEDS.
program unsigned data
labels char GTU
examples. 8051
:
that to Winter- Programming
them
shows
18
for
in
C
Microprocessors and Microcontrollers 8- 10
9051
Example 8.4.2 Write an 8051C program to get a byte of data from
Programming in
Pl and then
C

P2.
send it to

Solution:
#include <regb1.h>
#defne INP P1
#defne OUTP P2
void main(void)

unigned char mybyte;


INP=0xFF: /*Configure port P1 as an input port /
while(1)

mybyte = INP; /*read a byte from P1 */


OUTP = mybyte; /*send it to P2 */

Example 8.4.3 Write an 8051 C program toreada byte of data from P0. ft is less than 50,
send it to Pl, otherwise, send it to P2.
Solution :
#include <reg51.h>
void main(void)
{
unsigned char mybyte
P0=0xFF ; /* Configure port PO as an input port /
mybyte=P0; /* read a byte from PO */
if(mybyte<50)
P1=mybyte; / send it to P1 if less than 50*/
else
P2=mybyte; / send it to P2 if more than 50*/

8.4.2 Bit-Addressable /O Programming


The I/O ports of PO-P3 are also bit-addressable. We can access a single bit without
disturbing the rest of the port. We use the sbit data type to access a single bit of PO-P3.
One way to do that is to use the Pi ^j format where i is the port 0, 1, 2 or 3 and j is
the bit 0-7 of that port. For example, PO ^ 3 indicates PO.3. This is illustrated n
following examples.
Example 8.4.4 Write an 8051 Cprogram to toggle only bit PO.5 continuously.

TECHNICAL PUBLICATIONS - An up thrust for knowledge


Microprocessors and Microcontrollers 8- 11 8051 Programming in C

Solution:
toggling an individual bit */
nclude <reg51.h>
sbit portbit = P0^5; /*declaration of single bit is using sbit/
void main(void)

while(1)

portbit=1; /* turm on P0.5 */


portbit=0; /* turn off PO.5 */

Example 8.4.5 Write an 8051 Cprogram to monitor bit P1.5. If it is high,


send 00H to PO;
otherwise, send OOH to P2.
Solution:
#include <reg51.h>
sbit portbit = P0^5; /* declaration of single bit using sbit */
void main(void)

portbit=1; /* configure mybit an input */


if(portbit==1)
P1=0x00;
else
P2=0xFF;

Example 8.4.6 Write an 8051 C program to send a given message, My program" on the
LCD connected to PO. Every time to latch the data into the LCD, it is
necessary to make
its enable (En) pin from high t0 00
Solution:
#incude <reg51.b>
#define LCD Data PO
sbit En=P1^0;
void main(void)

unsigned char message |]="My program";


unigned char C;
for(C=0; C<10; C++) / send 10 characters "/

LCD Data = message [cl:


B051 Programming inc
En=1; / Make En high /
En=0; /° Make En Low /

8.4.3 Accessing SFR Addresses 80-FFH


We can also access the SFR RAM space 80-FFH by using the sfr data type.
illustrated in example 8.14. Furthermore, we can also access a single bit of any SFR if is This
specify the bit address. It is important to note that, here, programmer has to kno. we
corresponding addresses and there is no need to have #include <reg51.h> statement in
the program.
Example 8.4.7 Write an 8051 C program to toggle all the bits of PO and P2 continuoueh
with a some delay. Use the sfr keyword to decare the port addresses.
Solution:
/ Accessing ports as SFRs using the sft data type "/
t PO = 0x80; / declaration of PO using sfr data type */
GP2 = 0xA0; / declaration of P2using sfr data type */
void Delay (undgned nt):
void main(void)
{
while(1) /* read it continuously */

PO=0x55;
P2=0x55;
Delay(250); /* delay */
PO=0xAA;
P2=0xAA;
Delay(250);

vold Delay (unsigned int count)

unslgned int i, j:
for (i=0; Í<count; 1++)
for (j=0: j<1200; j++)

}
Example 8.4.8 Write an 8051 C program to turm bit PO.5 on and off 10,000 times.
Winter-18. Marks 6
GTU :

lodae
MicroprDceSSors and Microcontrolers 8-13 8051 Programming in C
Solution :
sbit PORTBIT = 0x85; /*
another way to declare bit P0^6 */
vold main(vold)
{
unsigned int i;
for(i=0; i<10000; i++)
{
PORTBIT=1;
PORTBIT=0;

8.4.4 Using Bit Data Type for


Bit-Addressable RAM
We can use sbit data type with only bit
addressable SFR
addressable section of the data RAM space 20-2FH, we can useregisters. To access bit
bit data type. This is
illustrated in example 8.4.9.
Example 8.4.9 Write an 8051 C program to get the status of bit PO.0,
send it to P1.5 continuously.
complement it and
Solution:
#include <reg51.h>
sbit inbit = PO^0:
sbit outbit = P1^5;
bit tempbit;
void main(void)

while(1)
{
tempbit=inbit; /* read a bit from PO.0 */
if(tempbit==1)/* complement the bit */
tempbit=0;
else
tempbit=1;
outbit=tempbit; /*send it to P1.5 /
}

85 Logical Operations in 8051 C


is monitoring
one of the most frequent operations required in embedded applications
a single or a group of bits of a port, checking the status of a bit and controlling an
operations such as
external device connected to a bit of an output port. Callows logical
and right. The Table 10.2
AND, OR, Exclusive-OR as well as shifting a byte to the left
shown below provides the syntax for such operations.
TECHNICAL PUBLICATIONS -An up thrust for knowledge
MicroprOCessors
Microcontrolers
and
vold main(void)
unsigned
void char C; <reg51.h>
sbitP0^0; void Solution :
S0=sbit#include Example
DELAY LED DELAY monitors
ORAND NOT
=
Shift Shift EX-OR
r for do P1^0;
8.5.1 Operation
founslgned { forwhile { SO
1;= (unigned switch left right
(j=0; (i=0; LED=LED;
(unsignedDELAY(1500);
(c=0; ToTable by
(S0 by
j<1200: SO
illustrate n-bits n-bits
i<count; int c<20; == /*
int int); and 8.5.1
LED
i,j: 0); /*
count) c++) when Examples
* * /* is
switch some
j++) i++) RLA RRA #DATA
XRL #DATA
A, ORL A,
#DATA
ANL A, CPL A
invert Check
Configure connected assembly In
/*
pressed, of
is
the flash connected the of
whether
to it logical 8-
14
status P0.0
LED port fashesabove
ten SOan to operations
of P1.0
An LED input
is port the
operations,
times pressed
up */ InC
stnglesin &
/ */ 0.0
st */ in
*/ LEDO
or let G
for not and =A>>
A A n ADATA=AADATA
A=A A-A;
&
ge */ ten us - =A
write assem Example inC
times. A
<Kn A 8051
DATA
a bly
Programming
program

that in
C
C window continuously
in C the
Prograrmming8051
sound
pin, an
Writeopen,
Pl.0 Hz. P2
8051
the P2.0.gets
hundred and knowedg
/
to to one input siren"/ PO
connected
connected few of
any an for
a of bits
P1.1 thust
Whenof status the
wave and
is is all up
sensor
sirensensor.
square P1.0 the An
toggle -
invert
8-
15 doora Configure PUBLIC
the window
a
sending while(Dsensor=1
Wsensor==1) to operator.
a and / mogram
system,
pin, and
by Ex-OR
P1.1 i++)j++) TECHN
and guard doorsiren
Microcontrollers
Microprocessors count) C
the the the
siren
siren;
~
i<count; 8051the
int): i,j: j<1200; P0=PO^
OxFF;
hometo
sound int unlgned
DELAY(150); int
Use int):
P2=P2^
OxFF:
monitor (undgned 1= Wsensor
1=
Dsensor (ungigDed an
connected ^0: P1^1;
<reg61.h>
Hnclude
a P2^0:
= (j=0;
(i=0; Write delay. (unlgnedPO=x55;
#ncude
<eg61.h> P2=0x665;
In can P1 whlle(1)
8.5.2 to (vold)
main
vold
We = = for for some vold
main
(vold)
is rogram DELAY Wsensor
Dsensor 8.5.3
sensor siren. Solution:
Ceample
} DELAY
Siren
sbtt a Solution
: Delay
trample
twith
vojd sbit sbit vold vold
{
(vold)
void Solution :
<regQl.h>
#include tempbit; vold Microprocessors
Microcontrollersand
Example
Write
8.5.5 } main(vold)
void bit sbit sbtt Solution :
<reg51.h>
#include Exampl
it
e
character outbit inbit Delay(unsigned
=
= 8.5.4
while(1) P1^5;P0^0;
forunigned
for init,j:
outbit=tempbit;
to tempbit=inbit; (j=0; (i=0; Delay(250);:
PO Write
bit-addressable/*tis
according j<1200;
i<count; int
an an
8051 8051 count)
/*sbit
to C j+i++)
1 1
M.1 +)
0 the
progam is
status /*invert/read used program C
memory*/ to
Table
8.5.2
of to a declare to 8-16
bits read it bit
and get
1
P1.0 from
given the
send port
bit
P0.0 PI.0
inP1.0 it (SFR)
send send send send the and to */ and
following P1.5
Action bits"/
D' 'C 'B' 'A P1.1 send
*/
to to to to
PO PO PO PO bits it
Table to
and P2.7
8.5.2. issue
after ogramming
int,
an
ASUu i
another.
xample
understand
tormatto provide BCD Question
Review
There O.6 Microprocessors
Microcontrollersand
and l.
the Data State
8.6.1 are
timeASCII. the switch(c) c=P1;
C=cOx3;unsigned
&
ASCI several
Conversion case(3): } case(2): } case
(1): case(0):
various break; break;P0=B; /* break;
sent break;P0=D'; P0='C; P0='A;
and
char c
information. date Manyformats logical
"12" / / /* /*
newer
operators issue issue issue issue 00000011
with*/
/* read
/
information
in Programs
to make mask
ASCII P1
ASCII ASCII ASCII
ASC, Sorepresent */
microcont rollers supported decision the
there D C B A unused
in / 8-
17
packed / / */
packed
isinformation
in by /
8051 8051 bits,
BCD a
need BCD have C. i.e.
and G ADD
to
unpacked format. asuch C
convert Real
as
The Time
BCDinformation unpackedpacked
BCD, 8051
GTU:
format. keyboard Clock Summer-12 Programming

an(RTC).
d
from
in
display They C
one
BCD and 8.6.2 main(vold)
voidSolution:
<reg51.b>
#include Solution:
35H Microprocessors
Microcontrollersand
can thconvert
Example 8.6.1
en To packed combined ToUnpacked Packed ASCII
and
be Packed
ORed
converted K2K1 unlgned
P1 K1 unsigned BCD 8.6.2 36H, convert
to ASCIl BCD 0011 :
= = = =
eachpacked K1K1 K2K1 and Write respectively. make ASCII to BCD
BCD >> &&
: 0001
K2; Ox0F; Ox0F; char char display an : 0001
toBCD BCD to to 4; binary
ASCI inASCIHEX in packed Packed to 0000
ASCII / K2 K1 8051 Packed
Unpacked pattern
BCD BCD Masking pressed
Key 0010 0011
with ASCIl /Apply
Make/*Shift /*Apply = =
them 0001
Let BCD.packed
6; '5; C BCD (one 0010
as30HASCII
Conversion packed
program
on se 0000
shown 4 P.
to times mask mask For BCD,
the Conversion byte) (i.e.
conversion, 0010
in
get BCD pattern to 0101
0000 0000
1111 0101
0011 example,
conversion it 31, 8-18
sopatterm is
ASCII
the convert 35H 32
/that first (two
Table 0101
0110 two
is
it lower to to on
bytes. get get ASCIl converted
processpressing bytes) bytes)
8.6.1. first unpacked
nibbleunpacked 0000
0110
DO00 1111 0011
0110
For digits 3611 6
converted
example, ’ keys to
upperBCD"/BCD"/ of
two unpacked
5
nibble keys and
0100 to 6
unpacked "7 3 keyboard BCD,
packed
0111 and
and ning
inG
6
BCD, to gives then
equivalent.ASCl and keep 8.6.3 main(void)
<reg51.h>
ncude
void Solution : Evample Microcontrollers
MiouprooeSSorsand
last the One the
10 10) 12310) remainder
remainders.
way Binary bytes
120 - Assume: Hex P2
y=y >> x=
4;y= unsigned
8.6.3
1 0 12 to P1unigned
2 10 12 3 on
convert (Hex) = PBCD PBCD = Write
Pl
y
|Ox30; |Cx30; x and
gives char char 805Ian
C
This & & Unpacked
number
7BH is binary to OxFO; 0xOF; P2. ASCII
bytes ORing3OH
BCD Packed
BCD
the isDecimal PBCD x,
y,
illustrated
MSD. number Z;
A)
1 7BHA) = progTam
-
0378H /* /* /* /* /* 0x47;
1 2 A make shiftmask make mask
These and
8.6.1 0011
0100 0011 0000
0000 0100
8.Fl6g.1. in to it toTable 8-
19
decimal ASCII it upper
to lower
it condert
digits Fig. ASCII ASCI
lower
4 0100
0111
n 8.6.1. 4
Conversion / bits /bits packed
p are is 4
bits */ */
to 0111
0011 0000 0111
0011 0000
then Thedivide
/ BCD
03 02 01 first
added 0x47
+30H32H02
+30H 03 remainder it in
01+30H
>31H
8051C
by ASCIIand to
with 8051
10
successively
30H gives Programming
33H
to display
get the
in
the LSD and C
Microprocessors
Microcontrollersand
Algorithm
(vold)
matn
voldSolution:
<rogQ1.b>
#include } <reg51.h>
#include
(void)
main
voldSolution: Example
Example 4. Divide
2. the 1.
the ASCI, RetrieveRepeat 3.Save
digits
Abyte
i=0;0XFB; unigned
unsigned
R|char
=3]: 8.6.5 ;i--)
while(Ql Abyte R[3];
char
doi=0;unslgned
0XFB;unsigned
= char and 8.6.4 the
{for(;
i>0 0)= } steps
on P0=R[i-1]+0x30; i=
Abyte=0;
R[i]=Abyte%10;
i+1;Q=Abyte/10;
P0, Write display Write each quotientnumber
remainder and 1
char P1 an
the an
and 8051 2
as by
Abyte, Abyte,i,0; digits 8051
P2. C untilnumber. a 10
and and
i,Q;
on Cquotient
program /* / /* /* program add
PO save
Repeat save finddivide sequentially
to /* 30H 8-20
remainder
quotient to is the
convert Make by
until convert to 0.
remainder.
10 convert
binary quotient */ (MSD
asand
8-bit a 1111
binary to number save
first). it
ASCII = 1011 to
0 it ASCII.
/ */ "/ (FBH)
GTU: data */l
Summer-12,decimal to to Programming
int 8051
decimal
ana
Marks asy and
then
1
sufficient
allocate
individual
in to back
B71 8.7 Question
Review MiMicrocontrollers
croprocessorsand
2. 1. the Ihe Let " " In
the 1.
Individual Bank
specific Whatever usExternal
can semiconductor
canrnot be (AT8951) On-chip RAM space On-chip Accessing Explain
B051 Use be burned 8051
discuss, P0-R<i
while(Ql 0)
= do
0: variables, is
directly P2=R[iPl=R[i i+1;i=
has of used write 256 we with Abyte=:
R[il=Abyte%10;
Q=Abyte/10;
addresses order 64 has ROM RAM:
variables remains 128 RAM how for Kdata to bytes. have the -3] -2] -
store has 4K Code help 1]
asRAMarray bytes both RAM or + + +
CAL Data 8051 into on-chip The : (00-7FH)
threein
0-7 given is program an indirectly spaces of 0x 0x 0x
: elementsto of RAM and example 30; 30; 30;
address used C on-chip 8051 on-chip ROM
below each on-chip Spaceprogram
NS external
and ROM, 128
for code, with how ASCII/
/*Make
Repeat
until /* /* / /
08 section, ROM using Space save finddivide
: scratch in by ROM. ROM bytes 8051
and addition RAM. 64 the which remainder 8-21
8051 uses predefined
64 kbytes the quotient
during AT8952 size : C by
beyond the pad It on-chip K We compiler 10
ROM RO we
- is varies quotient /
An register
8051 to Compller C of and can can asand
up
RAM.mainly the on-chip has uses a
data store
thrust C RAM execution
The : from R1 read number '/save
compiler In 8K RAM =
used and registers.
for 8051l C and 64 on-chip
ROM. version from data 0 it
banks data / /
ledge kbyte tables
by space. ROM of or : space
allocatesprogram,and register Thi s
of
the into ROM to Inwrite 8051
and
the externalprogram. on-chip ROMcan version. the
it.whereas into code Prograrnming
locationsRAM stack. banks However, we 8052,
we data
The this
Incan and memory space.
Dallas 8751 on-chip RAM
order have in
the C
(vold)
man sbitSolution:
vold <regb1.b>
sbit#include Note : Microprocessors
Microcontrollersand
8051C.
in example,
code For the To 8.7.2
Example 2. : 3.
ALSBoutbit first.
SendLSB 8 RAM make So 1. Stack 4.
Let " " In 8
8051, undoned far, 8051/8052 allocate The In Array
us WeWe moves
mybyte;
forunlgnedchar
= i;
ACCundgned = = 8.8.1 see carn can Data space, the we Use 8052 assembly,
However,
ACCoutbit
ALSB; = ACC^0:P2^0; there the addresses elements
(i=0; Write the
transfer Serialization
transfer char C
have of contiguous
= are compiler
we Code Chas
i<8; following compiler stack's the
ACC> hexnum[]="0123456789ABCDEF";
an seen
char two need 256 :
1++) 8051 data data Data default right
addresses
>1; mybyte ways to use that bytes RAMstarting
C serially
example serially array
after
programn using
to
put the all Space manage to starting
=0X24; code byte locations
ofaddress right
transfer
via using the
programs 8051 RAM
to port keyword space size by its address elements. after
to 8-22
send serial data variables 8051registersspace
pin C to array to variables
byte to
using port serially code store C somewhere for
see /*use instead
elements. the
24H and were and
how
software predefined in
serially code front stack
supported stored resources of in
data space
of 128 the is
one
serialization control. th e data in 08H.
/ the muchbytes. range
bit hardware.
at variable or128 8051
a tables more of
time bytes This Programming
can TFHto
50H
via declaration.instead
of
effectively. helps C
be compiler
P2.0. done RAM
the in
of C
C
in P2.0. P2.0.
Programming
via via
time time
8051 a a
P2.0 at at knowled
bit Ao bit
one one
A1
serially serially for
Ao thrust
241H Register
ACC up
Ay Ag byte
byte An
Ag A receive -
8-23 send PUBLICA
TECHNIC
Register
ACC
Ag to A_ t0
0X24;
program progzam
As
=
mybyte
Az
Microcontrollers As C ACC
=
ACC<<1;
i++) outbit C
8O51 =
AMSB; 8051 i++)
unsigned
char
i; AMSB
inbit;
=
Ag char ACC
=
mybyte;
i<8;
undoned
char
i;
an
P2.0 an LSB. i<8;
Ag Write ACC^7: unrlgned(i=0;
Anclude
<reg51.h> #inchude
<
reg61.b>ACC^7;
Send
MSB
first. P2^0; Write (i=0;
and
Microprocessors is P2^0;
void
main
(void) for vold
man
(void)
8.8.2
= = }
8.8.3bit for
Solution: AMSB first =
outbit = AMSB
Solution:
Example Example inbit
The
cbitsbit sbtsbit
{
MicroproDCeSsors and Microcontrollers 8-24 8U51
Programming in c
ACC = ACC>>1;

P2.0 A7 A_ As As Ag Ag Aq Ao
Register ACC
Example 8.8.4 Write an 8051 C program to receive byte serially one bit at a time via PTn
The first bit is MSB.
Solution:
#include <reg51.h>
sbit inbit = P2^0;
sbit ALSB = ACC^0;
void main (vold)

unsigned char i;
for (i=0; i<8; i++)

ALSB = inbit;
ACC = ACC<<1;

Ay As As A4 Ag Ag A4 Ao P2.0

Register ACC
Review Question

1. Explain the process of data


serialization using 8051C.
8.9 More Examples GTU : Winter-11, Summer-12,14, 18,19
Example 8.9.1 There are 8 push button switches interfaced to port 0 of an lntel 8051
microcontroller. Write a program to read the state of the suvitches and operate the L
connected to port 1 accordingy. For example, if switch S0 is pressed,
S2 ana S3 are pressea, then LED Z an4 3
turns LEDO
*****E must turn ON and so on. **
Microprocessors and Microcontrollers 8- 25 8051 Programming n C

Solution :

Start

Read the state of


the switches

Operates the
LEDS

#include <rog51.h>
void mairn(void)

for(;:)

P1=PO;
}
}
The same program may also be written as follows :
#include <reg51.h>
#define SWITCHESPO
#define LEDS P1
void maln (vold)

for(;:)
{
LEDS = SWITCHES;

Comypare the following programs and discuss the advantages and disadvantages
CAample 8.9.2
of each one.

1)
#include <reg51.h>
void main(void)
{
P1="W;
P1=E;
knowledge
NICAL PUBLICATIONS An up thrust for
8051
Microprocessors and Microcontrollers 8- 26
Programming in C
P1=L;
PlC;
Pl=0;
P1M;
Pl=E;

2)
#include <reg1.h>
void main (void)

unigned char str (] WELCOME;


unsigned char i;
fori=0; i<7;it+)
P1=str{ij;

3)
ncude <reg51.h>
void main (void)
Notice keyword code1
code unstgned char strilWELCOME;
unigned char i
for (i=0; i<7; i++)
Pl=stri;

Solution : All the programs send message "WELCOME'" to port Pl, one character at a
time, but they do it in different ways. In the first program separate statements are
written to send each character to port P1. Thus, if we want to change the characters or
message, the whole program will change. It also mixes the code and data together. The
second program uses array to store message in the RAM data space. It has a imitaton
of array size. The third program also uses array to store message; but it uses code aaa
space. This allows the size of the array to be as long as on-chip ROM. However, ir
important to note that, the more code space we use for data, the less space is left for ou
program code. We can easily modify the contents of string in the program 2 a
program 3. That is not the case for program 1.
Example 8.9.3 4) Find the checksum byte for the hexadecimal data : 18H. 5AH, 46H a
69H. b) Perform the checksum to ensure data integrity. c) With an example show hou
7
checksum detects the error, GTU : Summer- |14, Winter- 11, Marks
is stored
Solution : To ensure the data integrity of the ROM contents, one extra bytecalculated by
the end of a series of data bytes called checksum byte. This byte is
performing two operations :
MicroproceSsors and Microcontrollers 8-27
8051 Programming inC

" Add all data bytes without considering carry.


Take 2's complement of the resulted sum.
a) Let us find the checksum byte
18H + 5AH + 46H + 69H - 121H

Ignoring carry we have sum = 21H. Taking 2's complement we have checksum
byte = DFH.
b) To ensure data integrity all the bytes including checksum byte are added.
Ignoring the carry if sum is 00H then the data integrity is ensured. Let us
check this
18H + 5AH + 46H + 69H + DFH = 200H
Ignoring carries we have sum equal to zero and therefore, we can say that data
is valid and not corrupted.
c) Let us consider that the last of data is corrupted arnd it is now 68H instead of
69H. By adding all byte with checksum byte we get,
18H + 5AH + 46H + 68H + DFH = 1FFH
say that data is
Ignoring carry in the sum, result is not zero and hence we can
corrupted.
Example 8.9.4 Write an 8051 C program to calculate checksum byte for the given data of four
GTU :Summer-14, Marks 7
bytes.
Solution:
#incude <reg51.h>
void main (void)
{0X18,0X5A,0K46,0K69)};
unsigned char data[] =
unigned char sum=0;
unsigned char chksumbyte,i;
for(i=0; i<4; i++)
{ as byte
/* since sum is declared
Sum =sum + data[i);
data type, carries are ignored
automatically /

2s complement
chksumbyte = ~ sum+1; Take

perform data integrity check for data given in


program to
Example 8.9.5 Write an 8051 C character V (valid) on port Pl; otherwise
send ASCIl
example. If data is not corrupted,
Send 'C' (corrupted) on port PI. knowledge
An up thrust for
TECHNICAL PUBLICATIOWS-
Solution :
#include <reg51,h>
vold main (vold)

unsigned char data|] ={0X18,0X6A,0X46,0X69,0XDF};


unslgned char chksum=0;
unsigned char i;
for(i=0; i<5; it+)
chksum=chksum+data[i];

if(chksum==0)
P1=V:
else
P1=C;

Example 8.9.6 Write an 8051 Cprogram to toggle all the bitsof Pl, P2 and POcontinuously
with a 250 ms delay. Use SFR keyword to declare the port addresses.
GTU :Summer-18,19, Marks 7

Solution:
#include reg51.h>
void Delay (void):
void main (void)
{ while (1) /* Repeat continuously "/
{
P0=0 x 55: /* toggle all bits of PO */
p1=0x 55; /* toggle all bits of P1 */
P2=0 x 55; /* toggle all bits of P2 *
Delay (250); /* wait for 250 ms */
PO=0 x AA; / toggle all bits of PO */
P1=0x AA; /* toggle all bits of P1 */
P2=0 x AA; /* toggle all bits of P2 */
Delay (250) * wait for 250 ms */

void Delay (unsigned int count)

unsigned int i,j:


for (i=0; i < count ; i++)
for (j=0; j< 1275; j++);
Microprocessors and Microcontrollers 8- 29 8051 Programming inC

Example 8.9.7 A stwitch (SW) is connected to P2.0 port pin, Write a C program to send out
the value 44H serially one-bit at a time via P1.0, depending upon the switch conattto :
When SW 0; LSB should g0 out frst, When SW 1; MSB should go out first.
Solution: Switch (SW) connected to P2.0 port pin P2.0 = 0 send serially value 44 by LSB
via P1.0 when P2.0=1 then send serially value 44 by MSB via P1.0

sbit s0 = P2^0; /* Switch is connected to port P2.0 pin */


sbit outbit = P1^0: /*send data value via P1.0*/
sbit ALSB = ACC ^0:
sblt AMSB = ACC ^7;
void main(void)

unsigned char Datavalue = Ox44;


unsigned char
ACC = Datavalue;
if(S0= =0) /* if SW = 0send LSB first */

for (i=0, i<8; i++)

outbit ALSB;
ACC = ACC>>1;

}
else /*else switch = 1send MSB irst */

for(i=0; i<8; i++)

outbit =AMSB:
ACC = ACC<<1;

Example 8.9.8 Write a Cprogram to toggle al bits of PO and P2 continuously with 250
msec delay. Use inverting operator, GTU : Summer- 12, Marks 7

Solution:
#include <reg51.h>
vold MSDelay (unslgned int);

TECHNICAL PUBLICATIONS - An up thrust for knowledge


MicroproceSSors and Microcontrollers
amming inG
vold main (vold)

PO = Ox55:
P2 = Ox55;
whlle (1)

PO = ~PO;
P2 = ~P2;
MSDelay (250);

void MSDelay (unsigned int count)

unsigned int i, j:
for (i = 0; i< count; i++)
for (j = 0; j < 1275; j++)

Example 8.9.9 Write a 8051 C-program to converta given het-data OFE mto its equtalent
decimal data and displaytheresultdigits on PO, PM and P2.
Solution:
#inchude<reg51.h>
void main(void)

unsigned char x, binbyte, d1, d2, d3;


binbyte = 0xFF;
x=binbyte/10;
d1=binbyte%10;
d2 = x%10;
d3 = x/10;
P0=d1;
P1=d2;
P2=d3;

Review Question

1. What is checksum byte ? How is it useful for checking data


integrity ?
O00

TECHNICAL PUBLICATIONS - An up thrust for


knowledge

You might also like