[go: up one dir, main page]

0% found this document useful (0 votes)
37 views390 pages

Chapter 4

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 390

Microprocessors

and Microcontrollers
Ali Parsayan
ali.parsayan@freeuni.edu.ge
1
Chapter 4
Intel MCS-51
Microcontrollers Family

2
Outline

• 4.1 MCS-51 Family Microcontrollers Structure


• 4.2 MCS-51 Family Programming Assembly Language
• 4.3 MCS-51 Family Microcontrollers Interrupts
• 4.4 MCS-51 Family Timers/Counters
• 4.5 MCS-51 Family Microcontrollers Serial Communication
• 4.6 MCS-51 Family Microcontrollers I/O
• 4.7 C Compilers for MCS-51Family Microcontrollers

3
MCS-51Family
Microcontrollers Structure

4
MCS-51 Family Members
• 89xx
o 8951
o 8952
o 8953
o 8955
o 898252
o 891051
o 892051
• Example (AT89C51, AT89LV51, AT89S51)
o AT= ATMEL(Manufacture)
o C = CMOS technology
o LV= Low Power(3.0v)
• Used program memory type
o 8031 no ROM
o 80xx mask ROM
o 87xx EPROM
o 89xx Flash EEPROM
5
MCS-51 Family Members

89XX ROM RAM Timer Int IO pin Other


Source
8951 4k 128 2 6 32 -

8952 8k 256 3 8 32 -

8953 12k 256 3 9 32 WD

8955 20k 256 3 8 32 WD

898252 8k 256 3 9 32 ISP

891051 1k 64 1 3 16 AC

892051 2k 128 2 6 16 AC

WD: Watch Dog Timer


AC: Analog Comparator
ISP: In System Programable 6
8051 Basic Component
• 4K bytes internal ROM
• 128 bytes internal RAM
• Four 8-bit I/O ports (P0 - P3).
• Two 16-bit timers/counters
• One serial interface

CPU RAM ROM


A single chip
Serial Microcontroller
I/O
Timer COM
Port
Port
7
8051 Block Diagram
External Interrupts

Interrupt 4k 128 bytes Timer 1


Control ROM RAM Timer 2

CPU

OSC Bus
4 I/O Ports Serial
Control

P0 P2 P1 P3 TXD RXD
8
Other 8051 featurs
• only 1 on chip oscillator (external crystal)
• 6 interrupt sources
o 2 external , 3 internal, 1 reset

• 64K external code (program) memory


o only read by PSEN

• 64K external data memory


o can be read and write by RD,WR

• Code memory is selectable by EA


o internal or external
9
8051 Internal Block Diagram 10
8051 Pin out

11
8051 Foot Print
P1.0 1 40 Vcc
P1.1 2 39 P0.0(AD0)
P1.2 3 38 P0.1(AD1)
P1.3 4 37 P0.2(AD2)
P1.4 5 36 P0.3(AD3)
P1.5 6 35 P0.4(AD4)
P1.6 7 34 P0.5(AD5)
P1.7 8 8051 33 P0.6(AD6)
RST 9 32 P0.7(AD7)
(8031)
(RXD)P3.0 10 31 EA/VPP
(TXD)P3.1
(8751) ALE/PROG
11 30
(INT0)P3.2 12 (8951) 29 PSEN
(INT1)P3.3 13 28 P2.7(A15)
(T0)P3.4 14 27 P2.6(A14)
(T1)P3.5 15 26 P2.5(A13)
(WR)P3.6 16 25 P2.4(A12)
(RD)P3.7 17 24 P2.3(A11)
XTAL2 18 23 P2.2(A10)
XTAL1 19 22 P2.1(A9)
GND 20 21 P2.0(A8)
12
Power Supply and Clock Pins
• Vcc(pin 40):
o Vcc provides supply voltage to the chip.
o The voltage source is +5V.
• GND(pin 20):ground
• XTAL1 and XTAL2(pins 19,18):
o These 2 pins provide external clock.
➢ using a quartz crystal oscillator
➢ using a TTL oscillator

13
External Memory and Serial I/O PINS

• PSEN (out):
o Program Store Enable, the read signal for external program
memory (active low).
• ALE (out):
o Address Latch Enable, to latch address outputs at Port0 and
Port2
• EA (in):
o External Access Enable, active low to access external program
memory locations 0 to 64K
• RXD,TXD:
o UART pins for serial I/O on Port 3
14
Reset Pin
• RST(pin 9):reset
o input pin and active high(normally low).
➢The high pulse must be high at least 2
machine cycles.
opower-on reset.
➢Upon applying a high pulse to RST, the
microcontroller will reset and all values in registers
will be lost.
➢Reset values of some 8051 registers
15
I/O Ports Pins

• One of the most useful features of the 8051 is that it


contains four I/O ports (P0 - P3)
• Port 0 (pins 32-39):P0(P0.0~P0.7)
o 8-bit R/W - General Purpose I/O
o Or acts as a multiplexed low byte address and data bus for external
memory design
• Port 1 (pins 1-8) :P1(P1.0~P1.7)
o Only 8-bit R/W - General Purpose I/O
• Port 2 (pins 21-28):P2(P2.0~P2.7)
o 8-bit R/W - General Purpose I/O
o Or high byte of the address bus for external memory design
• Port 3 (pins 10-17):P3(P3.0~P3.7)
o General Purpose I/O
o if not using any of the internal peripherals (timers) or external interrupts.
• Each port can be used as input or output (bi-direction)
16
Hardware Structure of I/O Pins
• Each pin of I/O ports
o Internally connected to CPU bus
o A D latch store the value of this pin
➢Write to latch=1:write data into the D latch
o 2 Tri-state buffer:
➢TB1: controlled by “Read pin”
✓Read pin=1:really read the data present at the pin
➢TB2: controlled by “Read latch”
✓Read latch=1:read value from internal latch
o A transistor M1 gate
➢Gate=0: open
➢Gate=1: close
17
Hardware Structure of I/O Pins

Read latch Vcc


TB2
Load(L1)

Internal CPU D Q P1.X


bus P1.X pin

Write to Clk Q M1
latch

TB1
Read pin

18
Writing “1” to an Output Pin

Read latch Vcc


TB2
Load(L1) 2. output pin
1. write a 1 to the pin is Vcc
D Q
1 P1.X
Internal CPU
bus P1.X pin
0 output 1
Write to Clk Q M1
latch

TB1
Read pin

19
Writing “0” to an Output Pin

Read latch Vcc


TB2
Load(L1) 2. output pin
1. write a 0 to the pin is ground
D Q
0 P1.X
Internal CPU
bus P1.X pin
1 output 0
Write to Clk Q M1
latch

TB1
Read pin

20
Reading “High” at an Input Pin

Read latch Vcc 2. MOV A,P1


TB2 external pin=High
1. write a 1 to the pin MOV Load(L1)
P1,#0FFH

1 1 P1.X pin
Internal CPU D Q
bus
P1.X
0 M1
Write to latch Clk Q

TB1
Read pin
3. Read pin=1 Read
latch=0 Write to latch=1

21
Reading “Low” at an Input Pin

Read latch Vcc


2. MOV A,P1
TB2
1. write a 1 to the pin Load(L1) external pin=Low
MOV P1,#0FFH
1 0 P1.X pin
Internal CPU D Q
bus
P1.X
0 M1
Write to latch Clk Q

TB1
Read pin
3. Read pin=1 Read
latch=0 Write to latch=1

22
I/O Port 3 Alternate Functions

23
I/O Port 3: Bit Latches and I/O Buffers

24
Port 0 Need to Pull-Up Resistors
Vcc
10 K

P0.0
DS5000 P0.1

Port
8751 P0.2
8951 P0.3
P0.4 0
P0.5
P0.6
P0.7

25
XTAL Connection to 8051
• Using a quartz crystal oscillator
• We can observe the frequency on the XTAL2 pin.
C2
XTAL2
30pF

C1
XTAL1
30pF

GND

26
XTAL Connection
to an External Clock Source
• Using a TTL oscillator
• XTAL2 is unconnected.

N XTAL2
C

EXTERNAL
OSCILLATOR
SIGNAL XTAL1

GND

27
Machine cycle
• Find the machine cycle for:
o (a) XTAL = 11.0592 MHz
o (b) XTAL = 16 MHz.
• Solution:
o (a) 11.0592 MHz / 12 = 921.6 kHz;
➢ machine cycle = 1 / 921.6 kHz = 1.085 s
o (b) 16 MHz / 12 = 1.333 MHz;
➢ machine cycle = 1 / 1.333 MHz = 0.75 s

28
Power-On RESET
Vcc

31
EA/VPP
X1
10 uF 30 pF

X2
RST
9
8.2 K

29
RESET Value of Some 8051 Registers:

Register Reset Value


PC 0000
ACC 0000
B 0000
PSW 0000
SP 0007
DPTR 0000
RAM are all zero
On-Chip Memory: Internal RAM

31
Registers
1F

Bank 3 Four Register Banks


Each bank has R0-R7
18 Selectable by psw.2,3
17

Bank 2

10
0F

Bank 1

08
07 R7
06 R6
05 R5
04
03
R4
R3
Bank 0
02 R2
01 R1
00 R0
32
Bit Addressable Memory
2F 7F 78 20h – 2Fh
2E (16 locations X 8-bits = 128 bits)
2D
2C Bit addressing:
2B mov C, 1Ah
2A or
29 mov C, 23h.2
28
27
26
25
24
23 1A

22 10

21 0F 08

20 07 06 05 04 03 02 01 00
33
Special Function Registers

• DATA registers
• CONTROL registers
o Timers
o Serial ports
o Interrupt system
o Analog to Digital converter
o Digital to Analog converter
o Etc. Addresses 80h – FFh
Direct Addressing used to access
SPRs

34
Bit Addressable RAM

Summary of the
8051
on-chip data
memory
(RAM)

35
Bit Addressable RAM

Summary of
the 8051
on-chip data
memory
(Special
Function
Registers)

36
37
38
8051 CPU Registers

• A (Accumulator)
• B
• PSW (Program Status Word)
• SP (Stack Pointer)
• PC (Program Counter)
• DPTR (Data Pointer)

Used in assembler
instructions

39
Registers
A

R0
DPTR DPH DPL
R1

R2
PC PC
R3

R4 Some 8051 16-bit Register


R5

R6

R7

Some 8-bit Registers of the


8051
40
External Memory
• EA(pin 31 - active low ):external access
o There is no on-chip ROM in 8031 and 8032 .
o The EA pin is connected to GND to indicate the
code is stored externally.
o PSEN & ALE are used for external ROM.
o For 8051, EA pin is connected to Vcc.
• PSEN(pin 29 - active low ):program store
enable
o This is an output pin and is connected to the
OE pin of the ROM. 41
External Memory
• ALE(pin 30):address latch enable
oIt is an output pin and is active high.
o8051 port 0 provides both address and
data.
oThe ALE pin is used for de-multiplexing
the address and data by connecting to the
G pin of the 74LS373 latch.
42
Address Multiplexing
for External Memory

Multiplexing
the address
(low-byte)
and data bus

43
Address Multiplexing
for External Memory

Accessing
external
code
memory

44
45
Accessing External Data Memory

Interface
to 1K
RAM

46
Timing for MOVX instruction

47
External code memory
WR
RD
PSEN OE
ALE 74LS373 CS
G
P0.0 A0
D
P0.7 A7

D0
D7
EA
P2.0 A8
P2.7 A15

8051 ROM
48
External data memory
WR WR
RD RD
PSEN
ALE 74LS373 CS
G
P0.0 A0
D
P0.7 A7

D0
D7
EA
P2.0 A8
P2.7 A15

8051 RAM
49
Overlapping External Code
and Data Spaces

50
Overlapping External Code
and Data Spaces
WR WR
RD
PSEN RD
ALE 74LS373 CS
G
P0.0 A0
D
P0.7 A7

D0
D7
EA
P2.0 A8
P2.7 A15

8051 RAM
51
Overlapping External Code
and Data Spaces
• Allows the RAM to be
o written as data memory, and
o read as data memory as well as code memory.
• This allows a program to be
o downloaded from outside into the RAM as
data, and
o executed from RAM as code. 52
53
MAX232 Dual
RS-232 Drivers
and Receivers

IC Memory SRAM 6264 64K


54
MCS-51Family
Programming
Assembly Language

55
MCS-51 Programming
Assembly Language
• Data Transfer Instructions
• Addressing Modes
• Arithmetic and Logic Instructions
• Program Flow (Control) Instructions

56
Data Transfer Instructions
• MOV dest, source
o dest  source
• Stack instructions
o PUSH byte ;increment stack pointer and move a byte to
stack
o POP byte ;move from stack to a byte and decrement
stack pointer

• Exchange instructions
o XCH a, byte ;exchange accumulator and byte
o XCHD a, byte ;exchange low nibbles of accumulator and byte
57
Addressing Modes
• Immediate Mode – specify data by its value
omov A, #0
➢ ;put 0 in the accumulator
➢ ;A = 00000000

omov R4, #11h


➢ ;put 11hex in the R4 register
➢ ;R4 = 00010001

omov B, #11
➢ ;put 11 decimal in b register
➢ ;B = 00001011

omov DPTR,#7521h
➢ ;put 7521 hex in DPTR
➢ ;DPTR = 0111010100100001

