Course
Introduction
EMT355/3 Microcontroller
Lecturers
Mr. Ahmad Husni Bin Mohd Shapri
Ir. Dr. Razaidi Hussin
Text Book
8051 Microcontroller and
Embedded Systems
by Muhammad Ali Mazidi
Teaching Plan
2 Parts
Assessments
Continual Assessment (30%)
Lab 1-3 (10%)
Assignments (20 %)
Mid Term Test (20%)
Mid Term Test (20%) – tentatively: SW-8
Final Examination (50%)
Course Outcomes
CO1: Ability to define, summarize, illustrate and classify
the concept and requirement of embedded system
CO2: Ability to define, summarize, illustrate, classify
and design a structured programmed in C
programming language for the system application
CO3: Ability to define, summarize, illustrate, classify,
design and evaluate embedded system based in a
single chip microcontroller
Introduction to
Embedded
System
Lecture: 3 hours
Embedded Systems
Overview
Computing systems are everywhere
Most of us think of “desktop” computers
PC’s
Laptops
Mainframes
Servers
But there’s another type of computing system
Far more common...
Embedded Computing
Systems
Computers are in
here...
Computing systems embedded and here...
within electronic devices.
and even
Hard to define. Nearly any here...
computing system other than a
desktop computer.
Billions of units produced yearly,
versus millions of desktop units.
Lots more of these,
Perhaps 50 per household and though they cost a
lot less each.
per automobile.
Common Characteristics
of Embedded Systems
Single-functioned
Executes a single program, repeatedly.
Tightly-constrained
Low cost, low power, small, fast, etc.
Reactive and real-time
Continually reacts to changes in the system’s
environment.
Must compute certain results in real-time without
delay.
Design Constraints
Limited Power
Most embedded systems operate within battery
operated equipment.
Limited Memory
An embedded system is constrained to a finite and
small amount of memory.
Real-Time
Most embedded systems are used in a control function.
They are expected to sense the real-time status of the
system in which they are housed and produce real-time
responses.
Definition of Embedded
System
An embedded system is a microprocessor-
based system that is built to control a function
or range of functions and is not designed to be
programmed by the end user.
The user may make choices concerning the
functionality of the system but cannot change the
functionality of the system by adding/replacing
software.
Can you “program” your refrigerator?
May be sooner than you think.
…
An embedded system is not a microprocessor used
in a “traditional” computing application
desktop PC
laptop
workstation
An embedded system is a microprocessor used as
a component in another piece of technology
(dedicated function)
Embedded Systems
Applications
Consumer segment, e.g. digital cameras,
camcorders, VCRs, Washing Machines, microwave
ovens, …
Automobiles, e.g., engine control, anti-lock brake,
air bags, …
Office automation, e.g., copiers, printers, FAX
machines, …
Telecommunications, e.g.,, cellular phones, PDAs,
interactive game boxes, answering machines, …
Other industrial products, e.g., door locks in hotel
rooms, automatic faucets, …
o Anti-lock brakes o Modems
o Auto-focus cameras o MPEG decoders
o Automatic teller machines o Network cards
o Automatic toll systems o Network switches/routers
A “short list” of o Automatic transmission o On-board navigation
embedded systems o Avionic systems o Pagers
o Battery chargers o Photocopiers
o Camcorders o Point-of-sale systems
o Cell phones o Portable video games
o Cell-phone base stations o Printers
o Cordless phones o Satellite phones
o Cruise control o Scanners
o Curbside check-in systems o Smart ovens/dishwashers
o Digital cameras o Speech recognizers
o Disk drives o Stereo systems
o Electronic card readers o Teleconferencing systems
o Electronic instruments o Televisions
o Electronic toys/games o Temperature controllers
o Factory control o Theft tracking systems
o Fax machines o TV set-top boxes
o Fingerprint identifiers o VCR’s, DVD players
o Home security systems o Video game consoles
o Life-support systems o Video phones
o Medical testing systems o Washers and dryers
Advantages of
Microprocessor-based
Replacement of discrete logic-based
circuits.
Provide functional upgrades.
Provide easy maintenance upgrades.
Improve mechanical performance.
Protection of intellectual property (IP).
Replacement of analog circuits.
Elements of an Embedded
System
Processor
Memory
Provide storage for the software and data.
Peripherals
Software
Initialization and Configuration.
Operating System.
The application software.
Error handling.
Debug and maintenance support.
Embedded System
Microcontroller
Embedded systems are mainly intended to
provide control over the behavior of the
system into which they are housed.
Therefore, it is customary to talk about an embedded
controller rather than an embedded processor.
It does process information but mainly for the
purpose of control.
When all hardware required to run the
application is provided on one chip, it is
referred to as an embedded microcontroller or
in short microcontroller.
ANY Questions
THE END
Important to know: Characteristics – Constrains - Definition - Advantages
8051
Microcontroller
Lecture: 3 hours
Microcontroller vs.
General Purpose
Microprocessor
General-purpose Microcontroller has :
microprocessors
contains : CPU (microprocessor)
RAM
No RAM
ROM
No ROM I/O ports
No I/O ports Timer
ADC and other
peripherals
…
…
General-purpose
microprocessors Microcontroller
Must add RAM, ROM, I/O The fixed amount of on-chip
ports, and timers externally to ROM, RAM, and number of I/O
make them functional
ports makes them ideal for many
Make the system bulkier and applications in which cost and
much more expensive space are critical
Have the advantage of
versatility on the amount of In many applications, the space
RAM, ROM, and I/O ports it takes, the power it consumes,
and the price per unit are much
more critical considerations than
the computing power
Microcontrollers for
Embedded Systems
An embedded product uses a microprocessor (or
microcontroller) to do one task and one task only
There is only one application software that is typically burned into
ROM
A PC, in contrast with the embedded system, can be
used for any number of applications
It has RAM memory and an operating system that loads a variety
of applications into RAM and lets the CPU run them
A PC contains or is connected to various embedded products
Each one peripheral has a microcontroller inside it that performs only
one task
…
Home
•Appliances, intercom, telephones, security systems, garage door openers, answering
machines, fax machines, home computers, TVs, cable TV tuner, VCR, camcorder,
remote controls, video games, cellular phones, musical instruments, sewing machines,
lighting control, paging, camera, pinball machines, toys, exercise equipment
Office
•Telephones, computers, security systems, fax machines, microwave, copier, laser printer,
color printer, paging
Automotive
•Trip computer, engine control, air bag, ABS, instrumentation, security system, transmission
control, entertainment, climate control, cellular phone, keyless entry
x86 PC Embedded
Applications
Many manufactures of general-purpose microprocessors
have targeted their microprocessor for the high end of
the embedded market
There are times that a microcontroller is inadequate for the
task
When a company targets a general purpose
microprocessor for the embedded market, it optimizes
the processor used for embedded systems
Very often the terms embedded processor and
microcontroller are used interchangeably
…
One of the most critical needs of an embedded system
is to decrease power consumption and space
In high-performance embedded processors, the trend is
to integrate more functions on the CPU chip and let
designer decide which features he/she wants to use
In many cases using x86 PCs for the high-end
embedded applications
Saves money and shortens development time
A vast library of software already written
Windows is a widely used and well understood platform
Choosing a
Microcontroller
8-bit microcontrollers
Motorola’s 6811
Intel’s 8051
Zilog’s Z8
Microchip’s PIC
There are also 16-bit and 32-bit
microcontrollers made by various chip
makers
Criteria for Choosing a
Microcontroller
Meeting the computing needs of the task at hand
efficiently and cost effectively
Speed
Packaging
Power consumption
The amount of RAM and ROM on chip
The number of I/O pins and the timer on chip
How easy to upgrade to higher performance or lower
power-consumption versions
Cost per unit
…
Availability of software development tools, such as
compilers, assemblers, and debuggers
Wide availability and reliable sources of the
microcontroller
The 8051 family has the largest number of
diversified (multiple source) suppliers
Intel (original)
Atmel
AMD
Infineon
8051
Intel introduced 8051, referred as MCS-51, in 1981
The 8051 is an 8-bit processor
The CPU can work on only 8 bits of data at a time
The 8051 had
o 128 bytes of RAM o 1 serial port
o 4K bytes of on-chip ROM o 4 I/O ports, each 8 bits wide
o 2 timers o 6 interrupt sources
The 8051 became widely popular after allowing
other manufactures to make and market any flavor
of the 8051, but remaining code-compatible
Block Diagram
of the Original
8051
/INT0 /INT1 T0 T1
Other
interrupts
128 bytes Timer/Counter
4K byte Program
Data Memory (Timer 0 &
Memory (ROM)
(RAM) Timer 1)
8051 CPU
64 K Bus I/O ports Serial Port
Oscillator Expansion Control
&Timing
From Crystal
Oscillator or RC ALE /PSEN P3 P2 P1 P0 TxD RxD
network (Address/data)
8051 Family
The 8051 is a subset of the
8052
The 8031 is a ROM-less 8051
Add external ROM to it
You lose two ports, and
leave only 2 ports
for I/O operations
Is 8-bit Still Relevant?
“n-bit” – the “n” refers to the data bus width of the CPU, and is
the maximum width of data it can handle at a time
PCs with 64-bit microprocessors are becoming common
Over 55% of all processors sold per year are 8-bit processors,
which comes to over 3 billion of them per year!*
8-bit microcontrollers are sufficient and cost-effective for many
embedded applications
More and more advanced features and peripherals are
added to 8-bit processors by various vendors
8-bit MCUs are well-suited for low-power applications that use
batteries
*Note: Statistics from Embedded.com Article ID# 9900861, Dec 2002
Eg: Remote
Control Car
Antenna Antenna
Front Electric
Forward RF RF Receiver Microcontroller Motor (Left/Right)
Microcontroller
Transmitter
Reverse
Rear Electric Motor
Left Power Power (Fwd/Reverse)
Voltage Regulator Voltage Regulator
Right
Car lights (LEDs)
Batteries Batteries
Controls
Harvard and von
Neumann Architectures
Harvard Architecture - a type of computer
architecture where the instructions (program code)
and data are stored in separate memory spaces
Example: Intel 8051 architecture
von Neumann Architecture - another type of
computer architecture where the instructions and
data are stored in the same memory space
Example: Intel x86 architecture (Intel Pentium, AMD
Athlon, etc.)
MCU Fetch-
Fetch operation - retrieves an
Execute instruction from the location in
Cycle code memory pointed to by the
program counter (PC)
Program
Counter
(PC)
Execute operation - executes the
instruction that was fetched
during the fetch operation. In
addition to executing the
+
F
e
Code Memory t instruction, the CPU also adds the
c
h
appropriate number to the PC to
CPU
point it to the next instruction to
be fetched.
To other
peripherals
8051 -
architecture
Inside the 8051
Registers
Program Counter
Flag Bits / PSW (program status word)
Register
Register Banks and Stack
Registers
Register are used to store information
temporarily, while the information could be
a byte of data to be processed, or
an address pointing to the data to be fetched
The vast majority of 8051 register are 8-bit
registers
There is only one data type, 8 bits
…
The 8 bits of a register are shown from
MSB D7 to the LSB D0
With an 8-bit data type, any data larger
than 8 bits must be broken into 8-bit chunks
before it is processed
…
The most widely used
registers
A (Accumulator): For all
arithmetic and logic
instructions
B, R0, R1, R2, R3, R4, R5, R6, R7
DPTR (data pointer), and PC
(program counter)
The Accumulator
The Accumulator is used as a general register to
accumulate the results of a large number of
instructions.
It can hold an 8-bit (1-byte) value and is the most
versatile register the 8051 has due to the shear
number of instructions that make use of the
accumulator.
More than half of the 8051’s 255 instructions
manipulate or use the accumulator in some way.
The Data Pointer (DPTR)
DPTR is the 8051’s only user-accessible 16-bit (2-byte) register.
The Accumulator, "R" registers, and "B" register are all 1-byte
values.
DPTR, as the name suggests, is used to point to data. It is used
by a number of commands which allow the 8051 to access
external memory.
When the 8051 accesses external memory it will access
external memory at the address indicated by DPTR.
While DPTR is most often used to point to data in external
memory, many programmers often take advantage of the
fact that it’s the only true 16-bit register available.
It is often used to store 2-byte values which have nothing to do
with memory locations.
The Program Counter (PC)
PC is a 2-byte address which tells the 8051 where the
next instruction to execute is found in memory.
When the 8051 is initialized PC always starts at 0000h
and is incremented each time an instruction is executed.
It is important to note that PC isn’t always incremented
by one.
Since some instructions require 2 or 3 bytes the PC will be
incremented by 2 or 3 in these cases.
The Program Counter is special in that there is no way to
directly modify it’s value.
…
All 8051 members start at memory
address 0000 when they’re powered
up
Program Counter has the value of 0000
The first opcode is burned into ROM address
0000H, since this is where the 8051 looks for
the first instruction when it is booted
The Stack Pointer (SP)
The Stack Pointer, like all registers except DPTR and PC,
may hold an 8-bit (1-byte) value.
The Stack Pointer is used to indicate where the next
value to be removed from the stack should be taken
from.
When you push a value onto the stack, the 8051 first
increments the value of SP and then stores the value at
the resulting memory location.
When you pop a value off the stack, the 8051 returns the
value from the memory location indicated by SP, and
then decrements the value of SP.
…
This order of operation is important.
When the 8051 is initialized SP will be initialized to 07h. If
you immediately push a value onto the stack, the value
will be stored in Internal RAM address 08h.
This makes sense taking into account what was
mentioned two paragraphs above: First the 8051will
increment the value of SP (from 07h to 08h) and then will
store the pushed value at that memory address (08h).
SP is modified directly by the 8051 by six instructions:
PUSH, POP, ACALL, LCALL, RET, and RETI. It is also used
intrinsically whenever an interrupt is triggered
ROM Memory Map in
8051 Family
No member of 8051 family can access more
than 64K bytes of opcode
The program counter is a 16-bit register
Data Type
8051 microcontroller has only one data
type - 8 bits
The size of each register is also 8 bits
It is the job of the programmer to break down data
larger than 8 bits (00 to FFH, or 0 to 255 in decimal)
The data types can be positive or negative
PSW Register
The PSW register, also
referred to as the flag
register, is an 8 bit
register
The PSW register
contains status bits that
reflect the current CPU
state.
RAM Memory Space
Allocation
There are 128 bytes of RAM in the 8051
Assigned addresses 00 to 7FH
The 128 bytes are divided into three different
groups as follows:
A total of 32 bytes from locations 00 to1F hex are set
aside for register banks and the stack
A total of 16 bytes from locations 20H to 2FH are set
aside for bit-addressable read/write memory
A total of 80 bytes from locations 30H to 7FH are used
for read and write storage, called scratch pad
…
Register Banks
These 32 bytes are divided into 4 banks of registers
in which each bank has 8 registers, R0-R7
RAM location from 0 to 7 are set aside for bank 0 of R0-
R7 where R0 is RAM location 0, R1 is RAM location 1, R2 is
RAM location 2, and so on, until memory location 7
which belongs to R7 of bank 0
It is much easier to refer to these RAM locations with
names such as R0, R1, and so on, than by their memory
locations
Register bank 0 is the default when 8051 is powered
up
…
…
We can switch to other banks by use of the PSW
register
Bits D4 and D3 of the PSW are used to select the desired
register bank
Use the bit-addressable instructions SETB and CLR to
access PSW.4 and PSW.3
Stack
The stack is a section of RAM used by the CPU to
store information temporarily
This information could be data or an address
The register used to access the stack is called the
SP (stack pointer) register
The stack pointer in the 8051 is only 8 bit wide, which
means that it can take value of 00 to FFH
When the 8051 is powered up, the SP register contains
value 07
RAM location 08 is the first location begin used
for the stack by the 8051
Special Function
Registers (SFRs)
SFRs provide control and data
exchange with the microcontroller’s
resources and peripherals
Some registers are not bit-addressable.
These include the stack pointer (SP) and
data pointer register (DPTR)
Summary of SFRs
Accumulator (ACC) and B register
ACC (also referred to as A) is used implicitly by several
instructions
B is used implicitly in multiply and divide operations
These registers are the input/output of the arithmetic and
logic unit (ALU)
Program status word - PSW
Shows the status of arithmetic and logical operations using
multiple bits such as Carry
Selects the Register Bank (Bank 0 - Bank 3)
Stack pointer - SP
…
Data pointer - DPTR (DPH and DPL)
16-bit register used to access external code or data
memory
Timer Registers - TH0, TL0, TH1, TL1, TMOD, TCON
Used for timing intervals or counting events
Parallel I/O Port Registers - P0, P1, P2 and P3
Serial Communication Registers- SBUF and SCON
Interrupt Management Registers - IP and IE
Power Control Register - PCON
ANY Questions
THE END
Important to know: Comparison with microprocessor - 8051 architecture -
Criteria of selection - Registers in 8051
Basic C
Programming
Language (recap)
Lecture: 3 hours
ReCAP
C – Loop Control
C – Basic Program Statements
C – Data Types C – Case Control
Statements
C – Constant & C – Array & String
Variable C – Pointer & Function
C – Operators and C – Arithmetic Functions
Expressions
C – Decision Control
Statement
http://fresh2refresh.com/c-programming/
C – Basic Program
Basic Structure of C Program
Structure of C program is defined by set of rules called protocol, to
be followed by programmer while writing C program. All C
programs are having sections/parts which are mentioned below.
Documentation section
Link Section
Definition Section
Global declaration section
Function prototype declaration section
Main function
User defined function definition section
Example :
/* C basic structure program Documentation section
Author: fresh2refresh.com
Date : 01/01/2012
*/
#include <stdio.h> /* Link section */
int total = 0; /* Global declaration and definition section */
int sum (int, int); /* Function declaration section */
int main () { /* Main function */
printf (“This is a C basic program \n”);
total = sum (1, 1);
printf (“Sum of two numbers : %d \n”, total);
return 0;
}
int sum (int a, int b) { /* User defined function */
return a + b;
}
OUTPUT:
This is a C basic program
Sum of two numbers : 2
C – Data Types
C data types are defined as the data storage format
that a variable can store a data to perform a specific
operation.
Data types are used to define a variable before to use
in a program.
Size of variable, constant and array are determined by
data types.
Types Data Types
1 Basic data types int, char, float, double
2 Enumeration data type enum
3 Derived data type pointer, array, structure, union
4 Void data type void
C – Constant
C Constants are also like normal variables. But, only difference
is, their values can not be modified by the program once they
are defined.
Constants refer to fixed values. They are also called as literals
Constants may be belonging to any of the data type.
Syntax:
const data_type variable_name;
(or)
const data_type *variable_name;
C – Variable
C variable is a named location in a memory where a
program can manipulate the data. This location is
used to hold the value of the variable.
The value of the C variable may get change in the
program.
C variable might be belonging to any of the data
type like int, float, char etc.
C – Operators and
Expressions
The symbols which are used to perform logical and
mathematical operations in a C program are called C
operators.
These C operators join individual constants and variables to
form expressions.
Operators, functions, constants and variables are combined
together to form expressions.
Consider the expression A + B * 5. where, +, * are operators, A,
B are variables, 5 is constant and A + B * 5 is an expression.
Types of C Operators:
Arithmetic operators
These are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus
Assignment operators
These are used to assign the values for the variables in C programs.
Relational operators
These operators are used to compare the value of two variables.
Logical operators
These operators are used to perform logical operations on the
given two variables.
…
Bit wise operators
These operators are used to perform bit operations on
given two variables.
Conditional operators (ternary operators)
Conditional operators return one value if condition is true
and returns another value is condition is false.
Increment/decrement operators
These operators are used to either increase or decrease
the value of the variable by one.
Special operators
&, *, sizeof( ) and ternary operators.
C – Decision Control
Statement
In decision control statements (C if else and nested if),
group of statements are executed when condition is
true. If condition is false, then else part statements are
executed.
There are 3 types of decision making control
statements in C language. They are,
if statements
if else statements
nested if statements
C – Loop Control Statements
Loop control statements in C are used to perform
looping operations until the given condition is true.
Control comes out of the loop statements once
condition becomes false.
There are 3 types of loop control statements in C
language. They are,
for
while
do-while
C – Case Control Statements
The statements which are used to execute only
specific block of statements in a series of blocks are
called case control statements.
There are 4 types of case control statements in C
language. They are,
switch
break
continue
goto
C – Array
C Array is a collection of variables belongings to the
same data type. You can store group of data of same
data type in an array.
Array might be belonging to any of the data types
Array size must be a constant value.
Always, contiguous (adjacent) memory locations are
used to store array elements in memory.
It is a best practice to initialize an array to zero or null
while declaring, if we don’t assign any values to array.
…
There are 2 types of C arrays. They are,
One dimensional array
Multi dimensional array
Two dimensional array
Three dimensional array, four dimensional array etc…
Eg:
int a[10]; // integer array
char b[10]; // character array i.e. string
int array[2][2] = {10,20,30,40}; //2D array
C – String
C Strings are nothing but array of characters ended
with null character (‘\0’).
This null character indicates the end of the string.
Strings are always enclosed by double quotes.
Whereas, character is enclosed by single quotes in C.
Example:
char string[20] = { ‘f’ , ’r’ , ‘e’ , ‘s’ , ‘h’ , ‘2’ , ‘r’ , ‘e’ , ‘f’ , ’r’ , ‘e’ , ‘s’
, ‘h’ , ‘\0’};
(or)
char string[20] = “fresh2refresh”;
(or)
char string [] = “fresh2refresh”;
Difference between above declarations are, when we
declare char as “string[20]”, 20 bytes of memory space is
allocated for holding the string value.
When we declare char as “string[ ]”, memory space will
be allocated as per the requirement during execution of
the program.
C – Pointer & Function
C Pointer is a variable that stores/points the address of another
variable. C Pointer is used to allocate memory dynamically i.e.
at run time. The pointer variable might be belonging to any of
the data type such as int, float, char, double, short etc.
Syntax :
data_type *var_name;
Example : int *p; char *p;
Where, * is used to denote that “p” is pointer variable and not a
normal variable.
…
C functions are basic building blocks in a
program. All C programs are written using
functions to improve re-usability,
understandability and to keep track on them.
A large C program is divided into basic building
blocks called C function. C function contains set
of instructions enclosed by “{ }” which performs
specific operation in a C program. Actually,
Collection of these functions creates a C
program.
…
There are 3 aspects in each C function. They are,
Function declaration or prototype – This informs
compiler about the function name, function
parameters and return value’s data type.
Function call – This calls the actual function
Function definition – This contains all the statements to
be executed.
…
C – Arithmetic Functions
C functions which are used to perform
mathematical operations in a program are
called Arithmetic functions.
Example: abs(), floor(), round(), ceil(), sqrt(),
exp(), log(), sin(), cos(), tan(), pow() and trunc()
functions
“math.h” and “stdlib.h” header files support all
the arithmetic functions in C language.
Self-test
Self-test
Self-test
Self-test
Self-test
Self-test
“
ANY Questions
”
THE END
Important to know: C – Syntax - Create function - Compile -
Execute
C Programming in
8051
Lecture: 3 hours
Assembly Code C Code
Code
.asm .c
Generation
Flow Assembler Compiler
Object Code Object Code
For our course:
SDCC - Small Linker
Device C Compiler
Machine Code
.hex
Why Program 8051 in C?
Compilers produce hex files that is downloaded to ROM of
microcontroller
The size of hex file is the main concern
Microcontrollers have limited on-chip ROM
Code space for 8051 is limited to 64K bytes
C programming is less time consuming, but has larger hex file size
The reasons for writing programs in C
It is easier and less time consuming to write in C than Assembly
C is easier to modify and update
You can use code available in function libraries
C code is portable to other microcontroller with little of no
modification
Data Type
A good understanding of C data types for 8051
can help programmers to create smaller hex
files
Unsigned char
Signed char
Unsigned int
Signed int
Sbit (single bit)
Bit and sfr
Unsigned char
The character data type is the most natural
choice
8051 is an 8-bit microcontroller
Unsigned char is an 8-bit data type in the
range of 0 – 255 (00 – FFH)
One of the most widely used data types for the 8051
Counter value
ASCII characters
C compilers use the signed char as the default
if we do not put the keyword unsigned
1. Write an 8051 C program to send values 00 – FF to port P1.
Solution:
Eg:
#include <8051.h> 1. Pay careful attention to
void main(void){ the size of the data
unsigned char z; 2. Try to use unsigned char
for (z=0;z<=255;z++) instead of int if possible
P1 = z;
}
2. Write an 8051 C program to send hex values for ASCII
characters of
0, 1, 2, 3, 4, 5, A, B, C, and D to port P1.
Solution:
#include <8051.h>
void main(void){
unsigned char mynum[]="012345ABCD";
unsigned char z;
for (z=0;z<=10;z++)
P1 = mynum[z];
}
Eg:
3. Write an 8051 C program to toggle all the bits of P1
continuously.
Solution:
//Toggle P1 forever
#include <8051.h>
void main(void){
for (;;){
P1 = 0x55;
P1 = 0xAA;
}
}
Signed char
The signed char is an 8-bit data type
Use the MSB D7 to represent – or +
Give us values from –128 to +127
We should stick with the unsigned char
unless the data needs to be represented as
signed numbers
temperature
Eg:
4. Write an 8051 C program to send values of –4 to +4 to
port P1.
Solution:
//Singed numbers
#include <8051.h>
void main(void){
char mynum[] = {+1,-1,+2,-2,+3,-3,+4,-4};
unsigned char z;
for (z=0;z<=8;z++)
P1 = mynum[z];
}
Unsigned and Signed int
The unsigned int is a 16-bit data type
Takes a value in the range of 0 to 65535 (0000 - FFFFH)
Define 16-bit variables such as memory addresses
Set counter values of more than 256
Since registers and memory accesses are in 8-bit
chunks, the misuse of int variables will result in a larger
hex file
Signed int is a 16-bit data type
Use the MSB D15 to represent – or +
We have 15 bits for the magnitude of the number from -
32768 to +32767
Eg:
5. Write an 8051 C program to toggle bit D0 of the port P1
(P1.0) 50,000 times.
Solution:
sbit keyword allows access
#include <8051.h> to the single bits of the SFR
__sbit __at (0x90) MYBIT; registers
void main(void){
unsigned int z;
for (z=0;z<=50000;z++){
MYBIT = 0;
MYBIT = 1;
//or /* BIT Register- P1 */
//P1_0 = 0; //__sbit __at (0x90) P1_0 ;
//P1_0 = 1; //__sbit __at (0x91) P1_1 ;
} //__sbit __at (0x92) P1_2 ;
} //__sbit __at (0x93) P1_3 ;
…
Bit and sfr
The bit data type allows access to single bits of
bit-addressable memory spaces 20 – 2FH
To access the byte-size SFR registers, we use
the sfr data type
Logical Operators in C
Bit-wise Operators in C
Logical operators
AND (&&), OR (||), and NOT (!)
Bit-wise operators
AND (&), OR (|), EX-OR (^), Inverter (~), Shift
Right (>>), and Shift Left (<<)
These operators are widely used in software
engineering for embedded systems and
control
…
Eg:
6. Run the following program on your simulator and examine
the results.
Solution:
#include <8051.h>
void main(void){
P0 = 0x35 & 0x0F; //ANDing
P1 = 0x04 | 0x68; //ORing
P2 = 0x54 ^ 0x78; //XORing
P0 = ~0x55; //inversing
P1 = 0x9A >> 3; //shifting right 3
P2 = 0x77 >> 4; //shifting right 4
P0 = 0x6 << 4; //shifting left 4
}
Eg:
7. Write an 8051 C program to toggle all the bits of P0 and P2
continuously with a 250ms delay. Using the inverting and
Ex-OR operators, respectively.
Solution:
#include <8051.h>
void MSDelay(unsigned int); …
void main(void){ void MSDelay(unsigned int
P0 = 0x55; itime){
P2 = 0x55; unsigned int i,j;
while (1){ for (i=0;i<itime;i++)
P0 = ~P0; for (j=0;j<1275;j++);
P2 = P2^0xFF; }
MSDelay(250);
}
}
Eg:
8. Write an 8051 C program to get bit P1.0 and send it to P2.7
after inverting it.
Solution:
#include <8051.h>
__bit membit;
void main(void){
while (1){
membit = P1_0; //get a bit from P1.0
P2_7 = ~membit; //invert it and send
//it to P2.7
}
}
Eg:
9. Write an 8051 C program to read the P1.0 and P1.1 bits and
issue an ASCII character to P0 according to the following
table.
P1.1 P1.0
0 0 send ‘0’ to P0
0 1 send ‘1’ to P0
1 0 send ‘2’ to P0
1 1 send ‘3’ to P0
Solution:
#include <8051.h>
void main(void){
unsigned char z;
z = P1;
z = z&0x3;
…
…
…
switch (z) {
case(0): {
P0=‘0’;
break;
}
case(1): {
P0=‘1’;
break;
}
case(2): {
P0=‘2’;
break;
}
case(3): {
P0=‘3’;
break;
}
}
}
Packed BCD to ASCII
Conversion
BCD AND ASCII APPLICATION PROGRAMS
BCD Numbers
As stated there, many newer microcontrollers
have a real-time clock (RTC) where the time
and date are kept even when the power is off.
However this data is provided in packed BCD
To be displayed on an LCD or printed by the printer, it
must be in ACSII format
BCD Number System
The binary representation of the digits 0 to 9
is called BCD (Binary Coded Decimal)
Unpacked BCD
In unpacked BCD, the lower 4 bits of the number
represent the BCD number, and the rest of the
bits are 0
Eg: 00001001 and 00000101 are unpacked BCD
for 9 and 5
…
Packed BCD
In packed BCD, a single byte has two BCD
number in it, one in the lower 4 bits, and one in
the upper 4 bits
Eg: 0101 1001 is packed BCD for 59H
Self-Study: BCD CALCULATION!
ASCII Numbers
On ASCII keyboards, when the key “0″ is
activated, “011 0000″ (30H) is provided to the
computer. Similarly, 31H (011 0001) is provided
for the key “1″, and so on
ASCII Table
ASCII to Packed BCD
Conversion
To convert ASCII to packed BCD
It is first converted to unpacked BCD
(to get rid of the 3)
Combined to make packed BCD
Eg:
10. Write an 8051 C program to convert packed BCD 0x29 to
ASCII and display the bytes on P1 and P2.
Solution:
#include <8051.h>
void main(void){
unsigned char x,y;
unsigned char mybyte = 0x29;
x = mybyte & 0x0F;
P1= x | 0x30;
y = mybyte & 0xF0;
y = y >> 4;
P2= y | 0x30;
}
Eg:
11. Write an 8051 C program to convert ASCII digits of ‘4’ and
‘7’ to packed BCD and display them on P1.
Solution:
#include <8051.h>
void main(void){
unsigned char bcdbyte;
unsigned char w =‘4’;
unsigned char z =‘7’;
w = w & 0x0F;
w = w << 4;
z = z & 0x0F;
bcdbyte = w | z;
P1= bcdbyte;
}
Checksum Byte in ROM
BCD AND ASCII APPLICATION PROGRAMS
Checksum Byte in ROM
To ensure the integrity of the ROM contents,
every system must perform the checksum
calculation
The process of checksum will detect any
corruption of the contents of ROM
The checksum process uses what is called a
checksum byte
The checksum byte is an extra byte that is tagged to
the end of series of bytes of data
…
To calculate the checksum byte of a series of
bytes of data
Add the bytes together and drop the carries
Take the 2’s complement of the total sum, and it
becomes the last byte of the series
To perform the checksum operation, add all
the bytes, including the checksum byte
The result must be zero
If it is not zero, one or more bytes of data have been
changed
Eg:
Assume that we have 4 bytes of hexadecimal data: 25H, 62H,
3FH, and 52H.(a) Find the checksum byte, (b) perform the
checksum operation to ensure data integrity, and (c) if the
second byte 62H has been changed to 22H, show how
checksum detects the error.
Solution:
(a) Find the checksum byte.
25H The checksum is calculated by first adding the
+ 62H bytes. The sum is 118H, and dropping the
+ 3FH carry, we get 18H. The checksum byte is the
+ 52H 2’s complement of 18H, which is E8H.
118H
…
…
(b) Perform the checksum operation to ensure data integrity.
25H
+ 62H Adding the series of bytes including the
+ 3FH checksum byte must result in zero. This
+ 52H indicates that all the bytes are unchanged
+ E8H and no byte is corrupted.
200H (dropping the carries)
(c) If the second byte 62H has been changed to 22H, show
how checksum detects the error.
25H
+ 22H Adding the series of bytes including the
+ 3FH checksum byte shows that the result is not
+ 52H zero, which indicates that one or more bytes
+ E8H have been corrupted.
1C0H (dropping the carry, we get C0H)
Eg:
12. Write an 8051 C program to calculate the checksum byte
for the data 25H, 62H, 3FH, and 52H.
Solution:
#include <8051.h>
void main(void){
unsigned char mydata[]= {0x25,0x62,0x3F,0x52};
unsigned char sum = 0;
unsigned char x;
unsigned char chksumbyte;
for (x=0;x<4;x++){
P2 = mydata[x];
sum= sum + mydata[x];
P1 = sum;
}
chksumbyte = ~sum + 1;
P1 = chksumbyte;
}
Eg:
13. Write an 8051 C program to perform the checksum operation
to ensure data integrity. If data is good, send ASCII character ‘G’
to P0. Otherwise send ‘B’ to P0.
Solution:
#include <8051.h>
void main(void){
unsigned char mydata[]={0x25,0x62,0x3F,0x52,0xE8};
unsigned char chksum = 0;
unsigned char x;
For (x=0;x<5;x++)
chksum = chksum + mydata[x];
if (chksum == 0)
P0='G';
else
P0='B';
}
Binary (hex) to Decimal
and ASCII Conversion
BCD AND ASCII APPLICATION PROGRAMS
Binary (hex) to Decimal
and ASCII Conversion
Many ADC (analog-to-digital converter)
chips provide output data in binary (hex)
To display the data on an LCD or PC screen,
we need to convert it to ASCII
Convert 8-bit binary (hex) data to decimal digits,
000 – 255
Convert the decimal digits to ASCII digits, 30H –
39H
Eg:
14. Write an 8051 C program to convert 11111101 (FD hex) to
decimal and display the digits on P0, P1 and P2.
Solution:
#include <8051.h>
void main(void){
unsigned char x,binbyte,d1,d2,d3;
binbyte = 0xFD;
x = binbyte / 10;
d1 = binbyte % 10;
d2 = x % 10;
d3 = x / 10;
P0 = d1;
P1 = d2;
P2 = d3;
}
RAM Data Space Usage
by 8051 C Compiler
The 8051 C compiler allocates RAM
locations
Bank 0 – addresses 0 – 7
Individual variables – addresses 08 and beyond
Array elements – addresses right after variables
Array elements need contiguous RAM locations and
that limits the size of the array due to the fact that
we have only 128 bytes of RAM for everything
Stack – addresses right after array elements
RAM Space
15. Compile and single-step the following program on your
8051 simulator. Examine the contents of the 128-byte RAM
space to locate the ASCII values.
Solution:
#include <8051.h>
void main(void){
unsigned char mynum[] = "ABCDEF"; //RAM space
unsigned char z;
for (z=0;z<=6;z++)
P1 = mynum[z];
}
RAM Space
16. Write, compile and single-step the following program on
your 8051 simulator. Examine the contents of the code space
to locate the values.
Solution:
#include <8051.h>
void main(void){
unsigned char mydata[100]; //RAM space
unsigned char x,z=0;
for (x=0;x<100;x++){
z--;
mydata[x] = z;
P1 = z;
}
}
Eg:
17. Compile and single-step the following program on your
8051 simulator. Examine the contents of the code space to
locate the ASCII values.
Solution:
#include <8051.h>
void main(void){
static __code unsigned char mynum[]="ABCDEF";
unsigned char z; To make the C compiler use the
for (z=0;z<=6;z++){ code space instead of the RAM
P1 = mynum[z]; space, we need to put the
} keyword code in front of the
} variable declaration
Eg:
18. Compare and contrast the following programs and
discuss the advantages and disadvantages of each one.
Solution:
(a)
#include <8051.h>
void main(void){
P1 =‘H’;
P1 =‘E’;
Short and simple, but the
P1 =‘L’;
individual characters are
P1 =‘L’;
embedded into the program
P1 =‘O’;
and it mixes the code and data
}
together
… Use the RAM data space to store
array elements, therefore the
(b) size of the array is limited
#include <8051.h>
void main(void){
unsigned char mydata[]=“HELLO”;
unsigned char z;
for (z=0;z<=5;z++)
P1 = mydata[z];
} Use a separate area of the code
space for data. This allows the size of
(c) the array to be as long as you want if
#include <8051.h> you have the on-chip ROM.
void main(void){
static __code unsigned char mydata[]=“HELLO”;
unsigned char z;
for (z=0;z<=5;z++)
P1 = mydata[z]; However, the more code space
} you use for data, the less space
is left for your program code.
ANY Questions
THE END
Important to know: Code 8051 using C - Data type - Logical operators -
BCD to ASCII conversion