58
Addressing Modes
• Immediate Mode – continue
o MOV DPTR,#7521h
o MOV DPL,#21H
o MOV DPH, #75

o COUNT EQU 30
o ~
o ~
o mov R4, #COUNT

o MOV DPTR,#MYDATA
o ~
o ~
o 0RG 200H
o MYDATA:DB “ABCD” 59
Addressing Modes
• Register Addressing – either source or destination
is one of the CPU registers
o MOV R0,A
o MOV A,R7
o ADD A,R4
o ADD A,R7
o MOV DPTR,#25F5H
o MOV R5,DPL
o MOV R,DPH
o MOV R4,R7 is incorrect
60
Addressing Modes
• Direct Mode – specify data by its 8-bit address
Usually for 30h-7Fh of RAM
o Mov a, 70h
➢ copy contents of RAM at 70h to a
o Mov R0,40h
➢ copy contents of RAM at 40h to a
o Mov 56h,a
➢ put contents of a at 56h
o Mov 0D0h,a
➢ put contents of a into PSW
Addressing Modes
• Direct Mode – play with R0-R7 by direct
address
o MOV A,4  MOV A,R4
o MOV A,7  MOV A,R7
o MOV 7,2  MOV R7,R6
o MOV R2,#5 ;Put 5 decimal at R2
o MOV R2,5h ;Put content of RAM at 5 (address) in R2
Addressing Modes
• Register Indirect – the address of the source or
destination is specified in registers
o Uses registers R0 or R1 for 8-bit address:
➢ mov psw, #0 ; use register bank 0
➢ mov r0, #0x3C
➢ mov @r0, #3 ; memory at 3C gets #3
➢ ; M[3C]  3
o Uses DPTR register for 16-bit addresses:
➢ mov dptr, #0x9000 ; dptr  9000h
➢ movx a, @dptr ; a  M[9000]
➢ Note that 9000 is an address in external memory
63
Use Register Indirect to access
upper RAM block (+8052)

64
Addressing Modes
• Register Indexed Mode – source or
destination address is the sum of the base
address and the accumulator (Index)
• Base address can be DPTR or PC
omov dptr, #4000h
omov a, #5
omovc a, @a + dptr ;a  M[4005]

65
Addressing Modes
• Register Indexed Mode continue
• Base address can be DPTR or PC
o ORG 1000h
➢1000 mov a, #5
PC ➢ movc a, @a + PC ;a  M[1008]
➢ Nop
• Table Lookup
• MOVC only can read internal code
memory
66
Acc Register
• A register can be accessed by direct and register
modes
• This 3 instruction has same function with different
code
o0703 E500 mov a,00h
o0705 8500E0 mov acc,00h
o0708 8500E0 mov 0e0h,00h
• Also this 3 instruction
o070B E9 mov a,r1
o070C 89E0 mov acc,r1
o070E 89E0 mov 0e0h,r1
67
SFRs Address
• B – always direct mode - except in MUL & DIV
o 0703 8500F0 mov b,00h
o 0706 8500F0 mov 0f0h,00h
o

o 0709 8CF0 mov b,r4


o 070B 8CF0 mov 0f0h,r4
• P0~P3 – are direct address
o 0704 F580 mov p0,a
o 0706 F580 mov 80h,a
o 0708 859080 mov p0,p1
• Also other SFRs (pcon, tmod, psw,….) 68
SFRs Address
• All SFRs such as:
o (ACC, B, PCON, TMOD, PSW, P0~P3, …)
• are accessible by name and direct address.
• But both of them must be coded as direct
address

69
8051 Instruction Format
• immediate addressing
Op code Immediate data

add a,#3dh ;machine code=243d


• Direct addressing
Op code Direct address

mov r3,0E8h ;machine code=ABE8

70
8051 Instruction Format
• Register addressing

Op code n n n

070D E8 mov a,r0 ;E8 = 1110 1000


070E E9 mov a,r1 ;E9 = 1110 1001
070F EA mov a,r2 ;EA = 1110 1010
0710 ED mov a,r5 ;ED = 1110 1101
0711 EF mov a,r7 ;Ef = 1110 1111
0712 2F add a,r7
0713 F8 mov r0,a
0714 F9 mov r1,a
0715 FA mov r2,a
0716 FD mov r5,a
0717 FD mov r5,a
71
8051 Instruction Format
• Register indirect addressing
Op code i
mov a, @Ri ; i = 0 or 1

070D E7 mov a,@r1


070D 93 movc a,@a+dptr
070E 83 movc a,@a+pc
070F E0 movx a,@dptr
0710 F0 movx @dptr,a
0711 F2 movx @r0,a
0712 E3 movx a,@r1
72
8051 Instruction Format
• relative addressing
Op code Relative address
here: sjmp here ;machine code=80FE(FE=-2)
Range = (-128 ~ 127)

• Absolute addressing (limited in 2k current mem block)

A10-A8 Op code A7-A0


0700 1 org 0700h
0700 E106 2 ajmp next ;next=706h
0702 00 3 nop
0703 00 4 nop
0704 00 5 nop
0705 00 6 nop
7 next:
8 end 73
8051 Instruction Format
• Long distance address
Op code A15-A8 A7-A0

Range = (0000h ~ FFFFh)


0700 1 org 0700h
0700 020707 2 ajmp next ;next=0707h
0703 00 3 nop
0704 00 4 nop
0705 00 5 nop
0706 00 6 nop
7 next:
8 end

74
Stack
pop
push

stack pointer

stack

75
Stack
• Stack-oriented data transfer
o Only one operand (direct addressing)
o SP is other operand – register indirect - implied
• Direct addressing mode must be used in Push and Pop
mov sp, #0x40 ; Initialize SP
push 0x55 ; SP  SP+1, M[SP]  M[55]
; M[41]  M[55]
pop b ; b  M[55]

• Note: can only specify RAM or SFRs (direct mode) to


push or pop.
• Therefore, to push/pop the accumulator, must use acc,
not a
76
Stack (push, pop)
• Therefore
Push a ;is invalid
Push r0 ;is invalid
Push r1 ;is invalid
push acc ;is correct
Push psw ;is correct
Push b ;is correct
Push 13h
Push 0
Push 1
Pop 7
Pop 8
Push 0e0h ;acc
Pop 0f0h ;b
77
Exchange Instructions

• two way data transfer


XCH a, 30h ; a → M[30]
XCH a, R0 ; a → R0
XCH a, @R0 ; a → M[R0]
XCHD a, R0 ; exchange “digit”

a[7..4] a[3..0] R0[7..4] R0[3..0]

Only 4 bits exchanged

78
Bit-Oriented Data Transfer
• Transfers between individual bits.
• Carry flag (C) (bit 7 in the PSW) is used as a single-bit
accumulator
• RAM bits in addresses 20-2F are bit addressable
mov C, P0.0

mov C, 67h

mov C, 2ch.7
SFRs that are Bit Addressable
• SFRs with
addresses ending in
0 or 8 are bit-
addressable.
(80, 88, 90, 98, etc)

• Notice that all 4


parallel I/O ports
are bit addressable.
Arithmetic Instructions
• Add
• Subtract
• Increment
• Decrement
• Multiply
• Divide
• Decimal adjust

81
Arithmetic Instructions
Mnemonic Description
ADD A, byte add A to byte, put result in A
ADDC A, byte add with carry
SUBB A, byte subtract with borrow
INC A increment A
INC byte increment byte in memory
INC DPTR increment data pointer
DEC A decrement accumulator
DEC byte decrement byte
MUL AB multiply accumulator by b register
DIV AB divide accumulator by b register
DA A decimal adjust the accumulator
ADD Instructions
• add a, byte: a  a + byte
• addc a, byte: a  a + byte + C
• These instructions affect 3 bits in PSW:
• C = 1 if result of add is greater than FF
• AC = 1 if there is a carry out of bit 3
• OV = 1 if there is a carry out of bit 7, but not from bit 6,
or visa versa.

83
Instructions that Affect PSW bits

84
ADD Examples

mov a, #3Fh • What is the value of the C,


AC, OV flags after the
add a, #D3h
second instruction is
executed?
0011 1111
1101 0011
0001 0010 C=1
AC = 1
OV = 0

85
Signed Addition and Overflow
0111 1111 (positive 127)
0111 0011 (positive 115)
0000 0000 00 0 1111 0010 (overflow cannot
… represent 242 in 8 bits 2’s
complement)
0111 1111 7F 127
1000 0000 80 128 1000 1111 (negative 113)
… 1101 0011 (negative 45)
1111 1111 FF 255 0110 0010 (overflow)

0011 1111 (positive)


1101 0011 (negative)
0001 0010 (never overflows)
86
Addition Example
; Computes Z = X + Y
; Adds values at locations 78h and 79h and puts them in 7Ah
;------------------------------------------------------------------
X equ 78h
Y equ 79h
Z equ 7Ah
;-----------------------------------------------------------------
org 00h
ljmp Main
;-----------------------------------------------------------------
org 100h
Main:
mov a, X
add a, Y
mov Z, a
end
87
The 16-bit ADD example
; Computes Z = X + Y (X,Y,Z are 16 bit)
;------------------------------------------------------------------
X equ 78h
Y equ 7Ah
Z equ 7Ch
;-----------------------------------------------------------------
org 00h
ljmp Main
;-----------------------------------------------------------------
org 100h
Main:
mov a, X
add a, Y
mov Z, a
mov a, X+1
adc a, Y+1
mov Z+1, a
end
88
Subtract

SUBB A, byte subtract with borrow

Example:
SUBB A, #0x4F ;A  A – 4F – C

There is no subtraction WITHOUT borrow.


Therefore, if a subtraction without borrow is desired,
it is necessary to clear the C flag.
Example:
Clr c
SUBB A, #0x4F ;A  A – 4F

89
Increment and Decrement

INC A increment A
INC byte increment byte in memory
INC DPTR increment data pointer
DEC A decrement accumulator
DEC byte decrement byte

• The increment and decrement instructions do NOT affect the C


flag.
• We can only INCREMENT the data pointer, not decrement.

90
Example:
Increment 16-bit Word
• Assume 16-bit word in R3:R2
mov a, r2
add a, #1 ; use add rather than increment to affect C
mov r2, a
mov a, r3
addc a, #0 ; add C to most significant byte
mov r3, a

91
Multiply
• When multiplying two 8-bit numbers, the size of the
maximum product is 16-bits

FF x FF = FE01
(255 x 255 = 65025)

MUL AB ; BA  A * B

B gets the High byte


A gets the Low byte

92
Division

• Integer Division
DIV AB ; divide A by B

A  Quotient(A/B)
B  Remainder(A/B)

OV - used to indicate a divide by zero condition.


C – set to zero
93
Decimal Adjust

• DA a ; decimal adjust a

• Used to facilitate BCD addition.


• Adds “6” to either high or low nibble after an addition
• to create a valid BCD number.

Example:
mov a, #23h
mov b, #29h
add a, b ; a  23h + 29h = 4Ch (wanted 52)
DA a ; a  a + 6 = 52
94
Logic Instructions
• Bitwise logic operations
o (AND, OR, XOR, NOT)
• Clear
• Rotate
• Swap

• Logic instructions do NOT affect the flags in


PSW
95
Bitwise Logic
ANL ➔ AND 00001111
ORL ➔ OR ANL 10101100
00001100
XRL ➔ XOR
CPL ➔ Complement 00001111
ORL 10101100
10101111

00001111
XRL 10101100
10100011

CPL 10101100
01010011

96
Address Modes with Logic

ANL – AND a, byte direct, reg. indirect, immediate


ORL – OR byte, a direct
XRL – eXclusive oR byte, #constant

CPL – Complement a cpl a

97
Uses of Logic Instructions
• Force individual bits low, without affecting other
bits.
anl PSW, #0xE7 ;PSW AND 11100111

• Force individual bits high.


orl PSW, #0x18 ;PSW OR 00011000

• Complement individual bits


xrl P1, #0x40 ;P1 XRL 01000000
98
Other Logic Instructions
• CLR - clear
• RL – rotate left
• RLC – rotate left through Carry
• RR – rotate right
• RRC – rotate right through Carry
• SWAP – swap accumulator nibbles

99
CLR ( Set all bits to 0)
• CLR A
• CLR byte (direct mode)
• CLR Ri (register mode)
• CLR @Ri (register indirect mode)

100
Rotate
• Rotate instructions operate only on acc
RL a
Mov a,#0xF0 ; a 11110000
RL a ; a 11100001

RR a
Mov a,#0xF0 ; a 11110000
RR a ; a 01111000
101
Rotate through Carry
C
RRC a

mov a, #0A9h ; a  A9
add a, #14h ; a  BD (10111101), C0
rrc a ; a  01011110, C1
C
RLC a

mov a, #3ch ; a  3ch(00111100)


setb c ;c1
rlc a ; a  01111001, C1
102
Rotate and Multiplication/Division
• A left shift, is the same as multiplying by 2, and a
right shift is the same as divide by 2

o mov a, #3 ; A 00000011 (3)


o clr C ; C 0
o rlc a ; A 00000110 (6)
o rlc a ; A 00001100 (12)
o rrc a ; A 00000110 (6)

103
Swap
• SWAP a
o mov a, #72h ; a  27h
o swap a ; a  72h

104
Bit Logic Operations
• Some logic operations can be used with single bit
operands
o ANL C, bit
o ORL C, bit
o CLR C
o CLR bit
o CPL C
o CPL bit
o SETB C
o SETB bit

• “bit” can be any of the bit-addressable RAM locations


or SFRs.
105
Program Flow Control
• Unconditional jumps (“go to”)

• Conditional jumps

• Call and return

106
Unconditional Jumps
• SJMP <rel addr> ; Short jump, relative address is 8-bit 2’s
complement number, so jump can be up to 127 locations forward, or 128
locations back.

• LJMP <address 16> ; Long jump


• AJMP <address 11> ; Absolute jump to anywhere within 2K block
of program memory

• JMP @A + DPTR ; Long indexed jump

107
Infinite Loops

Start: mov C, p3.7


mov p1.6, C
sjmp Start

• Microcontroller application programs are almost


always infinite loops!

108
Re-locatable Code
• Memory specific NOT Re-locatable (machine code)
o org 8000h
o Start: mov C, p1.6
o mov p3.7, C
o ljmp Start
o end

• Re-locatable (machine code)


o org 8000h
o Start: mov C, p1.6
o mov p3.7, C
o sjmp Start
o end
109
Jump table
Mov dptr,#jump_table
Mov a,#index_number
Rl a
Jmp @a+dptr
...
Jump_table: ajmp case0
ajmp case1
ajmp case2
ajmp case3
110
Conditional Jump
• These instructions cause a jump to occur only if a
condition is true.
• Otherwise, program execution continues with the next
instruction.
o loop: mov a, P1
o jz loop ; if a = 0, goto loop, % else goto next instruction
o mov b, a
• There is no zero flag (z)
• Content of A checked for zero on time

111
Conditional jumps
Mnemonic Description
JZ <rel addr> Jump if a = 0
JNZ <rel addr> Jump if a != 0
JC <rel addr> Jump if C = 1
JNC <rel addr> Jump if C != 1
JB <bit>, <rel addr> Jump if bit = 1
JNB <bit>,<rel addr> Jump if bit != 1
JBC <bir>, <rel addr> Jump if bit =1, &clear bit
CJNE A, direct, <rel addr> Compare A and memory,
jump if not equal
Example: Conditional Jumps
if (a = 0) is true
send a 0 to LED
else
send a 1 to LED

jz led_off
Setb P1.6
sjmp skipover
led_off: clr P1.6
mov A, P0
skipover:
113
More Conditional Jumps
Mnemonic Description
CJNE A, #data <rel addr> Compare A and data, jump if
not equal
CJNE Rn, #data <rel addr> Compare Rn and data, jump
if not equal
CJNE @Rn, #data <rel Compare Rn and memory,
addr> jump if not equal
DJNZ Rn, <rel addr> Decrement Rn and then jump
if not zero
DJNZ direct, <rel addr> Decrement memory and then
jump if not zero
Iterative Loops
For A = 0 to 4 do For A = 4 to 0 do
{…} {…}

clr a mov R0, #4


loop: ... loop: ...
... ...
inc a djnz R0, loop
cjne a, #4, loop
115
Iterative Loops (examples)
mov a,#50h mov a,#25h
mov b,#00h mov r0,#10h
cjne a,#50h,next mov r2,#5
mov b,#01h Again: mov @ro,a
next: nop inc r0
end djnz r2,again
mov a,#0aah end
mov b,#10h mov a,#0h
Back1: mov r6,#50 mov r4,#12h
Back2: cpl a Back: add a,#05
djnz r6,back2 djnz r4,back
djnz b,back1 mov r5,a
end end 116
Call and Return

• Call is similar to a jump, but


o Call pushes PC on stack before branching

acall <address ll> ; stack  PC


; PC  address 11 bit

lcall <address 16> ; stack  PC


; PC  address 16 bit
117
Return
• Return is also similar to a jump, but
o Return instruction pops PC from stack to get
address to jump to

ret ; PC  stack

118
Subroutines

Main: ...
acall sublabel
call to the subroutine
...
...
sublabel: ...
... the subroutine

ret

119
Initializing Stack Pointer
• SP is initialized to 07 after reset.(Same address as R7)

• With each push operation 1st , pc is increased

• When using subroutines, the stack will be used to store


the PC, so it is very important to initialize the stack
pointer. Location 2Fh is often used.

mov SP, #2Fh


120
Subroutine - Example
square: push b
mov b,a
mul ab
pop b
ret
• 8 byte and 11 machine cycle

square: inc a
movc a,@a+pc
ret
table: db 0,1,4,9,16,25,36,49,64,81

• 13 byte and 5 machine cycle 121


Subroutine – another example
; Program to compute square root of value on Port 3
; (bits 3-0) and output on Port 1.
org 0
ljmp Main reset service
Main: mov P3, #0xFF ; Port 3 is an input
loop: mov a, P3
anl a, #0x0F ; Clear bits 7..4 of A
lcall sqrt main program
mov P1, a
sjmp loop

sqrt: inc a
movc a, @a + PC subroutine
ret

Sqrs: db 0,1,1,1,2,2,2,2,2,3,3,3,3,3,3,3 data


end 122
Why Subroutines?
• Subroutines allow us to have "structured"
assembly language programs.
• This is useful for breaking a large design
into manageable parts.
• It saves code space when subroutines can be
called many times in the same program.

123
example of delay
mov a,#0aah Delay2:
Back1: mov p0,a mov r6,#0ffh
lcall delay1 back1: mov r7,#0ffh ;1cycle
cpl a Here: djnz r7,here ;2cycle
sjmp back1 djnz r6,back1;2cycle
Delay1: mov r0,#0ffh;1cycle ret ;2cycle
Here: djnz r0,here ;2cycle end
ret ;2cycle
end Delay=1+(1+255*2+2)*255+2
=130818 machine cycle
Delay=1+255*2+2=513 cycle

124
Long delay Example
GREEN_LED: equ P1.6
org ooh
ljmp Main reset service
org 100h
Main: clr GREEN_LED
Again: acall Delay
cpl GREEN_LED main program
sjmp Again

Delay: mov R7, #02


Loop1: mov R6, #00h
Loop0: mov R5, #00h
djnz R5, $
djnz R6, Loop0 subroutine
djnz R7, Loop1
ret
END
125
Example
; Move string from code memory to RAM
org 0
mov dptr,#string
mov r0,#10h
Loop1: clr a
movc a,@a+dptr
jz stop
mov @r0,a
inc dptr
inc r0
sjmp loop1
Stop: sjmp stop
; on-chip code memory used for string
org 18h
String: db ‘this is a string’,0
end 126
Example
; p0:input p1:output
mov a,#0ffh
mov p0,a
back: mov a,p0
mov p1,a
sjmp back

setb p1.2
mov a,#45h ;data
Again: jnb p1.2,again ;wait for data request
mov p0,a ;enable strobe
setb p2.3
clr p2.3 127
Example
; duty cycle 50%
back: cpl p1.2
acall delay
sjmp back

back: setb p1.2


acall delay
Clr p1.2
acall delay
sjmp back 128
Example
; duty cycle 66%
back: setb p1.2
acall delay
acall delay
Clr p1.2
acall delay
sjmp back

129
Interrupts

mov a, #2
mov b, #16
mul ab
Program Execution

mov R0, a interrupt


mov R1, b
ISR:
inc r7
mov a, #12
mov a,r7
mov b, #20
jnz NEXT
mul ab
cpl P1.6
add a, R0
NEXT: reti
mov R0, a
return
mov a, R1
addc a, b
mov R1, a
end 130
Interrupt Sources
• 8051 has 5 sources of interrupts
o Timer 0 overflow
o Timer 1 overflow
o External Interrupt 0
o External Interrupt 1
o Serial Port events (buffer full, buffer empty, etc)

• One of enhanced versions has 22 sources


o More timers, programmable counter array, ADC, more
external interrupts, another serial port (UART)

131
Interrupt Process
• If interrupt event occurs AND interrupt flag for
that event is enabled, AND interrupts are
enabled, then:
o Current PC is pushed on stack.
o Program execution continues at the interrupt vector
address for that interrupt.
o When a RETI instruction is encountered, the PC is
popped from the stack and program execution
resumes where it left off.

132
Interrupt Priorities
• What if two interrupt sources interrupt at
the same time?
• The interrupt with the highest PRIORITY
gets serviced first.
• All interrupts have a default priority order.
• Priority can also be set to “high” or “low”.

133
Interrupt SFRs

Interrupt enables for the 5 original 8051


interrupts:
Timer 2
Serial (UART0)
Global Interrupt Timer 1
Enable – must be set External 1
to 1 for any interrupt 1 = Enable Timer 0
to be enabled 0 = Disable External1340
Interrupt Vectors
• Each interrupt has a specific place in code memory
where program execution (interrupt service routine)
begins.
External Interrupt 0: 0003h
Timer 0 overflow: 000Bh
External Interrupt 1: 0013h
Timer 1 overflow: 001Bh
Serial : 0023h
Timer 2 overflow(8052+) 002bh

There are only 8 memory locations between vectors


135
Interrupt Vectors
• To avoid overlapping Interrupt Service routines,
it is common to put JUMP instructions at the
vector address. This is similar to the reset vector.

org 009B ; at EX7 vector


ljmp EX7ISR
cseg at 0x100 ; at Main program
Main: ... ; Main program
...
EX7ISR: ... ; Interrupt service routine
... ; Can go after main program
reti ; and subroutines. 136
Example Interrupt Service Routine
;EX7 ISR to blink the LED 5 times.
;Modifies R0, R5-R7, bank 3.
;----------------------------------------------------
ISRBLK: push PSW ;save state of status word
mov PSW,#18h ;select register bank 3
mov R0, #10 ;initialize counter
Loop2: mov R7, #02h ;delay a while
Loop1: mov R6, #00h
Loop0: mov R5, #00h
djnz R5, $
djnz R6, Loop0
djnz R7, Loop1
cpl P1.6 ;complement LED value
djnz R0, Loop2 ;go on then off 10 times
pop PSW
reti 137
MCS-51 Family
Timers/Counters

138
Timers /Counters Programming
• 2 timers/counters: timer/counter 0 and timer/counter 1.
• They can be used as:
o 1- The timer is used as a time delay generator.
➢The clock source is the internal crystal frequency of the
8051.
o 2- An event counter.
➢ External input from input pin to count the number of
events on registers.
➢ These clock pulses could represent the number of people
passing through an entrance, or the number of wheel
rotations, or any other event that can be converted to
pulses. 139
140
Timer
• Set the initial value of registers
• Start the timer and then the 8051 counts up.
• Input from internal system clock (machine cycle)
• When the registers equal to 0 and the 8051 sets a bit to
denote time out
8051

P2 P1 to
Set LCD
Timer 0 TH0
TL0
141
Counter
• Count the number of events
o Show the number of events on registers
o External input from T0 input pin (P3.4) for Counter 0
o External input from T1 input pin (P3.5) for Counter 1
o External input from Tx input pin.
8051
o We use Tx to denote T0 or T1.
TH0
P1 to
TL0 LCD
P3.4
a switch T0
142
Registers Used in Timer/Counter
• TH0, TL0, TH1, TL1
• TMOD (Timer mode register)
• TCON (Timer control register)
• Since 8052 has 3 timers/counters, the
formats of these control registers are
different.
o T2CON (Timer 2 control register), TH2 and
TL2 used for 8052 only.
143
Basic Registers of the Timer
• Both timer 0 and timer 1 are 16 bits wide.
o These registers stores
➢the time delay as a timer
➢the number of events as a counter
o Timer 0: TH0 & TL0
➢Timer 0 high byte, timer 0 low byte
o Timer 1: TH1 & TL1
➢Timer 1 high byte, timer 1 low byte
o Each 16-bit timer can be accessed as two separate
registers of low byte and high byte.
144
Timer Registers

TH0 TL0

D15 D14 D13 D12 D11 D10 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0

Timer 0
TH1 TL1

D15 D14 D13 D12 D11 D10 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0

Timer 1
145
TMOD Register
• Timer mode register: TMOD
MOV TMOD,#21H
o An 8-bit register
o Set the usage mode for two timers
➢Set lower 4 bits for Timer 0 (Set to 0000 if not used)
➢Set upper 4 bits for Timer 1 (Set to 0000 if not used)
o Not bit-addressable
(MSB) (LSB)
GATE C/T M1 M0 GATE C/T M1 M0
Timer 1 Timer 0
146
TMOD Register
• GATE: Gating control when set.
o Timer/counter is enabled only while the INTx pin is high and the TRx
control pin is set.
o When cleared, the timer is enabled whenever the TRx control bit is set.
• C/T: Timer or counter selected cleared for timer operation (input
from internal system clock).
o Set for counter operation (input from Tx input pin).
• M1 Mode bit 1
• M0 Mode bit 0
(MSB) (LSB)
GATE C/T M1 M0 GATE C/T M1 M0
Timer 1 Timer 0
147
C/T (Clock/Timer)
• This bit is used to decide whether the timer is
used as a delay generator or an event counter.
• C/T = 0 : timer
• C/T = 1 : counter

148
Gate
• Every timer has a mean of starting and stopping.
o GATE=0
➢Internal control
➢The start and stop of the timer are controlled by way of
software.
➢Set/clear the TR for start/stop timer.
o GATE=1
➢External control
➢The hardware way of starting and stopping the timer by
software and an external source.
➢Timer/counter is enabled only while the INT pin is high and
the TR control pin is set (TR). 149
Timer Modes
• M0 and M1 select the timer mode for timers 0 & 1.
M1 M0 Mode Operating Mode
0 0 0 13-bit timer mode
8-bit THx + 5-bit TLx (x= 0 or 1)
0 1 1 16-bit timer mode
8-bit THx + 8-bit TLx
1 0 2 8-bit auto reload
8-bit auto reload timer/counter;
THx holds a value which is to be reloaded into
TLx each time it overflows.
1 1 3 Split timer mode
150
Example
• Find the value for TMOD if we want to program timer 0 in
mode 2,
• use 8051 XTAL for the clock source, and use instructions to
start and stop the timer.
Solution:
timer 1 timer 0

TMOD= 0000 0010 Timer 1 is not used.


Timer 0, mode 2,
C/T = 0 to use XTAL clock source (timer)
gate = 0 to use internal (software)
start and stop method. 151
Timer modes

152
TCON Register (1/2)
• Timer control register: TMOD
o Upper nibble for timer/counter, lower nibble for
interrupts
• TR (run control bit)
o TR0 for Timer/counter 0; TR1 for Timer/counter 1.
o TR is set by programmer to turn timer/counter on/off.
➢TR=0: off (stop)
➢TR=1: on (start)
(MSB) (LSB)
TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
Timer 1 Timer0 for Interrupt 153
Example Interrupt Service Routine
• TF (timer flag, control flag)
o TF0 for timer/counter 0; TF1 for timer/counter 1.
o TF is like a carry. Originally, TF=0. When TH-TL roll
over to 0000 from FFFFH, the TF is set to 1.
➢TF=0 : not reach
➢TF=1: reach
➢If we enable interrupt, TF=1 will trigger ISR.

(MSB) TCON Register (2/2) (LSB)


TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
Timer 1 Timer0 for Interrupt
154
Equivalent Instructions
for the Timer Control Register
For timer 0
SETB TR0 = SETB TCON.4
CLR TR0 = CLR TCON.4

SETB TF0 = SETB TCON.5


CLR TF0 = CLR TCON.5
For timer 1
SETB TR1 = SETB TCON.6
CLR TR1 = CLR TCON.6

SETB TF1 = SETB TCON.7


CLR TF1 = CLR TCON.7

TCON: Timer/Counter Control Register


TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
Timer Mode 1
• In following, we all use timer 0 as an example.
• 16-bit timer (TH0 and TL0)
• TH0-TL0 is incremented continuously when TR0 is set to 1.
And the 8051 stops to increment TH0-TL0 when TR0 is
cleared.
• The timer works with the internal system clock. In other
words, the timer counts up each machine cycle.
• When the timer (TH0-TL0) reaches its maximum of FFFFH,
it rolls over to 0000, and TF0 is raised.
• Programmer should check TF0 and stop the timer 0. 156
Steps of Mode 1
• 1- Choose mode 1 timer 0
o MOV TMOD,#01H
• 2- Set the original value to TH0 and TL0.
o MOV TH0,#FFH
o MOV TL0,#FCH
• 3- You had better to clear the flag to monitor:
TF0=0.
o CLR TF0
• 4- Start the timer.
o SETB TR0
157
Steps of Mode 1
5.The 8051 starts to count up by incrementing the
TH0-TL0.
o TH0-TL0= FFFCH,FFFDH,FFFEH,FFFFH,0000H
TR0=1 TR0=0
Start timer TH0 TL0
Stop timer

FFFC FFFD FFFE FFFF 0000

TF = 0 TF = 0 TF = 0 TF = 0 TF = 1

TF Monitor TF until TF=1 158


Steps of Mode 1
• 6- When TH0-TL0 rolls over from FFFFH to
0000, the 8051 set TF0=1.
o TH0-TL0= FFFEH, FFFFH, 0000H (Now TF0=1)
• 7- Keep monitoring the timer flag (TF) to see if it
is raised.
o AGAIN: JNB TF0, AGAIN
• 8- Clear TR0 to stop the process.
o CLR TR0
• 9- Clear the TF flag for the next round.
o CLR TF0
159
Mode 1 Programming

XTAL
oscillator ÷ 12
C/T = 0 Timer
overflow
flag

TH TL TF

TR
TF goes high when FFFF 0

160
Timer Delay Calculation
for XTAL = 11.0592 MHz
• (a) in hex
o (FFFF – YYXX + 1) × 1.085 s
o where YYXX are TH, TL initial values
respectively.
o Notice that values YYXX are in hex.
• (b) in decimal
o Convert YYXX values of the TH, TL register to
decimal to get a NNNNN decimal number
o then (65536 – NNNNN) × 1.085 s
161
Example
• square wave of 50% duty on P1.5
• Timer 0 is used
;each loop is a half clock
MOV TMOD,#01 ;Timer 0,mode 1(16-bit)
HERE: MOV TL0,#0F2H ;Timer value = FFF2H
MOV TH0,#0FFH
CPL P1.5 P1.5
ACALL DELAY 50% 50%
SJMP HERE whole clock
162
Example
• generate delay using timer 0
DELAY:
SETB TR0 ;start the timer 0
AGAIN: JNB TF0,AGAIN
CLR TR0 ;stop timer 0
CLR TF0 ;clear timer 0 flag
RET

FFF2 FFF3 FFF4 FFFF 0000

TF0 = 0 TF0 = 0 TF0 = 0 TF0 = 0 TF0 = 1


163
Example (3/3)
• Solution: In the above program notice the following
steps.
o 1. TMOD = 0000 0001 is loaded.
o 2. FFF2H is loaded into TH0 – TL0.
o 3. P1.5 is toggled for the high and low portions of the pulse.
o 4. The DELAY subroutine using the timer is called.
o 5. In the DELAY subroutine, timer 0 is started by the “SETB TR0”
o instruction.
o 6. Timer 0 counts up with the passing of each clock, which is provided by
the crystal oscillator.
➢ As the timer counts up, it goes through the states of FFF3, FFF4, FFF5, FFF6, FFF7,
FFF8, FFF9, FFFA, FFFB, FFFC, FFFFD, FFFE, FFFFH. One more clock rolls it to 0,
raising the timer flag (TF0 = 1). At that point, the JNB instruction falls through.
o 7. Timer 0 is stopped by the instruction “CLR TR0”. The DELAY
subroutine ends, and the process is repeated.
• Note: to repeat the process, we must reload the TL and TH
registers, and start the timer again (in the main program).
164
Example
• This program generates a square wave on pin P1.5 Using
timer 1
• Find the frequency.(don’t include the overhead of instruction
delay)
• XTAL = 11.0592 MHz
MOV TMOD,#10H ;timer 1, mode 1
AGAIN: MOV TL1,#34H ;timer value=3476H
MOV TH1,#76H
SETB TR1 ;start
BACK: JNB TF1,BACK
CLR TR1 ;stop
CPL P1.5 ;next half clock
CLR TF1 ;clear timer flag 1
SJMP AGAIN ;reload timer1
165
Example
• Solution:
o FFFFH – 7634H + 1 = 89CCH = 35276 clock
count
o Half period = 35276 × 1.085 s = 38.274 ms
o Whole period = 2 × 38.274 ms = 76.548 ms
o Frequency = 1/ 76.548 ms = 13.064 Hz.
• Note:
o Mode 1 is not auto reload then the program must reload the
TH1, TL1 register every timer overflow if we want to have a
continuous wave.
166
Find Timer Values
• Assume that XTAL = 11.0592 MHz .
• And we know desired delay
• how to find the values for the TH,TL ?
o 1- Divide the delay by 1.085 s and get n.
o 2- Perform 65536 –n
o 3- Convert the result of Step 2 to hex (yyxx )
o 4- Set TH = yy and TL = xx.

167
Example
• Assuming XTAL = 11.0592 MHz,
• write a program to generate a square wave of 50 Hz
frequency on pin P2.3.
• Solution:
o 1- The period of the square wave = 1 / 50 Hz = 20 ms.
o 2- The high or low portion of the square wave = 10 ms.
o 3- 10 ms / 1.085 s = 9216
o 4- 65536 – 9216 = 56320 in decimal = DC00H in hex.
o 5- TL1 = 00H and TH1 = DCH.

168
Example
MOV TMOD,#10H ;timer 1, mode 1
AGAIN: MOV TL1,#00 ;Timer value = DC00H
MOV TH1,#0DCH
SETB TR1 ;start
BACK: JNB TF1,BACK
CLR TR1 ;stop
CPL P2.3
CLR TF1 ;clear timer flag 1
SJMP AGAIN ;reload timer since
;mode 1 is not
;auto-reload
169
Generate a Large Time Delay
• The size of the time delay depends on two factors:
o They crystal frequency
o The timer’s 16-bit register, TH & TL
• The largest time delay is achieved by making
TH=TL=0.
• What if that is not enough?
• Next Example show how to achieve large time
delay
170
Example
• Examine the following program and find the time delay in seconds.
• Exclude the overhead due to the instructions in the loop.
MOV TMOD,#10H
MOV R3,#200
AGAIN: MOV TL1,#08
MOV TH1,#01
SETB TR1
BACK: JNB TF1,BACK
CLR TR1
CLR TF1
DJNZ R3,AGAIN
• Solution:
o TH – TL = 0108H = 264 in decimal
o 65536 – 264 = 65272.
o One of the timer delay = 65272 × 1.085 s = 70.820 ms
o Total delay = 200 × 70.820 ms = 14.164024 seconds

171
Timer Mode 0
• Mode 0 is exactly like mode 1 except that it is a
13-bit timer instead of 16-bit.
o 8-bit TH0
o 5-bit TL0
• The counter can hold values between 0000 to
1FFF in TH0-TL0.
o 213-1= 2000H-1=1FFFH
• We set the initial values TH0-TL0 to count up.
• When the timer reaches its maximum of 1FFFH,
it rolls over to 0000, and TF0 is raised.
172
Timer Mode 2

• 8-bit timer.
o It allows only values of 00 to FFH to be loaded into TH0.

• Auto-reloading
• TL0 is incremented continuously when
TR0=1.
• next example: 200 µs delay on timer 0.
173
Steps of Mode 2
• 1- Chose mode 2 timer 0
o MOV TMOD,#02H
• 2- Set the original value to TH0.
o MOV TH0,#38H
• 3- Clear the flag to TF0=0.
o CLR TF0
• 4- After TH0 is loaded with the 8-bit value, the 8051
gives a copy of it to TL0.
o TL0=TH0=38H
• 5- Start the timer.
o SETB TR0 174
Steps of Mode 2
• 6- The 8051 starts to count up by incrementing the TL0.
o TL0= 38H, 39H, 3AH,....
• 7- When TL0 rolls over from FFH to 00, the 8051 set
TF0=1. Also, TL0 is reloaded automatically with the
value kept by the TH0.
o TL0= FEH, FFH, 00H (Now TF0=1)
o The 8051 auto reload TL0=TH0=38H.
o Clr TF0
o Go to Step 6 (i.e., TL0 is incrementing continuously).
• Note that we must clear TF0 when TL0 rolls over. Thus,
we can monitor TF0 in next process.
• Clear TR0 to stop the process.
o Clr TR0
175
Timer 1 Mode 2 with internal Input

XTAL
÷ 12
oscillator

C/T = 0

TL1 TF1 overflow flag

reload
TR1 TH1

TF goes high when FF 0

176
Example
• Find the frequency of a square wave generated on pin P1.0.
Solution:
MOV TMOD,#2H ;Timer 0,mode 2
MOV TH0,#0
AGAIN:MOV R5,#250 ;count 250 times
ACALL DELAY
CPL P1.0
SJMP AGAIN

DELAY:SETB TR0 ;start


BACK: JNB TF0,BACK ;wait until TL0 ovrflw auto-reload
CLR TR0 ;stop
CLR TF0 ;clear TF
DJNZ R5,DELAY
RET
T = 2 (250 × 256 × 1.085 s) = 138.88 ms, and frequency = 72 Hz. 177
Example
• Assuming that we are programming the timers for mode 2, find
the value (in hex) loaded into TH for each of the following cases.
o (a) MOV TH1,#-200 (b) MOV TH0,#-60 (c) MOV TH1,#-3
o (d) MOV TH1,#-12 (e) MOV TH0,#-48
• Solution:
o Some 8051 assemblers provide this way.
o -200 = -C8H  2’s complement of –200 = 100H – C8H = 38 H
Decimal 2’s complement (TH value)
-200 = - C8H 38H
- 60 = - 3CH C4H
- 3 FDH
- 12 F4H

- 48 D0H 178
Example
• Find
o (a) the frequency of the square wave generated in the following
code
o (b) the duty cycle of this wave.
• Solution:
o “MOV TH0,#-150” uses 150 clocks.
o The DELAY subroutine = 150 × 1.085 s = 162 s.
o The high portion is twice tat of the low portion (66% duty
cycle).
o The total period = high portion + low portion
o T= 325.5 s + 162.25 s = 488.25 s
o Frequency = 2.048 kHz.
179
Example
MOV TMOD,#2H ;Timer 0,mode 2
MOV TH0,#-150 ;Count=150
AGAIN:SETB P1.3
ACALL DELAY
high period
ACALL DELAY
CLR P1.3
ACALL DEALY low period
SJMP AGAIN

DELAY:SETB TR0 ;start


BACK: JNB TF0,BACK
CLR TR0 ;stop
CLR TF0 ;clear TF
RET 180
Counter
• These timers can also be used as counters
counting events happening outside the 8051.
• When the timer is used as a counter, it is a pulse
outside of the 8051 that increments the TH, TL.
• When C/T=1, the counter counts up as pulses are
fed from
o T0: timer 0 input (Pin 14, P3.4)
o T1: timer 1 input (Pin 15, P3.5)

181
Port 3 Pins Used For Timers 0 and 1

Pin Port Pin Function Description

14 P3.4 T0 Timer/Counter 0 external input


15 P3.5 T1 Timer/Counter 1 external input

(MSB) (LSB)

GATE C/T=1 M1 M0 GATE C/T=1 M1 M0


Timer 1 Timer 0

182
Timer/Counter

183
Counter Mode 1
• 16-bit counter (TH0 and TL0)
• TH0-TL0 is incremented when TR0 is set to 1 and an external
pulse (in T0) occurs.
• When the counter (TH0-TL0) reaches its maximum of FFFFH, it
rolls over to 0000, and TF0 is raised.
• Programmers should monitor TF0 continuously and stop the
counter 0.
• Programmers can set the initial value of TH0-TL0 and let TF0=1
as an indicator to show a special condition.
(example: 100 people have come).
184
Timer 0 with External Input (Mode 1)

overflow
flag
Timer 0
external TH0 TL0 TF0
input Pin
3.4

C/T = 1 TF0 goes high when FFFF 0


TR0

185
Counter Mode 2
• 8-bit counter.
o It allows only values of 00 to FFH to be loaded
into TH0.
• Auto-reloading
o TL0 is incremented if TR0=1 and external
pulse occurs.

186
Example
• Assuming that clock pulses are fed into pin T1, write a program for counter 1
in mode 2 to count the pulses and display the state of the TL 1 count on P2.
• Solution:
MOV TMOD,#01100000B ;mode 2, counter 1
MOV TH1,#0
SETB P3.5 ;make T1 input port
AGAIN:SETB TR1 ;start
BACK: MOV A,TL1
MOV P2,A ;display in P2
JNB TF1,Back ;overflow
CLR TR1 ;stop
CLR TF1 ;make TF=0
SJMP AGAIN ;keep doing it

187
Example
• Timer 1 as an event counter fed into pin3.5.
• “SETB P3.5” make P3.5 an input port by making it high

8051

P2 is connected to 8 LEDs and


P2 to
input T1 to pulse.
LEDs
P3.5
T1

188
Example
• Assume that a 1-Hz frequency pulse is connected to input pin 3.4.
• Write a program to display counter 0 on an LCD. Set the initial
value of TH0 to -60.
• Solution:
• Note that on the first round, it starts from 0 and counts 256 events,
since on RESET, TL0=0. To solve this problem, load TH0 with -60
at the beginning of the program. 8051

P1 to
LCD
P3.4
1 Hz clock T0
189
Example
ACALL LCD_SET_UP ;initialize the LCD
MOV TMOD,#00000110B ;Counter 0,mode2
MOV TH0,#-60
SETB P3.4 ;make T0 as input
AGAIN:SETB TR0 ;starts the counter
BACK: MOV A,TL0 ;every 60 events
ACALL CONV ;convert in R2,R3,R4
ACALL DISPLY ;display on LCD
JNB TF0,BACK ;loop if TF0=0
CLR TR0 ;stop
CLR TF0
SJMP AGAIN
190
Example
• converting 8-bit binary to ASCII
CONV: MOV B,#10 ;divide by 10
DIV AB
MOV R2,B ;save low digit
MOV B,#10 ;divide by 10 once more
DIV AB
ORL A,#30H ;make it ASCII
MOV R4,A
MOV A,B R4 R3 R2
ORL A,#30H
MOV R3,A
MOV A,R2
ORL A,#30H
MOV R2,A ;ACALL LCD_DISPLAY here
RET 191
A Digital Clock
• Past example shows a simple digital clock.
o If we feed an external square wave of 60 Hz frequency into the
timer/counter, we can generate the second, the minute, and the
hour out of this input frequency and display the result on an
LCD.
• You might think that the use of the instruction “JNB
TF0, target” to monitor the raising of the TF0 flag is a
waste of the microcontroller’s time.
o The solution is the use of interrupt. See Chapter 11.
o In using interrupts we can do other things with the 8051.
o When the TF flag is raised it will inform us.
192
GATE=1 in TMOD
• All discuss so far has assumed that GATE=0.
o The timer is stared with instructions “SETB TR0”
and “SETB TR1” for timers 0 and 1, respectively.
• If GATE=1, we can use hardware to control the
start and stop of the timers.
o INT0 (P3.2, pin 12) starts and stops timer 0
o INT1 (P3.3, pin 13) starts and stops timer 1
o This allows us to start or stop the timer externally at
any time via a simple switch.
193
GATE (external control)
• Timer 0 must be turned on by “SETB TR0”
• If GATE=1 count up if
• INT0 input is high
o TR0=1
• If GATE=0 count up if
o TR0=1

194
195
196
197
198
MCS-51 Family
Interrupts

199
Interrupts Programming
• An interrupt is an external or internal event that
interrupts the microcontroller to inform it that a device
needs its service.
• Interrupts vs. Polling:
o A single microcontroller can serve several devices.
o There are two ways to do that:
➢ interrupts
➢ polling.
o The program which is associated with the interrupt is called
the interrupt service routine (ISR) or interrupt handler.

200
Steps in executing an interrupt
• Finish current instruction and saves the PC on
stack.
• Jumps to a fixed location in memory depend on
type of interrupt
• Starts to execute the interrupt service routine
until RETI (return from interrupt)
• Upon executing the RETI the microcontroller
returns to the place where it was interrupted.
• Get pop PC from stack
201
Interrupt Sources
• Original 8051 has 6 sources of
interrupts
o Reset
o Timer 0 overflow
o Timer 1 overflow
o External Interrupt 0
o External Interrupt 1
o Serial Port events (buffer full, buffer empty, etc)
• Enhanced version has 22 sources
– More timers, programmable counter array, ADC,
more external interrupts, another serial port (UART)
202
Interrupt Vectors
• Each interrupt has a specific place in code
memory where program execution (interrupt
service routine) begins.
• External Interrupt 0: 0003h
• Timer 0 overflow: 000Bh
Note: that there are only 8
• External Interrupt 1: 0013h memory locations between
• Timer 1 overflow: 001Bh vectors.
• Serial : 0023h
• Timer 2 overflow(8052+) 002bh
203
ISRs and Main Program in 8051
ORG 00H
SJMP main
ORG 03H
ljmp int0sr
ORG 0BH
ljmp t0sr
ORG 13H
ljmp int1sr
ORG 1BH
ljmp t1sr
ORG 23H
ljmp serialsr

ORG 30H
main:

END
Interrupt Enable (IE) register
• All interrupt are disabled after reset
• We can enable and disable them bye IE
Enabling and disabling an interrupt
• by bit operation:
• Recommended in the middle of program
SETB EA SETB IE.7 ;Enable All
SETB ET0 SETB IE.1 ;Enable Timer0 ovrf
SETB ET1 SETB IE.3 ;Enable Timer1 ovrf
SETB EX0 SETB IE.0 ;Enable INT0
SETB EX1 SETB IE.2 ;Enable INT1
SETB ES SETB IE.4 ;Enable Serial port
• by mov instruction:
• Recommended in the first of program
MOV IE, #10010110B
Example
• A 10khz square wave with 50% duty cycle
ORG 0 ;Reset entry poit
LJMP MAIN ;Jump above interrupt
ORG 000BH ;Timer 0 interrupt vector
T0ISR: CPL P1.0 ;Toggle port bit
RETI ;Return from ISR to Main program
ORG 0030H ;Main Program entry point
MAIN: MOV TMOD,#02H ;Timer 0, mode 2
MOV TH0,#-50 ;50 us delay
SETB TR0 ;Start timer
MOV IE,#82H ;Enable timer 0 interrupt
SJMP $ ;Do nothing just wait
END
207
Example
• Write a program using interrupts to
simultaneously create 7 kHz and 500 Hz square
waves on P1.7 and P1.6.
8051
143
s
71
P1.7 s

2ms
P1.6 1ms

208
Solution
ORG 0
LJMP MAIN
ORG 000BH
LJMP T0ISR
ORG 001BH
LJMP T1ISR 8051 143
ORG 0030H
s
71
MAIN: MOV TMOD,#12H P1.7 s
MOV TH0,#-71
SETB TR0
SETB TF1
MOV IE,#8AH
MOV IE,#8AH 2ms
SJMP $ P1.6 1m
s
T0ISR: CPL P1.7
RETI
T1ISR: CLR TR1
MOV TH1,#HIGH(-1000)
MOV TL1,#LOW(-1000)
SETB TR1
CPL P1.6
RETI 209
END
Timer ISR
• There is no need for a “CLR TFx”
instruction in timer ISR
• 8051 clears the TF internally upon
jumping to ISR
• We should reload timer in mode 1
• There is no need on mode 2 (timer auto
reload)
210
External interrupt type control
• By low nibble of Timer control register TCON
• IE0 (IE1): External interrupt 0(1) edge flag.
o set by CPU when external interrupt edge (H-to-L) is detected.
o Does not affected by H-to-L while ISR is executed(no int on int)
o Cleared by CPU when RETI executed.
o does not latch low-level triggered interrupt
• IT0 (IT1): interrupt 0 (1) type control bit.
o Set/cleared by software
o IT=1 edge trigger
o IT=0 low-level trigger
(MSB) (LSB)
TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
Timer 1 Timer0 for Interrupt 211
External Interrupts
Level-triggered (default)
INT0
(Pin 3.2) 0
IT0 0003
1
IE0 (TCON.3)
Edge-triggered

Level-triggered (default)
INT0
(Pin 3.3) 0 0013
IT1
1
IE1 (TCON.3)
Edge-triggered

212
Example of external interrupt
ORG 0000H
LJMP MAIN
;
;interrupt service routine (ISR)
;for hardware external interrupt INT1
;

ORG 0013H
SETB P1.1
MOV R0,200
WAIT: DJNZ R0,WAIT
CLR P1.1
RETI
;
;main program for initialization
;
ORG 30H
MAIN: SETB IT1 ;on negative edge of INT1
MOV IE,#10000100B
WAIT2: SJMP WAIT2
END
213
214
Example of external interrupt
Org 0000h
Ljmp main
Org 0003h
x0isr: clr p1.7
Reti
Org 0013h
x1isr: setb p1.7
Reti
Org 0030h
Main: mov ie,#85h
Setb it0
Setb it1
Setb p1.7
Jb p3.2,skip
Clr p1.7
Skip: Sjmp $
end 215
Interrupt Priorities
• What will happen when two interrupt sources interrupt at
the same time?
• The interrupt with the highest PRIORITY gets serviced
first.
• All interrupts have a power on default priority order.
o 1- External interrupt 0 (INT0)
o 2- Timer interrupt0 (TF0)
o 3- External interrupt 1 (INT1)
o 4- Timer interrupt1 (TF1)
o 5- Serial communication (RI+TI)
• Priority can also be set to “high” or “low” by IP register.
216
Interrupt Priorities (IP) Register
--- --- PT2 PS PT1 PX1 PT0 PX0

• IP.7: reserved
• IP.6: reserved
• IP.5: timer 2 interrupt priority bit(8052 only)
• IP.4: serial port interrupt priority bit
• IP.3: timer 1 interrupt priority bit
• IP.2: external interrupt 1 priority bit
• IP.1: timer 0 interrupt priority bit
• IP.0: external interrupt 0 priority bit
217
Example
--- --- PT2 PS PT1 PX1 PT0 PX0

• MOV IP , #00000100B or SETB IP.2 gives priority order


1. Int1
2. Int0
3. Timer0
4. Timer1
5. Serial
• MOV IP , #00001100B gives priority order
1. Int1
2. Timer1
3. Int0
4. Timer0
5. Serial
218
Interrupt inside an interrupt
--- --- PT2 PS PT1 PX1 PT0 PX0

• A high-priority interrupt can interrupt a low-


priority interrupt
• All interrupt are latched internally
• Low-priority interrupt wait until 8051 has
finished servicing the high-priority interrupt

219
MCS-51Family
Serial Communication

220
Basics of serial communication
• Parallel: expensive - short distance – fast Serial:
o cheaper
o longer (two different cities by modem)
o slower

221
Basics of serial communication
Start and stop bits
• When there is no transfer, the signal is high
• Transmission begins with a start (low) bit
• LSB first
• Finally, 1 stop bit (high)
• Data transfer rate (baud rate) is stated in bps
o bps: bit per second

223
How to communicate 8051 to PC
• Connect TXD to RXD and RXD to TXD from pc to 8051
• Use max232 to transform signal from TTL level to RS232 level
• The baud rate of the 8051 must matched the baud rate of the pc
• PC standard baud rate
o 2400-4800-9600-14400-19200-28800-33600-57600
• Serial mode 1 is used
• Timer 1 is used
• The 8051 UART divides the machine cycle frequency by 32
• Machine cycle is 1/12 XTAL frequency
• We use timer1 in mode 2 (auto reload) 224
RxD and TxD pins in the 8051
• TxD pin 11 of the 8051 (P3.1)
• RxD pin 10 of the 8051 (P3.0)
• SBUF register:
o MOV SBUF, #’D’ ;load SBUF=44H, ASCII for ‘D’
o MOV SBUF, A ;copy accumulator into SBUF
o MOV A, SBUF ;copy SBUF into accumulator

225
MAX232

226
227
228
Various Baud Rates
Serial control (SCON) Register
SM0 SM1 SM2 REN TB8 RB8 TI RI

• SM0 (SCON.7) : mode specifier


• SM1 (SCON.6) : mode specifier
• SM2 (SCON.5) : used for multi processor communication
• REN (SCON.4) : receive enable (by software enable/disable)
• TB8 (SCON.3) : transmit bit8
• RB8 (SCON.2) : receive bit 8
• TI (SCON.1) : transmit interrupt flag set by HW clear by SW
• RI (SCON.0) : receive interrupt flag set by HW clear by SW
230
Mode of operation
SM0 SM1 MODE operation transmit rate
0 0 0 shift register fixed (xtal/12)
0 1 1 8 bit UART variable (timer1)
1 0 2 9 bit UART fixed (xtal/32 or xtal/64)
1 1 3 9 bit UART variable (timer1)

231
Mode of operation
• Mode 0 :
o Serial data enters and exits through RxD
o TxD outputs the shift clock.
o 8 bits are transmitted/received(LSB first)
o The baud rate is fixed a 1/12 the oscillator frequency.
• Application
o Port expansion 8051

TXD clk
Shift register
RXD data

232
Mode of operation
• Mode 1
o Ten bits are transmitted (through TxD) or received (through RxD)
o A start bit (0), 8 data bits (LSB first), and a stop bit (1)
o On receive, the stop bit goes into RB8 in SCON
o the baud rate is determined by the Timer 1 overflow rate.
o Timer1 clock is 1/32 machine cycle (MC=1/12 XTAL)
o Timer clock can be programmed as 1/16 of machine cycle
o Transmission is initiated by any instruction that uses SBUF as a destination
register.

233
234
Mode of operation
• Mode 2 :
o Eleven bits are transmitted (through TxD), received (through RxD)
➢ A start bit (0)
➢ 8 data bits (LSB first)
➢ A programmable 9th data bit
➢ and a stop bit (1)
o On transmit, the 9th bit (TB8) can be assigned 0 or 1.
o On receive, the 9the data bit goes into RB8 in SCON.
o the 9th can be parity bit
o The baud rate is programmable to 1/32 or 1/64 the oscillator
frequency in Mode 2 by SMOD bit in PCON register
o Mode 3
o Same as mode 2
o But may have a variable baud rate generated from Timer 1.
235
SMOD
• Bit 7 of PCON register
• If SMOD=1 double baud rate
• PCON is not bit addressable
• How to set SMOD
oMov a, pcon
oSetb acc.7
oMov pcon,a

236
Example
An example of sending a message.
;initialization
MOV TMOD,#20H
MOV TH1,#-12
MOV SCON,#52H
;begin to trnasmit
SETB TR1
AGAIN1: MOV A,#'B'
CALL TRANSS
MOV A,#'A'
CALL TRANSS
MOV A,#'L'
CALL TRANSS
MOV A,#'E'
CALL TRANSS
SJMP AGAIN1
;seial transmiting subroutine
TRANSS:MOV SBUF,A
AGAIN2: JNB TI,AGAIN2
CLR TI
RET
237
END
Example
An example for serial port interrupt
ORG 0000H
LJMP MAIN
;jump to serial ISR
ORG 23H
LJMP ISR
;main program
ORG 30H
;1-initializtion ;ISR for reading from serial port
MAIN: MOV P0,#0FFH ISR: PUSH ACC
MOV TMOD,#20H JB TI,TRANSM
MOV TH1,#-13 MOV A,SBUF
MOV SCON,#50H MOV P2,A
MOV IE,#90H CLR RI
;2-begin SJMP ISREND
SETB TR1 TRANSM:CLR TI
ISREND: POP ACC
AGAIN: MOV A,P0
RETI
MOV P1,A
END
SJMP AGAIN; 238
Example
an example for serial port interrupt
;for transmitting
ORG 0000H
LJMP MAIN
;jump to serial ISR
ORG 23H
LJMP ISR ;ISR for receive from serial to p0
;main program ;transmitting to serial from p1
ORG 30H ISR: JB TI,TRANSM
;initializtion MOV A,SBUF
mov P0,A
MAIN: MOV P0,#0FFH
CLR RI
MOV TMOD,#20H RETI
MOV TH1,#-13 TRANSM: MOV A,P1
MOV SCON,#50H MOV SBUF,A
MOV IE,#90H CLR TI
RETI
;2-begin
END
SETB TR1
239
AGAIN: SJMP AGAIN
Example
ORG 0000
;Initialize serial port & timer
INIT: MOV SCON,#52H ;Serial port mode 1
MOV TMOD,#20H ;Timer 1, mode 2
MOV TH1,#-13 ;Reload count for 2400 baud
SETB TR1 ;Start timer 1
;move character 'B' to accumulator for transmitting
MOV A,#'B'
;Transmit characters by serial port
OUTCHR:MOV C,P ;Put parity bit in C flag
CPL C ;Change to odd parity
MOV ACC.7,C ;Add to character code
AGAIN: JNB TI,AGAIN ;Buffer empty? no:check again
CLR TI ;Yes:clear falg and
MOV SBUF,A ;send character
CLR ACC.7 ;Strip off parity bit
JMP $
240
END
Power control register

241
Power control
• usefull for applications where power
consumption is critical
• two power reducing modes
o Idle
o Power down

242
Idle mode
• An instruction that sets PCON.0 causes Idle mode
o Last instruction executed before going into the Idle mode
o the internal CPU clock is gated off
o Interrupt, Timer, and Serial Port functions act normally.
o All of registers , ports and internal RAM maintain their data
during Idle
o ALE and PSEN hold at logic high levels
• Any interrupt
o will cause PCON.0 to be cleared by HW (terminate Idle mode)
o then execute ISR
o with RETI return and execute next instruction after Idle
instruction.
• RST signal clears the IDL bit directly
243
Power-Down Mode
• An instruction that sets PCON.1 causes power
down mode
• Last instruction executed before going into the
power down mode
• the on-chip oscillator is stopped.
• all functions are stopped, the contents of the on-
chip RAM and Special Function Registers are
maintained.
• The ALE and PSEN output are held low
• The reset that terminates Power Down 244
Example
Org 0000h
Ljmp main

Org 0003h
Orl pcon,#02h ;power down mode
Reti

Org 0030h
Main:
……
……
……
Orl pcon,#01h ;Idle mode
end 245
246
MCS-51Family
I/O

247
PPI-8255
• 8051 has limited number of I/O ports
• one solution is to add parallel interface chip(s)
• 8255 is a Programmable Peripheral Interface PPI
• Add it to 8051 to expand number of parallel ports
• 8051 I/O port does not have handshaking capability
• 8255 can add handshaking capability to 8051

248
PPI-8255
• Programmable Peripheral Interface (PPI)
o Has 3 8_bit ports A, B and C
o Port C can be used as two 4 bit ports CL and Ch
o Two address lines A0, A1 and a Chip select CS
o 8255 can be configured by writing a control-word in CR
register

249
250
251
8255 Operating Modes
• Mode 0 : Simple I/O
o Any of A, B, CL and CH can be programmed as input or
output
• Mode 1: I/O with Handshake
o A and B can be used for I/O
o C provides the handshake signals
• Mode 2: Bi-directional with handshake
o A is bi-directional with C providing handshake signals
o B is simple I/O (mode-0) or handshake I/O (mode-1)
• BSR (Bit Set Reset) Mode
o Only C is available for bit mode access
➢Allows single bit manipulation for control applications 252
253
Mode 0
• Provides simple input and output
operations for each of the three ports.
o No “handshaking” is required, data is simply
written to or read from a specified port.
o Two 8-bit ports and two 4-bit ports.
o Any port can be input or output.
o Outputs are latched.
o Inputs are not latched
254
Mode 1
• Mode 1 Basic functional Definitions:
o Two Groups (Group A and Group B).
o Each group has one 8-bit data port and one 4-
bit control/data port.
o The 8-bit data port can be either input or
output. Both inputs and outputs are latched.
o The 4-bit port is used for control and status of
the 8-bit data port.
255
8255 mode 1 (output)
256
Mode 1 – Control Signals
• Output Control Signal Definition
o OBF (Output Buffer Full F/F). (C7 for A, C1 for B)
➢The OBF output will go “low” to indicate that the CPU has
written data out to the specified port.
– A signal to the device that there is data to be read.
o ACK (Acknowledge Input). (C6 for A, C2 for B)
➢A “low” on this input informs the 8255 that the data from
Port A or Port B has been accepted.
– A response from the peripheral device indicating that it has read
the data.
o INTR (Interrupt Request). (C3 for A, C0 for B)
➢A “high” on this output can be used to interrupt the CPU
when an output device has accepted data transmitted by the
CPU. 257
Timing diagram for mode1(output)

258
8255 mode 1 (input) 259
Mode 1 – Control Signals
• Input Control Signal Definition
o STB (Strobe Input). (C4 for A, C2 for B)
➢A “low” on this input loads data into the input latch.
o IBF (Input Buffer Full F/F) (C5 for A, C1 for B)
➢A “high” on this output indicates that the data has
been loaded into the input latch; in essence, an
acknowledgement from the 8255 to the device.
o INTR (Interrupt Request) (C3 for A, C0 for B)
➢A “high” on this output can be used to interrupt the
CPU when an input device is requesting service.
260
Timing diagram for mode1(input)

261
Mode 2 - Strobed Bidirectional Bus I/O
• MODE 2 Basic Functional Definitions:
o Used in Group A only.
o One 8-bit, bi-directional bus port (Port A) and
a 5-bit control port (Port C).
o Both inputs and outputs are latched.
o The 5-bit control port (Port C) is used for
control and status for the 8-bit, bi-directional
bus port (Port A).
262
Mode 2
• Output Operations Pin Functio
o OBF (Output Buffer Full). The OBF n
Output will go low to indicate that the PC7 /OBF
CPU has written data out to port A. PC6 /ACK
o ACK (Acknowledge). A low on this input PC5 IBF
enables the tri-state output buffer of Port A
PC4 /STB
to send out the data. Otherwise, the output
buffer will be in the high impedance state. PC3 INTR
• Input Operations PC2 I/O
o STB (Strobe Input). A low on this input PC1 I/O
loads data into the input latch.
PC0 I/O
o IBF (Input Buffer Full F/F). A high on this
output indicates that data has been loadedinto the input latch.
264
BSR Mode
• If used in BSR mode, then the bits of port C can
be set or reset individually

265
BSR Mode example
Move dptr, 0093h
Up: Move a, 09h ;set pc4
Movx @dptr,a
Acall delay
Mov a,08h ;clr pc4
Movx @dptr,a
Acall delay
Sjmp up
266
Interfacing 8255 with 8051
• CS is used to interface 8255 with 8051
• If CS is generated from lets say Address lines A15:A12
as follows,
A15:A13 = 110
• Address of 8255 is:
o 110 xxxxx xxxx xx00b
• Base address of 8255 is
o 1100 0000 0000 0000b=C000H
• Address of the registers
o A = C000H
o B = C001H
o C = C002H
o CR = C003H 267
Interfacing 8255 with 8051
P2.7(A15) A2
P2.6(A14) A1
P2.5(A13) A0

74138
8051 3×8 decoder /CS

8255
ALE O0 A0
74373 O1 A1

P0.7-P0.0 D7-D0
(AD7-AD0)
O7
D7-D0
/RD /RD
/WR /WR

268
8255 Usage: Simple Example
• 8255 memory mapped to 8051 at address C000H base
o A = C000H, B = C001H, C = C002H, CR = C003H
• Control word for all ports as outputs in mode0
o CR : 1000 0000b = 80H
test: mov A, #80H ; control word
mov DPTR, #C003H ; address of CR
movx @DPTR, A ; write control word
mov A, #55h ; will try to write 55 and AA alternatively
repeat: mov DPTR,#C000H ; address of PA
movx @DPTR, A ; write 55H to PA
inc DPTR ; now DPTR points to PB
movx @DPTR, A ; write 55H to PB
inc DPTR ; now DPTR points to PC
movx @DPTR, A ; write 55H to PC
cpl A ; toggle A (55→AA, AA→55)
acall MY_DELAY ; small delay subroutine
sjmp repeat ; for (1) 269
I/O devices
• Peripheral devices (also called I/O devices) are pieces of
equipment that exchange data with a CPU
• Examples: switches, LED, CRT, printers, keyboard,
keypad
• Speed and characteristics of these devices are very
different from that of CPU so they cannot be connected
directly
• Interface chips are needed to resolve this problem
• Main function of an interface chip is to synchronize data
transfer between CPU and I/O device
• Data pins of interface chip are connected to CPU data
bus and I/O port pins are connected to I/O device 270
I/O devices
• Since a CPU may have multiple I/O devices, CPU data bus may be
connected to data buses of multiple interface
• An address decoder is used to select one device to respond to the
CPU I/O request
• Different CPUs deal with I/O devices differently
• Some CPUs have dedicated instructions for performing input and
output operations (isolated I/O)
• Other CPUs use the same instruction for reading from memory
and reading from input devices, as well as writing data into
memory and writing data into output devices (memory-mapped
I/O)
• MCS-51 (8051) is memory mapped
271
Synchronization of CPU
and interface chip
• There must be a mechanism to make sure that
there are valid data in the interface chip when
CPU reads them
• Input synchronization: two ways of doing this
o 1- Polling method
➢interface chip uses a status bit to indicate if it has valid data
for CPU
➢CPU keeps checking status bit until it is set, and then reads
data from interface chip
➢Simple method, used when CPU has nothing else to do
o 2- Interrupt driven method: interface chip interrupts
the CPU when it has new data. CPU executes the ISR272
Synchronization of CPU
and interface chip
• Output synchronization: two ways of doing
this
o 1- Polling method
➢interface chip uses a status bit to indicate that the
data register is empty
➢CPU keeps checking status bit until it is set, and
then writes data into interface chip
o 2- Interrupt driven method: interface chip
interrupts the CPU when it data register is
empty. CPU executes the ISR 273
Synchronization of CPU
and interface chip
• Methods used to synchronize data transfer between
interface chip and I/O devices:
o 1- Brute force method: interface chip returns voltage levels in
its input ports to CPU and makes data written by CPU directly
available on its output ports
➢ All 8051 port can perform brute force I/O
o 2- Strobe method:
➢ During input, the I/O device activates a strobe signal when data are
stable. Interface chip latches the data
➢ For output, interface chip places output data on output port. when data
is stable, it activates a strobe signal. I/O device latches the data
o 3- Handshake method: two handshake signals are needed
➢ One is asserted by interface chip and the other by I/O device
274
I/O Ports: Hardware Specs
• P0 is open drain.
o Has to be pulled high by external 10K resistors.
o Not needed if P0 is used for address lines
• P1, P2, P3 have internal pull-ups
• Port fan- out (number of devices it can drive) is
limited.
o Use buffers (74LS244, 74LS245,etc) to increase
drive.
• P1, P2, P3 can drive up to 4 LS-TTL inputs 275
Switch On I/O Ports
• Case-1:
o Gives a logic 0 on switch close
o Current is 0.5ma on switch close
• Case-2:
o Gives a logic 1 on switch close
o High current on switch close
• Case-3:
o Can damage port if 0 is output

276
Simple input devices
• DIP switches usually have 8 switches
• Use the case-1 from previous page
• Sequence of instructions to read a value from DIP
switches:

mov P1,#FFH
mov A,P1,

277
Interfacing a Keypad
• A 16-key keypad is built as shown in the figure below.
o 16 keys arranged as
a 4X4 matrix.
o Should “activate”
each row by placing
a 0 on its R output.
➢Then the column
output is read.
➢If there is a 0 on
one of the column
bits, then the button
at the column/row
intersection has
been pressed.
➢Otherwise, try next row.
o Repeat constantly 278
Bouncing Contacts
• Push-button switches, toggle switches, and
electromechanical relays all have one thing in common:
contacts.
• Metal contacts make and break the circuit and carry the
current in switches and relays. Because they are metal,
contacts have mass.
• Since at least one of the contacts is movable, it has
springiness.
• Since contacts are designed to open and close quickly,
there is little resistance (damping) to their movement
279
Bouncing
• Because the moving contacts have mass and springiness
with low damping they will be "bouncy" as they make
and break.
• That is, when a normally open (N.O.) pair of contacts is
closed, the contacts will come together and bounce off
each other several times before finally coming to rest in
a closed position.
• The effect is called "contact bounce" or, in a switch,
"switch bounce”.

280
Why is it a problem?
• If such a switch is used as a source to an
edge-triggered input such as INT0, then the
MCS-51 will think that there were several
“events” and respond several times.
• The bouncing of the switch may last for
several milliseconds.
o Given that the MCS-51 operates at
microsecond speed, a short ISR may execute
several times in response to the above
described bounciness 281
Hardware Solution
• The simplest hardware solution uses an RC time constant to
suppress the bounce. The time constant has to be larger than the
switch bounce and is typically 0.1 seconds.
• As long as capacitor voltage does not exceed a threshold value, the
output signal will be continued to be recognized as a logic 1.
• The buffer after the switch produces a sharp high-to-low
transition. Vcc

OUT
Hardware Solution

283
Software Solution
• It is also possible to counter the bouncing
problem using software.
• The easies way is the wait-and-see
technique
o When the input drops, an “appropriate” delay
is executed (10 ms), then the value of the line is
checked again to make sure the line has
stopped bouncing
284
Interfacing a Keypad
scan: mov P1,#EFH
jnb P1.0,db_0
scan1: jnb P1.1,db_1
scan2: jnb P1.2,db_2
scan3: jnb P1.3,db_3
scan4: mov P1,#DFH
jnb P1.0,db_4
…..
…..
…..

285
Interfacing a Keypad
db_0: lcall wt_10ms
jb P1.0, scan1
mov A, #0
ljmp get_code
db_1: lcall wt_10ms
jb P1.1, scan2
mov A, #1
ljmp get_code
…..
….
…..
get_code: mov DPRT, #key_tab
movc A, @A+DPRT
ljmp scan
key_tab: db ‘0123456789ABCDEF’
END 286
Simple output devices
• Case-1
o LED is ON for an output of zero
o Most LEDs drop 1.7 to 2.5 volts and need about 10ma
o Current is (5-2)/470
• Case-2
o Too much current
o Failure of Port or LED
• Case-3
o Not enough drive (1ma)
o LED too dim

287
The 7-Segment Display
• 7 LEDs arranged to form the number 8.
o By turning on and off the appropriate segments
(LEDs), different combinations can be roduced.
o useful for displaying the digits 0 through 9, and some
characters. a

f b

e c

d
288
The 7-segment Display
• 7-segment displays come in 2 configurations:

Common Anode Common Cathode

• As we have seen, it would be preferable to connect the


cathode of each diode to the output pin.
• Therefore, the common anode variety would be better
for our interfacing needs.
289
Interfacing a 7-segment display
• Also, as seen with interfacing the LED, a resistor will be
needed to control the current flowing through the diode.
– This leaves two possibilities:

o Case 2 would be more appropriate as case 1 will produce different


brightness depending on the number of LEDs turned on. 290
Use of current buffer
• Interfacing to a DIP switch and 7-segment display
• Output a ‘1’ to ON a segment
• We can use 74244 to common cathode 7_seg

291
BCD to 7_Seg lookup table
BCD pgfedcba hex
7_seg
mov a,p3 0000 001111 11 3f
anl a,0fh 0001 00110000 30
get_code: mov DPTR, #7s_tab 0010 0101101 1 5b
movc A, @A+DPRT 0011 010011 11 4f
mov p1,a 0100 011001 10 66
0101 01101101 6d
7s_tab: db 3fh,30h,5bh,4fh,66h 0110 01111101 7d
db 6dh,7dh,07h,7fh,6fh 0111 00000111 07
end 1000 01111111 7f
1001 01101111 6f
a a a a a a a a
f b f b b f b f f b f b f b
g g g g g g g
e c e e c c c e c c e c c
d d d d d d d
LCD Interfacing
• Liquid Crystal Displays (LCDs)
• cheap and easy way to display text
• Various configurations (1 line by 20 X char up to 8 lines
X 80 ).
• Integrated controller
• The display has two register
o command register
o data register
• By RS you can select register
• Data lines (DB7-DB0) used to transfer data and
commands
293
Alphanumeric LCD Interfacing
• Pinout
o 8 data pins D7:D0 E communications bus

Microcontroller
R/W
o RS: Data or Command
Register Select RS

o R/W: Read or Write DB7–DB0

o E: Enable (Latch data) 8


LCD
• RS – Register Select controller

o RS = 0 → Command Register LCD Module


o RS = 1 → Data Register
• R/W = 0 → Write , R/W = 1 → Read
• E – Enable
o Used to latch the data present on the data pins.
• D0 – D7
o Bi-directional data/command pins.
o Alphanumeric characters are sent in ASCII format. 294
LCD Commands
• The LCD’s internal controller can accept several
commands and modify the display accordingly. These
commands would be things like:
o Clear screen
o Return home
o Decrement/Increment cursor
• After writing to the LCD, it takes some time for it to
complete its internal operations. During this time, it will
not accept any new commands or data.
o We need to insert time delay between any two commands or
data sent to LCD
295
Pin Description
296
Command Codes

297
Command Codes

298
LCD Timing

299
300
Interfacing LCD with 8051
8051

LM015

P3.4
RW
P3.5 E

P3.3 RS

P1.7-P1.0 D7-D0

301
Interfacing LCD with 8051
mov A, command
call cmd
delay
mov A, another_cmd
call cmd
delay
mov A, #’A’
call data
delay
mov A, #’B’
call data
delay
….
Command and Data Write Routines
data:mov P1, A ;A is ascii data
setb P3.3 ;RS=1 data
clr P3.4 ;RW=0 for write
setb P3.5 ;H->L pulse on E
clr P3.5
ret
cmd: mov P1,A ;A has the cmd word
clr P3.3 ;RS=0 for cmd
clr P3.4 ;RW=0 for write
setb P3.5 ;H->L pulse on E
clr P3.5
ret
302
Example

303
Stepper Motors

• more accurately controlled than a normal motor


allowing fractional turns or n revolutions to be
easily done
• low speed, and lower torque than a comparable
D.C. motor
• useful for precise positioning for robotics
• Servomotors require a position feedback signal
for control 304
Stepper Motor Diagram

305
Stepper Motor Step Angles

306
Terminology

• Steps per second, RPM


o SPS = (RPM * SPR) /60

• Number of teeth

• 4-step, wave drive 4-step, 8-step

• Motor speed (SPS)

• Holding torque
307
Stepper Motor Types

• Variable Reluctance

• Permanent Magnet

308
Variable Reluctance Motors

309
Variable Reluctance Motors
• Reluctance motor is usually a four wire motor –
the common wire goes to the +v supply and the
windings are stepped through
• Our example is a 30o motor
• The rotor has 4 poles and the stator has 6 poles
• Example

310
Variable Reluctance Motors
• To rotate we excite the 3 windings in
sequence
o W1 - 1001001001001001001001001
o W2 - 0100100100100100100100100
o W3 - 0010010010010010010010010
• This gives two full revolutions

311
Unipolar Motors

312
Unipolar Motors

313
Unipolar Motors
• To rotate we excite the 2 windings in
sequence
o W1a - 1000100010001000100010001
o W1b - 0010001000100010001000100
o W2a - 0100010001000100010001000
o W2b - 0001000100010001000100010
• This gives two full revolutions

314
Basic Actuation Wave Forms

315
Unipolar Motors
• To rotate we excite the 2 windings in
sequence
o W1a - 1100110011001100110011001
o W1b - 0011001100110011001100110
o W2a - 0110011001100110011001100
o W2b - 1001100110011001100110011
• This gives two full revolutions at 1.4 times
greater torque but twice the power
316
Enhanced Waveforms

• better torque
• more precise control
Unipolar Motors
• The two sequences are not the same, so by
combining the two you can produce half
stepping
o W1a - 11000001110000011100000111
o W1b - 00011100000111000001110000
o W2a - 01110000011100000111000001
o W2b - 00000111000001110000011100

318
Motor Control Circuits
• For low current options the ULN200x family of
Darlington Arrays will drive the windings direct.

319
Interfacing to Stepper Motors

320
Example

321
Digital to Analog Converter

322
Example – Step Ramp

323
Analog to Digital

324
Vin Range

325
Timing

326
Interfacing ADC

327
Example

328
Temperature Sensor

329
Printer Connections

330
IO Base Address for LPT

331
Printer’s Ports

332
MCS-51 Family
C Language Programming

333
Overview
• C for microcontrollers
o Review of C basics
o Compilation flow for Cygnal
o C extensions
o In-line assembly
o Interfacing with C
• Examples
• Arrays and Pointers
• I/O Circuitry
• Functions and Header Files
• Multitasking and multithreading 334
C for Microcontrollers
• Of higher level languages, C is the closest to
assembly languages
o bit manipulation instructions
o pointers (indirect addressing)
• Most microcontrollers have available C
compilers
• Writing in C simplifies code development
for large projects.
335
Available C Compilers

• Reads51
• Cygnal – integrated with the IDE
• Keil

336
Compilation Process (Cygnal)

program.c
compile no SRC option
program.LST program.OBJ
build/make
program.M51

337
Modular Programming
• Like most high level languages, C is a
modular programming language (but NOT
an object oriented language)
• Each task can be encapsulated as a
function.
• Entire program is encapsulated in “main”
function.

338
Basic C Program Structure
• Compiler directives and include files
• Declarations of global variables and
constants
• Declaration of functions
• Main function
• Sub-functions
• Interrupt service routines
339
Back to C Basics
• All C program consists of:
o Variables
o Functions (one must be “main”)
➢Statements
• To define the SFRs as variables:
o #include <c8051F020.h>

340
Variables
• All variables must be declared at top of program, before
the first statement.
• Declaration includes type and list of variables.
Example: void main (void) { must go HERE!
int var, tmp;
• Types:
o int (16-bits in our compiler)
o char (8-bits)
o short (16-bits) not standard C – an 8051 extension
o long (32-bits)
o sbit (1-bit)
o others that we will discuss later 341
Variables
• The following variable types can be signed or
unsigned:
o signed char (8 bits) –128 to +127
o signed short (16 bits) –32768 to +32767
o signed int (16 bits) –32768 to +32767
o signed long (32 bits) –2147483648 to +2147483648
o unsigned char (8 bits) 0 to + 255
o unsigned short (16 bits) 0 to + 65535
o unsigned int (16 bits) 0 to + 65535
o unsigned long (32 bits) 0 to + 4294967295
• NOTE: Default is signed – it is best to specify. 342
Statements
• Assignment statement:
o variable = constant or expression or variable
• examples: upper = 60;
I = I + 5;
J = I;

343
Operators
• Arithmetic: +, -, *, /
• Relational: >, >=, <, <=
• Equality: ==, !=
• Logical: && (and), || (or)
• Increment and decrement: ++, --
• Example:
if (x != y) && (c == b)
{
a=c + d*b;
a++;
}
344
Example
Adder program (add 2 16-bit numbers)
$INCLUDE (C8051F020.inc) #include <c8051f020.h>
XL equ 0x78 void main (void) {
XH equ 0x79
int x, y, z;
YL equ 0x7A
YH equ 0x7B // disable watchdog timer
cseg at 0 WDTCN = 0xde;
ljmp Main WDTCN = 0xad;
cseg at 100h z = x + y;
; Disable watchdog timer }
Main: mov 0xFF, #0DEh
mov 0xFF, #0ADh
mov a, XL
add a, YL
mov XL, a
mov a, XH
addc a, YH The C version
mov XH, a
nop
end The assembly version
345
Compilation Process (Cygnal)
Use the #pragma CODE adder.c
compiler directive to get
assembly code generated
in LST file. compile look here in RAM
when debugging
adder.OBJ
adder.LST
build/make

adder.M51
Map file shows where variables Symbol Table in M51 file:
------ DO
are stored. One map file is
D:0008H SYMBOL x
generated per project. D:000AH SYMBOL y
D:000CH SYMBOL z
------- ENDDO
346
Bitwise Logic Instructions
Examples:
• AND & n = n & 0xF0;
• OR |
• XOR ^
• n = n & (0xFF << 4)
left shift <<
• right shift >>
• 1’s complement ~ n = n & ~(0xFF >> 4)

347
Example – Logic in Assembly and C
Main: void main (void) {
mov WDTCN, #0DEh char x;
mov WDTCN, #0ADh WDTCN = 0xDE;
xrl a, #0xF0 ; invert bits 7-4 WDTCN = 0xAD;
orl a, #0x0C ; set bits 3-2 x = x ^ 0xF0;
anl a, #0xFC ; reset bits 1-0 x = x | 0x0C;
mov P0, a ; send to port0 x = x & 0xFC;
P0 = x;
}

The assembly version The C version


348
Loop Statements - While
• While loop:
o while (condition) { statements }
o while condition is true, execute statements
o if there is only one statement, we can lose the {}
o Example: while (1) ; // loop forever

349
Loop Statements - For
• For statement:
o for (initialization; condition; increment)
{statements}
o initialization done before statement is executed
o condition is tested, if true, execute statements
o do increment step and go back and test
condition again
o repeat last two steps until condition is not true

350
Example (loop)
• for (n = 0; n<1000; n++)
o n++ means n = n + 1
• Be careful with signed integers!
o for (i=0; i < 33000; i++) LED = ~LED;
• Why is this an infinite loop?

351
do - while
• do
o statements
• while (expression);
• Test made at the bottom of the loop

352
Decision (if)
if (condition1)
{statements1}
else if (condition2)
{statements2}

else
{statementsn}
353
Decision (switch)
switch (expression) {
case const-expr: statements
case const-expr: statements
default: statements
}

354
Example
switch (unibble) { Need a statement like
case 0x00 : return (0xC0); “return” or “break”
or execution falls
case 0x01 : return (0xF9); through to the next
case (unlike VHDL)
case 0x02 : return (0xA4);
case 0x03 : return (0xC0);
default : return (0xFF);
}

355
C Extensions: Additional Keywords
For accessing SFRs

Specify where variables go in memory


356
Accessing Specific Memory

357
C Access to 8051 Memory

code: program
memory accessed
by movc @a + dptr data

bdata

idata
xdata

358
data
data char I; The C version
I =2;

mov I,#02h The assembly version

359
idata
idata char I; The C version
I =2;

mov R0,#I The assembly version


mov @R0,#02h

360
pdata
pdata char I; The C version
I =2;

mov a,#02h
mov R0,#I The assembly version
movx @R0,a

361
xdata
xdata char I; The C version
I =2;

mov dptr ,#I


mov a, #02h The assembly version
movx @dptr , a

362
code
code char I =2; The C version
data char c;
c=I;

mov dptr ,#I


clr a

movc a, @a+dptr The assembly version


mov c,a

363
C Extensions for 8051 (Cygnal)
• New data types:
o Example:
bit bit new_flag; //stored in 20-2F
sbit sbit LED = P1^6;
sfr sfr SP = 0x81; //stack pointer
sfr16 sfr16 DP = 0x82; // data pointer

364
C Data Types With Extensions

365
Declaring Variables in Memory

char data temp;


char idata varx;
int xdata array[100];
char code text[] = “Enter data”;

366
Interrupts

Specify register bank 2


void timer0 (void) interrupt 1 using 2 {
if (++interruptcnt == 4000) { /* count to 4000 */
second++; /* second counter */
interruptcnt = 0; /* clear int counter */
}
} 367
Other Interrupt Numbers

• Interrupt number is same as “Priority Order” in datasheet 368


In-line Assembly
• When it is more efficient, or easier, can
insert assembly code in C programs.
o #pragma asm
o put your assembly code here
o #pragma endasm

369
Compilation Process (Cygnal)
program.c .OBJ or .SRC can
be generated, not both
compile
no SRC with SRC
option option
program.LST program.OBJ program.SRC

build/make rename file

program.M51 program.asm

build/make assemble
program.OBJ
Must use this path for C programs with in-line assembly
It is also necessary to add #pragma SRC to code 370
Interfacing with C
• Example: Temperature Sensor program
o Configures the external oscillator
o Configures the ADC0 for temp. sensor
o Configures Port1 so LED can be used
o Configures Timer3 to synch the ADC0
o Uses ADC0 ISR to take temperature samples and
averages 256 of them and posts average to global
variable
o Main program compares average temp. to room
temp. and lights LED if temp is warmer.
o Temp_2.c
371
Converting to Real Values
• C makes it easier to implement equations
• Example: Temperature conversion
o For analog to digital conversion – assuming left justified:

ADC 0 / 16 Vref
V= 12

2 Gain
o The temperature sensor:

V − 0.776
TempC =
0.00286
Temperature Conversion

ADC 0 / 16 Vref
( 12
 ) − 0.776
TempC = 2 Gain
0.00286
Let Vref = 2.4V, Gain = 2

ADC 0 − 42380
TempC =
156
373
C for the Equation
ADC 0 − 42380
… Temp C =
156
unsigned int result, temperature;

result = ADC0; //read temperature
sensor
temperature = result - 42380;
temperature = temperature / 156;
* Must be careful about range of values expected
and variable types
374
Arrays in C
• Useful for storing data
temp_array[0]
temp_array[1]
temp_array[2]
type arr_name[dimension]
temp_array[3]
...
int temp_array[256] temp_array[253]
temp_array[254]
temp_array[255]

Array elements are stored in adjacent locations in


memory.
375
Pointers in C
• Pointers are variables that hold memory
addresses.
• Specified using * prefix.
o int *pntr; // defines a pointer, pntr
o pntr = &var; // assigns address of var to pntr
o Data char *s ; //ptr is stored in data memory
o Xdata int * number; //ptr is stored in xdata memory
o Char data * str ; // ptr to string in data
o Int xdata * numtab ; //ptr to int in xdata

376
Pointers and Arrays
Note: the name of an array is a pointer to the first element:
*temp_array is the same as temp_array[0]
So the following are the same:
temp_array[0]
n = *temp_array; temp_array[1]
temp_array[2]
n = temp_array[0]; temp_array[3]
...
and these are also the same: temp_array[253]
n = *(temp_array+5); temp_array[254]
temp_array[255]
n = temp_array[5]; 377
C for Large Projects
• Use functions to make programs modular
• Break project into separate files if the
programs get too large
• Use header (#include) files to hold
definitions used by several programs
• Keep main program short and easy to
follow
• Consider multi-tasking or multi-threaded
implementations 378
Functions
• The basis for modular structured
programming in C.

return-type function-name(argument declarations)


{
declarations and statements
}

379
Example – no return value or arguments
void SYSCLK_Init (void) {
// Delay counter
int i;
// Start external oscillator with 22.1184MHz crystal
OSCXCN = 0x67;
// Wait for XTLVLD blanking interval (>1ms)
for (i = 0; i < 256; i++) ;
// Wait for crystal osc. to settle
while (!(OSCXCN & 0x80)) ;
// Select external oscillator as SYSCLK
OSCICN = 0x88;
380
}
Example – with arguments
void Timer3_Init (int counts) {
// Stop timer, clear TF3, use SYSCLK as timebase
TMR3CN = 0x02;
// Init reload value
TMR3RL = -counts;
// Set to reload immediately
TMR3 = 0xffff;
// Disable interrupts
EIE2 &= ~0x01;
// Start timer
TMR3CN |= 0x04;
}
381
Example – with return value
char ascii_conv (char num) {
return num + 30;
}

382
Header Files
• Use to define global constants and variables
// 16-bit SFR Definitions for 'F02x
sfr16 TMR3RL = 0x92; // Timer3 reload value
sfr16 TMR3 = 0x94; // Timer3 counter
sfr16 ADC0 = 0xbe; // ADC0 data
sfr16 DAC0 = 0xd2; // DAC data
sfr16 DAC1 = 0xd5;
// Global CONSTANTS
#define SYSCLK 22118400 // SYSCLK frequency in Hz
sbit LED = P1^6; // LED='1' means ON
sbit SW1 = P3^7; // SW1='0' means switch pressed
#define MAX_DAC ((1<<12)-1) // Maximum value of the DAC register 12 bits
#define MAX_INTEGRAL (1L<<24) // Maximum value of the integral
// Function PROTOTYPES
void SYSCLK_Init (void);
void PORT_Init (void);
void ADC0_Init (void);
void DAC_Init (void);
void Timer3_Init (int counts);
void ADC0_ISR (void); 383
Multitasking and Multithreading
• Multitasking: Perception of multiple tasks being
executed simultaneously.
o Usually a feature of an operating system and tasks are
separate applications.
o Embedded systems are usually dedicated to one
application.
• Multithreading: Perception of multiple tasks
within a single application being executed.
o Example: Cygnal IDE colors code while echoing
characters you type.
384
Multitasking and Multithreading
A “thread”
void main (void) { void SYSCLK_Init (void){
long temperature; int i;
WDTCN = 0xde; OSCXCN = 0x67;
WDTCN = 0xad; for (i=0; i < 256 i++) ;
SYSCLK_Init(): while (!(OSCXCN & 0x80)) ;
PORT_Init (); OSCICN = 0x88; }
Timer3_Init (SYSCLK/SAMPLE_RATE);
AD0EN = 1; void PORT_Init (void) {
EA = 1; XBR0 = 0x04;
while (1) { XBR1 = 0x00;
temperature = result; XBR2 = 0x40;
if (temperature < 0xB230) LED = 0; P0MDOUT |= 0x01;
else LED = 1; P1MDOUT |= 0x40;}
} void Timer3_Init (int counts) {
} TMR3CN = 0x02;
TMR3RL = -counts;
TMR3 = 0xffff;
EIE2 &= ~0x01;
TMR3CN |= 0x04; }
385
Multi-tasking/threading
Implementations
• Cooperative multi-tasking – each application
runs for a short time and then yields control to
the next application.
• Timer-based multi-tasking – on each timer
interrupt, tasks are switched.
• When switching between tasks, state of processor
(internal registers, flags, etc) must be saved and
previous state from last task restored. This is the
“overhead” of multitasking. Also called “context
switching”. 386
Multithreading with Interrupts

Interrupt
Foreground thread Service
Main program Routine Background thread
reti

Subroutines
Interrupt
ret
Service
Routine Background thread

reti
387
Real-Time Operating Systems (RTOS)
• Usually a timer-based task switching system
that can guarantee a certain response time.
• Low level functions implement task
switching.
• High level functions create and terminate
threads or tasks.
• Each task might have its own software stack
for storing processor state.
388
Example – Switch/LED Program
#include <c8051F020.h>
#pragma SRC // Need this to generate .SRC file
void PORT_Init (void);
char Get_SW(void) {
#pragma ASM
mov a, P3
anl a, #80h ; mask all but P3.7
mov R7, a ; function value (char) returned in R7
#pragma ENDASM
}
void Set_LED(void) {
#pragma ASM Functions can be
setb P1.6
#pragma ENDASM implemented in assembly
}
void Clr_LED(void) {
language
#pragma ASM
clr P1.6
#pragma ENDASM
}
void PORT_Init (void){ XBR2 = 0x40; // Enable crossbar and enable P1.6 (LED) as push-pull output}
P1MDOUT |= 0x40; // enable P1.6 (LED) as push-pull output
}
389
Question?

390

You might also like