ee 315 microprocessors course notesee315.cankaya.edu.tr/uploads/files/ee 315 microprocessors course...
TRANSCRIPT
1
EE 315 MICROPROCESSORS COURSE NOTES
COURSE CONTENTS
1. Introduction What is microprocessor?
What is microcontroller?
General information about microcontrollers
Why PIC?
Why PIC16F84
What are required to program PIC?
Assembler program
PIC programmer hardware
PIC programmer software
2. PIC Hardware Types of PIC
Types of PIC Memories
3. PIC16F84 Pin view
Feeding voltage
Clock pins and clock oscillator types
Reset pins and reset circuit
I/O ports
Memory of PIC16F84
Program memory
RAM
W register
4. What is assembler PIC assembly language
PIC assembly language rules
Types of PIC assembly instructionss
How to write numbers and characters
PIC assembly instructions
5. PIC programming
Flow diagram symbols
Drawing the flow diagram
Writing the assembly program instructions
Compiling the programs (MPASM)
Writing of the programs on PIC
Using PICUP program
Implementing programmed PIC
Other files generated by MPASM
Include files
6. Data transfer and decision making
Use of W register
Decision making by bit testing
7. Loop editing Loop editing by using counter
Loop editing by making comparison
Status register
2
8. Time delaying and subprograms Loops with time delays
Subprograms
9. Bit shifting and logical process commands
Shifting left
Shifting right
COMF and SWAPF instructions
Logical process instructions
10. Arithmetic processes Arithmetic process instructions
8-bit addition
16-bit addition
8-bit subtraction
16-bit subtraction
11. Lookup tables What is lookup table?
Program counter
Step motor control
12. Interrupts What is interrupt?
INTCON register
Interrupt sources
Editing of interrupt subprogram
13. Hardware counters
What is hardware counter / Timer
TMR0 counter / Timer
Option Register
Properties of TMR0 counter
Watchdog timer
14. D/A and A/D conversion Digital/Analog converter
Analog/Digital converter
15. Read and Write procedures to EEPROM data memory
Properties of EEPROM data memory
Reading data from EEPROM memory
Writing data to EEPROM memory
Verification of writing procedure
16. Use of MPLAB MPLAB
MPSIM-PIC SIMULATOR
GRADING
HOMEWORKS 5%
LABS 20%
MID TERM 30%
FINAL EXAM 45%
3
Embedded systems overview
An embedded system is a computer system designed for specific control functions within a
larger system, often with real-time computing constraints. It is embedded as part of a
complete device often including hardware and mechanical parts.
A general-purpose computer, such as a personal computer (PC), is designed to be flexible and
to meet a wide range of end-user needs. Embedded systems control many devices in common
use today.
Portable devices (e.g. digital watches), MP3 players, traffic lights, factory controllers and so
on.
Example of an embedded system
ADSL modem/router. Labelled parts are microprocessor (4), RAM (6), and flash memory (7).
A “short list” of embedded systems
4
Processors
Different types of embedded processors
General Purpose – Pentium, Athelon, Intel, AMD
Micro-controllers – PIC (Microchip), 8051, MSP430 (TI)
Special Processors – TMS320 Series DSP (TI)
Application Specific Instruction-Set Processors (ASIPs)
General-Purpose Microprocessor
CPU (Central Processing Unit)
General-purpose microprocessors in personal computers are used for computation, text
editing, multimedia display, and communication over the Internet.
Programmable device used in a variety of applications from automobiles to cellular phones
and industrial process control.
General Microprocessors contain no RAM, ROM, I/O ports on the chip itself
Ex. Intel’s x86 family (8088, 8086, 80386, 80386, 80486, Pentium)
Motorola’s 680x0 family (68000, 68010, 68020, etc)
Microcontroller
A microcontroller has a CPU in addition to a fixed amount of RAM, ROM, I/O ports on one
single chip; this makes them ideal for applications in which cost and space are critical.
Micocontrollers are very widely used, finding applications in everything from toys to
automobiles to industrial applications.
Inside the Computer
5
Internal organization of computers
Internal Block Diagram of a CPU
Program counter: Points to the address of the next instruction to be executed.
Contents are placed on the address bus to find and fetch the desired instruction.
6
Some Terminology
Bit is a binary digit that can have the value 0 or 1
A byte defines as 8 bits
A nibble is half a byte
A word is one or two bytes
A kilobyte is 210
bytes (1024 bytes), the abbreviation K is most often used
Example: A floppy disk holding 356 Kbytes of data
A megabyte is 220
bytes (1024 Kbyte), it is exactly 1,048,576 bytes
A gigabyte is 230
bytes (1024 Mbyte)
A terabyte (TB) is 240
bytes (1024 Gbyte)
A petabyte (PB) is 250
bytes (1024 Tbyte)
•A exabyte (EB) is 260
bytes (1024 Pbyte)
Some background: Codes for Characters
Representing characters as digital data.
The ASCIIcode (American Standard Code for Information Interchange) is a 7-bit code for
Character data. Typically 8 bits are actually used with the 8th bit being zero or used for error
detection (parity checking).
8 bits = 1 Byte.
‘A’ = 01000001
‘&’ = 00100110
MEMORY TYPES
ROM (Read Only Memory): Type of memory that does not lose its contents when power is
turned off. It is also called nonvolatile memory. You can not write on ROM.
PROM (Programmable memory)
User programmable (one-time programmable)
If the information burned into PROM is wrong, it needs to be discarded since internal fuses
are blown permanently.
Special equipment needed: ROM burner or ROM programmer
EPROM (Erasable Programmable ROM)
7
Allows making changes in the contents of PROM after it is burned
One can program the memory chip and erase it many many times
Erasing its contents can take up to 20 minutes; the entire chip is erased
All EPROM chips have a window that is used to shine ultraviolet (UV) radiation to erase its
contens
Also referred to as UV-EPROM
EEPROM (Electrically Erasable ROM)
Method of erasing is electrical
Moreover, one can select which byte to be erased
Cost per bit is much higher than for UV-EPROM
Also known as Flash Memory
RAM (Random Access Memory)
RAM memory is called volatile memory since cutting off the power to the IC will mean the
loss of data.
Also referred to as R/WM (Read and Write Memory)
General Information for Microcontroller
Types of microcontroller produced by microchip
PIC12C508
PIC16C84
PIC16F84
PIC16C711
Type of microcontroller produced by Intel
MCS-51 8031AH
MCS-51 8051AH
MCS-51 8751AHP
MCS-51 8052AH
MCS-51 80C51FA
An Introduction to PIC microcontrollers
Advantages of PIC (Peripheral Interface Controller)
It is a RISC (Reduced Instruction Set Computer) design
Only thirty seven instructions
8
Its code is extremely efficient, allowing the PIC to run with typically less program memory
than its larger competitors.
It is low cost, high clock speed
Software is obtained free from Microchip or the Internet
WHY TO USE PIC16F84
PIC16F84 microcontroller’s memory is produced with flash technology.
When users make a mistake in the program, users have chance to rewrite again.
Cost effective use of the devices.
Requirements for PIC programming
A computer compatible IBM
A text editor
PIC assembler, MPASM (www.microchip.com, www.atlaskitap.com )
PIC programming hardware
PIC programming software
PIC microcontroller (PIC16F84) (PicUp)
Bredboard, power supply, digital voltmeter
PIC test card
The difference between a microcontroller and a microprocessor:
- µC intended as a single chip solution, µP requires external support chips (memory, interface)
- µC has on-chip non-volatile memory for program storage, µP does not.
- µC has more interface functions on-chip (serial interfaces, Analog-to-Digital conversion,
timers, etc.) than µP
- µC does not have virtual memory support (I.e, could not run Linux), while µP does.
- General purpose µPs are typically higher performance (clock speed, data width, instruction
set, cache) than µCs
µP vs µC
Microcontroller structure
9
The Central Processing Unit:
The CPU consists of an Arithmetic Logic Unit (ALU); that is the logic circuits that do the
arithmetic and logic operations as required by each program instruction, together with the
local storage registers.
Under the management of the control unit, program instructions are fetched from memory,
decoded and executed.
Memory:
-Memory holds the bit patterns which define the program. A program in this context can be
defined simply as the list of instructions.
-Memory holding software should ideally be as fast as the CPU, and normally uses
semiconductor technologies.
-Memory also holds data being processed by the program.
-Program memories appear as an array of cells, each holding a bit pattern.
The interface ports:
-Microprocessor or microcontroller must be able to interact with its environment.
- Any device such as a keyboard and screen may be read and controlled
Data highway:
-All the elements of computer are wired together with one common data highway, or bus.
- CPU acting as the master controller, all information flow is back and forward along this
shared wires.
-Although this is efficient, it does mean that only one thing can happen at any time.
- There could be problem with the use of a single data bus to communicate with everything,
e.g., CPU cannot be copying data to an output port at the same time as it is fetching down an
instruction for future execution.
10
Another architecture:
This architecture separates the shared memory into entirely separate Program and Data stores.
Each memory has its own Address bus and thus there is no interaction between a Program cell
and a Data cell’s address.
11
A snapshot of CPU executing the first instruction of a program whilst simultaneously fetching
down the second instruction.
Program Counter:
Instructions are normally stored sequentially in Program memory, and the Program Counter is
the counter register that keeps track of the current instruction word.
Instruction Register 1 (IR1):
The contents of the Program store cell pointed to by the Program Counter, that is the
instruction word n, is loaded into IR1 and held for processing during the next cycle.
Instruction Register 2 (IR2):
During the same cycle as instruction word n is being fetched, the previously fetched
instruction word n-1 in IR1 is moved into IR2 and feeds the instruction decoder.
Instruction Decoder: The ID is the “brain” of the CPU, deciphering the instruction word in IR2 and sending out the
appropriate sequence of signals to the execution unit as necessary to locate the operand in the
data store and to configure the ALU to its appropriate form.
File Address Register:
When the CPU wishes to access a cell (or File) in the data store, it places the File address in
the FAR.
File Data Register:
This is a bi-directional register which either:
- Holds the contents of an addressed File if the CPU is executing a Read cycle (movf 5,w).
- Holds the data that a CPU wishes to send out (Write) to an addressed File (movwf 6)
Working Register:
W is the ALU’s Working register, generally holding one of an instruction’s operands, either
source or destination.
Introduction to the PIC16F84 Microcontroller
The Microchip PIC (Programmable Interface Controller) family of microcontrollers was
introduced in 1989 by Arizona Microchip.
The second generation of this family was introduced in 1994, and the PIC16F84A is the latest
incarnation of one of the first introductions.
12
However, the core processor is similar to all these 14-bit family members and software is
identical. The newer PIC18FXXX 16-bit family members introduced in 1999 are upwards
compatible.
Physical View:
PIC16F84A PINOUT DESCRIPTION
13
PIC16F84 Features:
•DC to 20 MHz clock, 2.0 to 6.0 V operating voltage
•1 K Flash program memory
•68 bytes of Data Ram
•64 bytes of EEPROM
•35 instructions
•13 I/O pins including 4 sources of interrupts
•Programmable 8-bit counter/timer
PIC16F84 pins arranged by function
14
15
PIC16F84A BLOCK DIAGRAMM
MEMORY ORGANIZATION
16
PROGRAM MEMORY MAP AND STACK
PROGRAM MEMORY ORGANIZATION
17
PICF1684 fetch unit
18
PICF1684 Program Store
Fetch section
– The Program store (top left) holds 1,024 (1K) 14-bit instructions.
– A 13-bit Program Counter to address (point to) each instruction in turn.
– A 2-stage pipeline conducts instructions to the Instruction decoder.
– A Fetch unit characterized by:
A Program store holding the codes defining the instructions making up a program. Each
location comprises a 14-bit binary code specifying a single instruction.
A 13-bit Program counter which acts as an Instruction pointer addressing the instruction
currently being fetched into the pipeline.
The Program counter potentially can address up to 213
= 8K = 8, 192 instructions, although
the PIC16F84 has only 1,024 = 1K instruction capacity.
The Program counter normally increments up from instruction 1 at location h’000’, but can
skip or jump if commanded by a relevant instruction.
A Pipeline storing two 14-bit instructions. The top register holds the nth instruction just
fetched from the Program store. The bottom register outputs the previously fetched (n − 1)th
instruction and feeds the Instruction decoder.
19
The Instruction decoder which takes the (n − 1)th instruction and generates the sequence of
events in the Execute unit appropriate to the instruction.
PICF1684 Execute Unit
Execution section
– An 8-bit Working register holds a single-byte operand for the Arithmetic Logic Unit.
– A Status register holding status information from the ALU, such as any carry-out, and
switches.
– A Data store holding 68 general-purpose Files and other special-purpose Files, such as the
Status register, to be discussed.
– An Execute unit characterized by:
An 8-bit Arithmetic Logic Unit (ALU) to do the logic and number crunching.
20
An 8-bit Working register to hold one of the operands fed to the ALU and also serve as a
possible destination for the outcome of the operation.
A Status register which holds (amongst other things) the Carry and Zero flags, allowing the
programmer to test conditions regarding a past operation carried out by the ALU.
A Data store which holds up to (for the PIC16F84) 68 8-bit general-purpose operands
(variables) and also special-purpose registers; for example the Status register.
All registers in the Data store have addresses entirely different from the Program store and are
called Files; e.g. File 3 is the Status register.
21
Figure is a simplified model of the PIC16F84’s Data store.
Data store can be thought as a filing cabinet, with each folder holding one data byte.
There are two different types of folders in the cabinet.
Some of these Files are named and have special significance. These are known as Special-
Purpose Registers (SPRs).
The other unnamed Files can be given names by the programmer and used for general-
purpose storage. These are known as General-Purpose Registers (GPRs).
SPRs are used to control and monitor the state of the microcontroller.
PIC16F84 can hold 68 byte-sized general-purpose variables, addressed from File h’0C’
through File h’4F’. Other PICs generally have more storage, although even the largest PICs
have a maximum storage of 368 general purpose bytes.
PIC16F84 has two drawers in its filing cabinet, each drawer has a potential to hold 128 (27)
Files. The Programmer can move from one to the other drawers at will by setting or clearing
bit 5 in the Status register.
Each drawer is called a bank. This bit can be thought as the key to open the particular filing
drawer.
From the diagram you can see that this bit is called RP0. Actually the PIC16F84 makes very
little use of these banks.
All the GPRs are imaged in both banks; for example, File h’20’ and File h’A0’ are the same!
Input/Output ports and Peripheral devices.
– An 8-bit and 5-bit general purpose input/output port.
– An 8-bit Timer/counter.
– An EEPROM 64-byte non-volatile memory module.
PIC16F8X Family of Devices
22
23
24
25
SPECIAL FUNCTION REGISTER FILE SUMMARY
26
STATUS REGISTER (ADDRESS 03h,83h)
27
Introduction to the PIC16F84 MCU Software Objectives
•To introduce the basic idea of a program in the context of software for the PIC mid-range
family.
• To investigate the binary structure of a typical direct address instruction.
• To inspect the machine-code structure of a typical literal instruction.
• To examine the Move and Addition instructions.
• To introduce the concept of assembly-level symbolic coding and its translation to machine
code.
Binary structure of instructions
The first instruction movf NUM_1,w simply loads a copy of the contents of File 05 (called
NUM_1) into the Working register (connected to the ALU).
The second (addlw 4) adds the literal (constant) four to it, with the outcome still in the
Working register.
Finally movwf NUM_2 stores the contents of this Working register back up into the Data
store at location File 06.
28
29
30
31
32
INSTRUCTION DESCRIPTIONS
33
34
35
36
37
38
Comparison of Numbers and Logic Operations
Objectives
• To be able to compare two unsigned byte numbers for:
– Contents of W EQUAL TO contents of File.
– Contents of W HIGHER THAN contents of File.
– Contents of W LOWER THAN or equal to contents of File.
• To be able to test either W or contents of a File for zero.
• To investigate how the logic instructions NOT, AND and Inclusive-OR instructions are
used.
• As an example, consider the task of designing the software for a microcontroller system to
warn you when your fuel level drops to 5 litres or below.
• Mathematically you need to subtract five from the fuel reading.
• If the reading is higher than or equal to five then no borrow-out will be generated; e.g. 22 −
5 no Borrow.
• If the Fuel reading is, say, 3 then 3 − 5 Borrow.
• In the special case where the Fuel reading is 5 then 5 − 5 no Borrow and Zero.
• Based on this we have the following rules:
Subtract Number 1 from Number 2; i.e. Number 2 − Number 1:
1. IF Number 1 is lower than or equal to Number 2 THEN the C flag will be 1.
2. IF Number 1 is equal to Number 2 THEN the Z flag will be set to 1.
3. IF Number 1 is higher than Number 2 THEN the C flag will be 0.
39
PORTS AND PINS OF PIC16F84
TRISA and TRISB
• PORTA is controlled by TRISA
• PORTB is controlled by TRISB
A 0 in a TRIS bit makes the corresponding Port pin an Output.
A 1 in a TRIS bit makes the corresponding Port pin an Input.
To make PORTB’s pins RB0 and RB1 an output and the rest inputs you would need to set
TRISB to b’11111100’
Example
TRISA equ h’85’ ; The PortA shadow register lives in File h’85’
TRISB equ h’86’ ; The PortB shadow register lives in File h’86’
STATUS equ 03 ; The Status register is in File 03 and also in Bank1
RP0 equ 5 ; Bit 5 of which is the Bank Switching bit
bsf STATUS,RP0 ; Switch into Bank1
movlw b’11100’ ; Prepare to set up TRISA; RA[4:2] Inputs
movwf TRISA ; RA[1:0] = Outputs
movlw b’01111111’; Prepare to set up TRISB; RB[7] = Output
movwf TRISB ; RB[6:0] = Input
bcf STATUS,RP0; Switch into Bank0
40
Numbers in Program
Hexadecimal numbers:
- For address hexadecimal three: 0x03, 3, 03, 03h, h’03’
- For literal or constant FF: 0xFF, h’FF’
FF or FFh are not used for literals.
Binary numbers: b’0000110’
Decimal numbers: d’15’, .15
ASCII characters: ’A’
Comparison of Numbers
• An example to illustrate the principle:
A car electronic dashboard monitoring system can access the petrol level reading at PORTB
and:
• Is to turn on a Green LED connected to bit 0 of PORTA (RA0) IF the fuel level is more
than 10 litres.
• ELSE is to turn on a Red LED connected to bit 1 of PORTA (RA1) IF the level is more
than 5 litres.
• ELSE is to turn on a buzzer connected to RA2
Comparing two numbers by subtracting
41
; Comparing two numbers by subtracting
LIST P=16F84A
FUEL equ h’06’ ; Read the fuel in litres PORTB
DISPLAY equ 05 ; Display devices are connected to Port A
GREEN_LED equ 0 ; in which bit0 is connected to the Green LED
RED_LED equ 1 ; and bit1 is connected to the Red LED
BUZZER equ 2 ; and bit2 is connected to the Buzzer
STATUS equ 3 ; The Status register is File 3
C equ 0 ; and the Carry/NOT Borrow flag is bit 0
RP0 equ 5 ; and the bank switch is bit 5
TRISA equ h’85’ ; Direction register for PORTA is File h’85’
TRISB equ h’86’ ; and for Port B is File h’86’
; First set up the pins to either input or output -----------------------
MAIN
bsf STATUS,RP0 ; Change to Bank 1
movlw b’11000’ ; Make RA2, RA1, RA0 outputs
movwf TRISA
movlw b’11111111’; Make Port B all Inputs
movwf TRISB
bcf STATUS,RP0 ; Back to Bank 0
clrf DISPLAY ; Turn off all LEDs and Buzzer
NEXT ; Check IF higher or equal to 11 litres ---------------------------------
movf FUEL,w ; Copy Fuel reading into W
addlw -d’11’ ; Subtract 11; i.e. W = FUEL - 11
btfsc STATUS,C ; IF a Borrow (C = = 0) THEN lower than 11 litres
goto GREEN ; ELSE indicate Green
• ; Check for higher or equal to 6 litres ---------------------------------
• movf FUEL,w ; Copy Fuel reading into W
• addlw -6 ; Subtract 6; i.e. W = FUEL - 6
• btfsc STATUS,C ; IF a Borrow (C = = 0) THEN lower than 6 litres
• goto RED ; ELSE indicate Red
• ; Must be the buzzer! ---------------------------------------------------
• bsf DISPLAY,BUZZER ; Sound the Buzzer (Bit 2 of PORTA)
• goto NEXT
• RED
• bsf DISPLAY,RED_LED ; Light the Red LED (Bit 1)
• goto NEXT
• GREEN
• bsf DISPLAY,GREEN_LED ; Light the Green LED (Bit 0)
• .... ..... ; Next part of the program
42
Division can be implemented simply by repetitive subtraction.
• Example: Write a program to divide a number byte in W by 6, with the Quotient being in
File h’30’ and Remainder in File h’31’.
QUOTIENT equ h’30’ ; Quotient is to be in File h’30’
REMAINDER equ h’31’ ; Remainder is to be in File h’31’
STATUS equ 03 ; The Status register is File 03
C equ 0 ; The Carry flag is bit0
;Zero the loop count————————————————
DIV_6
clrf QUOTIENT ; Start with zero count
;Subtract six——————————————————-
LOOP
addlw -6 ; Take away six
;Test for a Borrow-out; exit loop IF true—————————
btfss STATUS,C ; IF Carry = = 1 THEN NO Borrow so skip
goto NEXT ; ELSE exit loop
;Increment loop count and repeat————————————
incf QUOTIENT,f ; Add one onto count
goto LOOP ; and do again
; Add back on the one six too many
NEXT
addlw 6 ; Add back on
movwf REMAINDER ; and copy to File h’31’
43
Branch instructions and looping
Objectives
• To review the bit test instructions (btfsz, btfss)
• To investigate branch instructions (DECFSZ, INCFSZ) and looping
• To discuss the Instruction cycle time for PIC
• To investigate the Logic Instructions
More examples for bit test instructions (btfss, btfsz)
Q. Define bit_1 of PORTA is input and bit_0 of PORTB is output. Write a program that when
button of RA1 is pressed led_0 turns on.
44
; ===prog_bit_test.asm===
LIST P=16F84A
PORTA EQU h’05’
PORTB EQU h’06’
STATUS EQU h’03’
TRISA EQU h’85’
TRISB EQU h’86’
CLRF PORTB; leds of PORTB are off
BSF STATUS, 5; Change to Bank 1
CLRF TRISB ; all pins of PORTB are output
MOVLW h’FF’;
MOVWF TRISA; all pins of PORTA are input
BCF STATUS, 5; Change to Bank 0
TEST_PORTA
BTFSC PORTA,1; test bit_1 of PORTA (If we press the button of PORTA ,PORTA_
bit_1=0)
GOTO TEST_PORTA; if PORTA_bit_1=1 , test again
BSF PORTB, 0; if PORTA_bit_1=0 , Set to 1 PORTB_bit_0
LOOP
GOTO LOOP
END
DECFSZ: decrement file register and skip next instructions if 0.
In this instruction, the fileReg is decremented, and if its content is zero, it skips the next
instruction.
DECFSZ fileReg, d
For example if file register address is h’31’ and destination is file register;
decfsz h’31’, f
INCFSZ: Increment file register and skip next instructions if 0.
In this instruction, the fileReg is incremented, and if its content is zero, it skips the next
instruction.
INCFSZ fileReg, d
For example if file register address is h’31’ and destination is file register;
incfsz h’31’, f
By placing the ‘’GOTO target’’ instruction, we can create a loop. The target address of the
‘’GOTO target’’ instruction is the beginning of the loop.
Exp_1. Write a program to (a) clear WREG and (b) add 3 to WREG ten times and place the
result in PORTB. Use the DECFSZ instruction to perform looping.
45
;this program adds value 3 to WREG ten times
LIST P=16F84A
PORTB EQU h’06’
COUNT EQU 0X25 ;use loc 25H for counter
MOVLW d’10’ ;WREG=10 for counter
MOVWF COUNT ;load the counter
MOVLW 0 ; WREG=0
AGAIN ADDLW 3 ; add 03 to WREG ( WREG=sum)
DECFSZ COUNT,F ; decrement counter, skip if count=0
GOTO AGAIN ; repeat until count becomes 0
MOVWF PORTB ; send sum to PORTB
LOOP GOTO LOOP
END
LOOP INSIDE A LOOP
•What is the maximum number of times that the loop in example?
Because location COUNT in fileReg is an 8-bit register, it can hold a maximum of FFH (255
decimal); therefore, the loop can be repeated a maximum of 255 times.
What happens if we want to repeat an action more times than 255? To do that, we use a loop
inside a loop, which is called a nested loop. In a nested loop, we use two registers to hold the
count.
Exp_2: Write a program to (a) lood the PORTB register with the value 55H, and (b)
complemet PORTB 700 times.
Solution: Becauce 700 is larger than 255 (the maximum capacity of any register), we use two
registers to hold the count.
46
;complement PORTB 700 times
LIST P=16F84A
PORTB EQU h’06’
R1 EQU 0X25 ;use loc 25H for counter_1
R2 EQU 0X26 ;use loc 26H for counter_2
COUNT_1 EQU d’10’ ; COUNT_1=10 for counter 1
COUNT_2 EQU d’70’ ; COUNT_2=70 for counter 2
MOVLW 55H ;WREG=55H
MOVWF PORTB ;PORTB=55H
MOVLW COUNT_1 ;WREG=10 outher loop count value
MOVWF R1 ;load 10 into loc 25H (outher loop count)
LOP_1 MOVLW COUNT_2 ;WREG=70 inner loop count value
MOVWF R2 ;load 70 into loc 26H (inner loop count)
LOP_2 COMF PORTB,f ;toggle PORTB
DECFSZ R2,f ; decrement counter, skip if count=0
GOTO LOP_2 ; repeat until count_2 becomes 0
DECFSZ R1,f ; decrement counter, skip if count=0
GOTO LOP_1 ; repeat until count_1 becomes 0
LOOP GOTO LOOP
END
Looping 100,000 times
•Because two registers give us a maximum value of 65025 (255x255=65025), we can use
three registers to get up to more than 16 million (224
) iterations.
•;complemet PORTB 100,000 times
• LIST P=16F84A
•PORTB EQU h’06’
•R1 EQU 0X25 ;use loc 25H for counter_1
•R2 EQU 0X26 ;use loc 26H for counter_2
•R3 EQU 0X27 ;use loc 27H for counter_3
•COUNT_1 EQU d’100’ ; COUNT_1=100 for counter 1
•COUNT_2 EQU d’100’ ; COUNT_2=100 for counter 2
•COUNT_3 EQU d’10’ ; COUNT_3=10 for counter 3
• MOVLW 55H ;WREG=55H
• MOVWF PORTB ;PORTB=55H
47
• MOVLW COUNT_3 ;WREG=10 outher loop count value
• MOVWF R3 ;load 10 into loc 27H (outher loop count)
•LOP_3 MOVLW COUNT_2 ;WREG=100 inner loop count value
• MOVWF R2 ;load 100 into loc 26H (inner loop count)
•LOP_2 MOVLW COUNT_1 ;WREG=100 inner loop count value
• MOVWF R1 ;load 100 into loc 25H (inner loop count)
•LOP_1 COMF PORTB,f
• DECFSZ R1,f ; decrement counter, skip if count=0
• GOTO LOP_1 ; repeat until count_1 becomes 0
• DECFSZ R2,f ; decrement counter, skip if count=0
• GOTO LOP_2 ; ;repeat until count _2 becomes 0
• DECFSZ R3,f ; decrement counter, skip if count=0
• GOTO LOP_3 ; ;repeat until count _3 becomes 0
•LOOP GOTO LOOP
• END
Instruction cycle time for PIC
• Instruction Cycles (Machine Cycles) is referred to a certain amount of time for the CPU to
execute an instruction.
• In PIC, the length of the instruction cycle depends on the frequency of the oscillator.
• In the PIC16, one instruction cycle consists of four
oscillator periods. Therefore, to calculate the instruction cycle for the PIC, we take ¼ of the
crystal frequency, then take its inverse.
• Most instructions take one instruction cycle to execute.
Exp: The following shows the crystal frequency for three different PIC-based system. Find
the period of the instruction cycle in each case.
(a) 4 MHz (b) 16 MHz (c) 20 MHz
Solution: (a) 4/4=1 MHz (internal frequency) ;instruction cycle time is 1/1MHz=1 µs
(b) 16/4=4 MHz (internal frequency) ;instruction cycle time is 1/4MHz=0.25 µs
(b) 20/4=5 MHz (internal frequency) ;instruction cycle time is 1/5MHz=0.2 µs
Some instructions take two instruction cycles to execute; these are:
GOTO
CALL
RETURN
RETLW
RETFIE
INCFSZ; if number of register is 0 take 2 instruction cycle, else take 1 instruction cycle.
DECFSZ ; if number of register is 0 take 2 instruction cycle, else take 1 instruction cycle.
BTFSC; if tested bit equal 0 take 2 instruction cycle, else take 1 instruction cycle.
BTFSS; if tested bit equal 1 take 2 instruction cycle, else take 1 instruction cycle.
48
Time delay for single loop
MOVLW h’01’ ; 1 cycle
MOVWF R1 ; 1 cycle
LOOP
DECFSZ R1 ; 1x0+2 (1x(N-1)+2)
GOTO LOOP ; 0 (2X(N-1))
TOTAL= 4 cycle
For 4 MHz oscillator frequency; total delay= 4us
Maximum time delay for single loop
Because of 8 bit register; maximum N=h’FF’=d’255’ ;
MOVLW h’FF’ ; 1 cycle
MOVWF R1 ; 1 cycle
LOOP
DECFSZ R1 ; 1x254+2 (1x(N-1)+2)
GOTO LOOP ; 2X254 (2X( N-1))
TOTAL= 766 cycle
For 4 MHz oscillator frequency; total delay= 766us
Instruction cycle number=1+1+1x(N-1)+2+2X(N-1)=3N+1
ICN=3N
Exp: Write a loop for 100 us time delay. (Oscillator frequency=10 MHz)
Internal frequency=10MHz/4=2,5 MHz
Instruction cycle time (ICT)=1/2,5MHz= 0,4 us
ICN=Time delay/ICT=100/0,4=250
ICN=3N+1=250
For N=82, ICN=3N+1=247
For three instruction cycle you can use instruction NOP (no operation)
MOVLW h’52’ ; 1 cycle (d’82’=h’52’)
MOVWF R1 ; 1 cycle
NOP ; 1 cycle
NOP ; 1 cycle
NOP ; 1 cycle
LOOP
DECFSZ R1 ,f ; 1x81+2 (1x(N-1)+2)
GOTO LOOP ; 2X81 (2X( N-1))
Total cycle=250 cycle
time delay=250*0,4us=100us
Time delay for double loop
DELAY
MOVLW h’FF’ ; 1 cycle
MOVWF R1 ; 1 cycle
LOP_1
MOVLW h’FF’ ;1xM (M=number in R1)
MOVWF R2 ; 1xM
49
LOP_2
DECFSZ R2,f ; 1xMxN (N=number in R2)
GOTO LOP_2 ; 2xMxN
DECFSZ R1,f ; 1xM
GOTO LOP_1 ; 2xM
RETURN ;2 cycle
total=196608 cycle (maximum number)
ICN=3xMxN
Exp: Write a program for 12 ms time delay. (Oscillator frequency=4 MHz)
Solution:
Internal frequency=4MHz/4=1 MHz
Instruction cycle time (ICT)=1/1 MHz= 1 us
ICN=Time delay/ICT=12ms/1us=12000
For single loop max ICN=766, you should use double loop.
For double loop ICN=3xMxN
If M=N, ICN=3M^2=12000
M=63.2, M=N=h’3F’
DELAY
MOVLW h’3F’ ; 1 cycle
MOVWF R1 ; 1 cycle
LOP_1
MOVLW h’3F’ ;1xM (M=number in R1)
MOVWF R2 ; 1xM
LOP_2
DECFSZ R2,f ; 1xMxN (N=number in R2)
GOTO LOP_2 ; 2xMxN
DECFSZ R1,f ; 1xM
GOTO LOP_1 ; 2xM
RETURN ;2 cycle
Logic Instructions
•Complement (NOT):
The byte contents of any specified File may be inverted using the comf instruction.
comf h’26’,w (or f)
50
AND
•The AND function gives a true output whenever all inputs are true.
•Another way of looking at this truth table is to regard the X input as a Control input and the
Y input as a data input.
• IF the Control input is 0 THEN the output is always 0.
• IF the Control input is 1 THEN:
– IF the Data input Y is 0 THEN the output is 0.
– IF the Data input Y is 1 THEN the output is 1.
That is f = Y.
1. ANDing an input with a 0 always gives a 0 output.
2. ANDing an input with a 1 does not change the logic value of the other input.
We can therefore use the AND function to zero bits. For example:
10101010
00001111
= 00001010
AND instructions
andlw :ANDs the contents of the Working register with an 8-bit literal constant; for example,
W = 11001110
andlw b’00000111’ ; clears the upper five bits of W
W = 00000110
andwf : ANDs the contents of the Working register with that of a File; with the outcome, as
usual, being either put in W or back in the File;
W = 00000111, F h’30’ =10011111
andwf h’30’,f ; clears the upper five bits of File h’30’
F h’30’= 00000111
51
•Another use of ANDing is to check the state of any bit or bits in a data; for example:
andlw b’00000011’ ; Check bits 0 & 1
btfsc STATUS,Z ; IF not both zero THEN skip
goto ALL_ZERO ; ELSE == 00, so go to ALL_ZERO routine
Q: Write program that will put a byte in PORTB showing which bits in both Files h’30’ and
h’31’ which are 1.
Inclusive OR
The Inclusive-OR function gives a true output whenever any input is true.
If X input as a Control input and the Y input as a data input,
• IF the Control input is 0 THEN:
– IF the Data input Y is 0 THEN the output is 0.
– IF the Data input Y is 1 THEN the output is 1.
That is f = Y.
• IF the Control input is 1 THEN the output is always 1.
1. ORing an input with a 0 does not change the logic value of the other input.
2. ORing an input with a 1 always gives a 1 output.
We can therefore use the OR function to set bits to 1.
For example:
10101010
+ 11111000
= 11111010
52
Iorlw: Inclusive-ORs the contents of the Working register with an 8-bit literal constant; for
example:
W=10000110
iorlw b’11100000’; sets to one the three upper bits of the Working register W= 11100110
Iorwf: Inclusive-ORs the contents of the Working register with that of a File; with the
outcome, as usual, being either put in W or back in the File; for example:
W= 11100000, F h’30’ =10010111
iorwf h’30’,f ;sets to one the upper three bits of File h’30’
F h’30’=11110111
Q: Write program that will put a byte in PORTB showing which bits in both Files h’30’ and
h’31’ which are 0.
Subroutines Objectives
• To examine the subroutine as the means of implementing a program module using the call
and return instructions.
• To describe the mechanism of the subroutine and its interaction with the stack.
• To show how parameters are passed to a subroutine.
Subroutine instructions Subroutines are often used to perform task that need to be performed frequently. This makes a
program more structured in addition to saving memory space. In PIC16F84, call and return
instructions are used for subroutines.
53
Subroutine calling
Stack Register
• The stack is read/write memory (RAM) used by the CPU to store some very critical
information temporarily. This information usually is an address, but it could be data as well.
• The 14-bit core PICs have a stack of eight 13-bit registers which are exclusively used to
hold subroutine return addresses. Remember that the Program counter is 13-bits wide to hold
the 13-bit addresses for the Program store. This structure, shown in following figure
In Figure the situation is shown after a call to a subroutine labelled DELAY_1MS. The
execution sequence of this call DELAY_1MS is:
1.Copy the 13-bit contents of the PC into the stack register pointed to by the Stack Pointer.
This will be the address of the instruction following the call instruction.
54
2. The Stack Pointer is decremented.
3. The destination address (which we assume is labelled DELAY_1MS), that is the location in
the Program store of the entry point instruction of the subroutine, overwrites the original state
of the Program counter. Effectively this causes the program execution to transfer to the
subroutine.
Apart from the pushing of the return address into the stack in steps 1 and 2, call acts exactly
like a plain goto. Thus call requires two instruction cycles for execution, as the pipeline needs
to be flushed to remove the next caller instruction which is already in situ.
The exit point from the subroutine should be a return instruction. This reverses the push
action of call and pulls the return address back out from the stack into the PC – as shown in
Fig. This also requires a flush of the Pipeline, and takes two cycles. The execution sequence
of return is:
1.Decrement the Stack Pointer.
2. Copy the address in the stack register pointed to by the Stack Pointer into the Program
Counter.
Example: Toggle all the bits of the PORTB continuously. Put a 0.5 s time delay in between
each issuing of data to PORTB. (Oscillator frequenc is 4 MHz)
Solution: for time delay;
Internal frequency=4MHz/4=1 MHz
Instruction cycle time (ICT)=1/1 MHz= 1 us
ICN=Time delay/ICT=0.5 s/1us=500000
For double loop we can use max. 196608 cycle
500000 cycle=499998+2=166666x3+2 (nop)
ICN=3xMxN
•If M=N, ICN=3M^2=166666=166665+1 (nop)
• M=235,7 M=N=h’EB’
delay subroutine DELAY
MOVLW h’EB’ ; 1 cycle
MOVWF R1 ; 1 cycle
LOOP_1
MOVLW h’EB’ ;1xM (M=number in R1)
MOVWF R2 ; 1xM
LOOP_2
DECFSZ R2,f ; 1xMxN (N=number in R2)
GOTO LOOP_2 ; 2xMxN
DECFSZ R1,f ; 1xM
GOTO LOOP_1 ; 2xM
RETURN ;2 cycle
total=166854 cycle
TOTAL DELAY= 166854*3=500562=0.5 s
55
; ------prog_subroutine_0.5ms------- LIST P=16F84A
INCLUDE ‘’P16F84A.INC’’
R1 EQU 0X25 ;use loc 25H for counter_1
R2 EQU 0X26 ;use loc 26H for counter_2
clrf PORTB
BSF STATUS,5
CLRF TRISB
BCF STATUS,5
TOGGLE
COMF PORTB,f ;toggle PORTB
CALL DELAY
CALL DELAY
CALL DELAY
GOTO TOGGLE
DELAY
MOVLW h’EB’ ;WREG=EB outer loop count value
MOVWF R1 ;load EB into loc 25H (outer loop count)
LOOP_1
MOVLW h’EB’ ;WREG=EB inner loop count value
MOVWF R2 ;load EB into loc 26H (inner loop count)
LOOP_2
DECFSZ R2,f ; decrement counter, skip if count=0
GOTO LOOP_2 ; repeat until count_2 becomes 0
DECFSZ R1,f ; decrement counter, skip if count=0
GOTO LOOP_1 ; repeat until count_1 becomes 0
RETURN
END
Example: Define bit_1 of PORTA is input and PORTB is output. Write a program that when
button of RA1 is pressed ten times, all leds of PORTB are on.
•; ------prog_TESTPORTA-------
• LIST P=16F84A
• INCLUDE ‘’P16F84A.INC’’
•R1 EQU h’0C’ ;use loc 0DH for counter_1
•R2 EQU h’0D’ ;use loc 0DH for counter_2
•MEM EQU h’0E’
• clrf PORTB
• BSF STATUS,5
• CLRF TRISB
• BSF TRISA,1
• BCF STATUS,5
• CLRF MEM
•AGAIN
• BTFSC PORTA,1
56
• GOTO AGAIN
• INCF MEM,f ;MEM=MEM+1
• MOVF MEM,W ;W=MEM
• SUBLW d’10’ ; W= 10-W
• BTFSC STATUS,2
• GOTO ON
• CALL DELAY
• GOTO AGAIN
•ON
• MOVLW h’FF’
• MOVWF PORTB
•LOOP GOTO LOOP
DELAY
• MOVLW h’FF’ ;WREG=EB outher loop count value
• MOVWF R1 ;load EB into loc 25H (outher loop count)
•LOOP_1
• MOVLW h’FF’ ;WREG=EB inner loop count value
• MOVWF R2 ;load EB into loc 26H (inner loop count)
•LOOP_2
• DECFSZ R2,f ; decrement counter, skip if count=0
• GOTO LOOP_2 ; repeat until count_2 becomes 0
• DECFSZ R1,f ; decrement counter, skip if count=0
• GOTO LOOP_1 ; repeat until count_1 becomes 0
• RETURN
• END
The XOR (Exclusive-OR)
This is a XOR gate.
•The switching algebra symbol for this operation is , i.e., 1 1 = 0 and 1 0 = 1.
57
XORWF: The content of register f is XOR’ed with the content of register W. The result is put
in W or back in the File. Z flag of status register is affected.
Syntax: XORWF f, d
EX-OR can also be used to see if two registers have the same value.
Exp: Read and test PORTA to see whether it has value b’00000110’. If it does, send 99H to
PORTB; otherwise, it stays cleared.
Solution: ...........
CLRF PORTB
MOVLW b’00000110’
test_PORTA
XORWF PORTA,f
BTFSS STATUS, 2
GOTO test_PORTA
CONT
MOVLW h’99’
MOVWF PORTB
LOOP
GOTO LOOP
END
XORLW: The content of W register is XOR’ed with the 8-bit literal k . The result is stored in
register W. Z flag of status register is affected.
Syntax: XORLW k
Another widely used application of EX-OR is to toggle the bits of an operand.
f xor 0 = f (all bits same)
f xor 1=f’ (toggle the all bits)
Exp: movlw b’11110000’
xorlw b’10000001’
movwf PORTB ; PORTB=01110001, bit_7 and bit_0 of WREG are toggled
Q: If the buttons connected RA0, RA2 and RA3 of PORTA are pressed, all leds of PORTB
are turned on.
Solution:
;=======EXP_XOR =======
LIST P=16F84A
INCLUDE ‘’P16F84A.INC’’
CLRF PORTB
58
BSF STATUS, 5 ; in BANK1
CLRF TRISB ;PORTB is output
MOVLW h’FF’
MOVWF TRISA ; PORTA is input
BCF STATUS, 5 ; in BANK0
TEST_PORTA
MOVLW b’00010010’ ; W=b’00010010’
XORWF PORTA,W ;W=PORTA xor W
BTFSS STATUS,2 ; Z=1?
GOTO TEST_PORTA ; if NO
ON
MOVLW h’FF’ ;if YES
MOVWF PORTB ;PORTB=FF
LOOP
GOTO LOOP
END
Arithmetic Operations
Addition of two 8-bit numbers: addition instructions are ADDLW and ADDWF
We can control the carry flag of status register after the addition.
If C=0, result includes max 8 bit data.
If C=1, result includes data greater than 8 bit.
Exp: Add h’4B’ and h’42’. Show the result at PORTB.
Solution:
LIST P=16F84A
INCLUDE ‘’P16F84A.INC’’
CLRF PORTB
BSF STATUS, 5 ; in BANK1
CLRF TRISB ;PORTB is output
BCF STATUS, 5 ; in BANK0
MOVLW h’4B’ ; W=h’4B’ , b’01001011
ADDLW h’42’ ; W=h’4B’+ h’42’
MOVWF PORTB ;PORTB=h’8D’ or b’10001101’ ,C=0
LOOP
GOTO LOOP
END
Addition of two 16-bit numbers:
If the numbers greater than 1 byte (8 bit), we can add these numbers using 16-bit addition.
When adding two 16-bit data operands, we need to be concerned with the propagation of a
carry from the lower byte to the higher byte. This is called multi-byte addition to distinguish it
from the addition of individual byte.
For example look at the addition of h’3CE7’+h’3B8D’
1
3C E7
+ 3B 8D
78 74
59
When the first byte is added, there is a carry (E7+8D=74, C=1). The carry is propagated to the
higher byte, which results in 3C+3B+1=78
Exp: Write a program to add two 16-bit numbers. The numbers are h’3CE7’ and h’ 3B8D’.
Show low byte of the result at PORTB. When bit_1 of PORTA (RA1) is pressed, show high
byte of the result at PORTB.
Solution: 2 byte (16-bit) numbers;
A=3CE7, B= 3B8D
Low byte of A (AL)=E7, High byte of A (AH)=3C
Low byte of B (BL)=8D, High byte of B (BH)=3B
;=======16-bit addition =======
LIST P=16F84A
INCLUDE ‘’P16F84A.INC’’
CLRF PORTB
BSF STATUS, 5 ; in BANK1
CLRF TRISB ;PORTB is output
MOVLW h’FF’
MOVWF TRISA ; PORTA is input
BCF STATUS, 5 ; in BANK0
AL EQU h’0C’ ; Address of AL
AH EQU h’0D’ ; Address of AH
BL EQU h’0E’ ; Address of BL
BH EQU h’0F’ ; Address of BH
BEGIN
MOVLW h’E7’ ; W=h’E7’
MOVWF AL ;AL=h’A3’
MOVLW h’3C’ ; W=h’3C’
MOVWF AH ;AH=h’3C’
MOVLW h’8D’ ; W=h’8D’
MOVWF BL ;BL=h’8D’
MOVLW h’3B’ ; W=h’3B’
MOVWF BH ;BH=h’3B’
ADD
MOVF AL,W ;W=AL
ADDWF BL,F ;BL=BL+W(AL)
BTFSC STATUS, 0 ;C=0 or 1?
INCF BH,F ;if C=1, BH=BH+1
MOVF AH,W ;W=AH
ADDWF BH,F ;BH=BH+W(AH)
SHOW_LOW_BYTE
MOVF BL,W ;W=BL
MOVWF PORTB ;show low byte at PORTB
TEST_RA1
BTFSC PORTA,1 ;RA1 is press
GOTO TEST_RA1 ;if NO
SHOW_HIGH_BYTE
60
MOVF BH,W ; if YES , W=BH
MOVWF PORTB ;show high byte at PORTB
LOOP
GOTO LOOP
END
Subtraction of two 8-bit numbers: Addition instructions are SUBLW and SUBWF
We can control the carry flag of status register after the subtraction.
•If C=1, result is positive.
•If C=0, result is negative.
Exp: Write a program to subtract h’5A’ - h’53’. Show the result at PORTB.
(C=1)
Solution: ;======8_bit subtraction====
LIST P=16F84A
INCLUDE ‘’P16F84A.INC’’
CLRF PORTB
BSF STATUS, 5 ; in BANK1
CLRF TRISB ;PORTB is output
BCF STATUS, 5 ; in BANK0
MOVLW h’5A’ ; W=h’5A’
MOVWF PORTB ;PORTB=5A
MOVLW h’53’ ; W=h’53’
SUBWF PORTB,F ;PORTB=PORTB (h’5A’ )-W(h’53’)
LOOP
GOTO LOOP
END
Exp: Write a program to subtract h’52’ - h’53’. Show the result at PORTB.
(C=0)
Solution: ;======8_bit subtraction====
LIST P=16F84A
INCLUDE ‘’P16F84A.INC’’
CLRF PORTB
BSF STATUS, 5 ; in BANK1
CLRF TRISB ;PORTB is output
BCF STATUS, 5 ; in BANK0
MOVLW h’52’ ; W=h’52’
MOVWF PORTB ;PORTB=52
MOVLW h’53’ ; W=h’53’
SUBWF PORTB,F ;PORTB=PORTB (h’52’ )-W(h’53’),result negative
COMF PORTB
INCF PORTB ;2’s complement os result,
LOOP
GOTO LOOP
END
61
Subtraction of two 16-bit numbers:
If the numbers greater than 1 byte (8 bit), we can subtract these numbers using 16-bit
subtraction. When subtracting two 16-bit data operands, we need to be concerned with the
propagation of a carry from the lower byte to the higher byte.
For example look at the subtraction of h’3CE7’-h’3B8D’
1
3C E7
- 3B 8D
01 5A
When the first byte is subtracted, there is a carry (E7-8D=59, C=1, positive). Subtract high
byte directly.
After the low byte subtraction; If C=0 subtract 1 from high byte of first number. And then
subtract higher bytes. And control the carry again. If C=1, show output directly. If C=0, take
2’s complement of output and show the result.
Exp: Write a program to subtract two 16-bit numbers. The numbers are h’3CE7’ and h’
3B8D’. Show low byte of the result at PORTB. When bit_1 of PORTA (RA1) is pressed,
show high byte of the result at PORTB.
Solution: 2 byte (16-bit) numbers;
A=3CE7, B= 3B8D
Low byte of A (AL)=E7, High byte of A (AH)=3C
Low byte of B (BL)=8D, High byte of B (BH)=3B
;=======16-bit SUBTRACTION =======
LIST P=16F84A
INCLUDE ‘’P16F84A.INC’’
CLRF PORTB
BSF STATUS, 5 ; in BANK1
CLRF TRISB ;PORTB is output
MOVLW h’FF’
MOVWF TRISA ; PORTA is input
BCF STATUS, 5 ; in BANK0
AL EQU h’0C’ ; Address of AL
AH EQU h’0D’ ; Address of AH
BL EQU h’0E’ ; Address of BL
BH EQU h’0F’ ; Address of BH
BEGIN
MOVLW h’E7’ ; W=h’E7’
MOVWF AL ;AL=h’A3’
MOVLW h’3C’ ; W=h’3C’
MOVWF AH ;AH=h’3C’
MOVLW h’8D’ ; W=h’8D’
MOVWF BL ;BL=h’8D’
MOVLW h’3B’ ; W=h’3B’
MOVWF BH ;BH=h’3B’
SUB
MOVF BL,W ;W=BL
SUBWF AL,F ;AL=AL-W(BL)
62
BTFSS STATUS, 0 ;C=0 ?
DECF AH,F ;if C=0, AH=AH-1
MOVF BH,W ;W=BH
SUBWF AH,F ;AH=AH-W(BH)
SHOW_LOW_BYTE
MOVF AL,W ;W=AL
MOVWF PORTB ;show low byte at PORTB
TEST_RA1
BTFSC PORTA,1 ;RA1 is pressed?
GOTO TEST_RA1 ;if NO
SHOW_HIGH_BYTE
MOVF AH,W ; if YES , W=AH
MOVWF PORTB ;show high byte at PORTB
LOOP
GOTO LOOP
END
ROTATE INSTRUCTIONS AND LOOKUP TABLE
Objectives • To investigate how the rotate instructions RLF, RRF and SWAPF are used.
• To describe the data serialization with example.
• To investigate the lookup table.
RLF instruction
RLF (rotate left file register): The 8 bits of the file register are rotated left one bit, the carry
(C) flag of STATUS register enters the LSB (least-significant bit) and MSB (most-significant
bit) moved to the C. After the rotation the result can be in file register or working register,
depending on the d bit.
Syntax:RLF f, d ;rotate file register left.
Exp:
MYREG EQU 0X20
BSF STATUS, C ;make C=1
MOVLW 0X15 ;WREG=h’15’= b’00010101’, C=0
MOVWF MYREG
RLF MYREG,F ; MYREG=00101011, C=0
RLF MYREG,F ; MYREG=01010110, C=0
RLF MYREG,F ; MYREG=10101100, C=0
RLF MYREG,F ; MYREG=01011000, C=1
RRF instruction RRF (rotate right file register): The 8 bits of the file register are rotated right one bit, the carry
(C) flag of STATUS register enters the MSB (most-significant bit) and LSB (least-significant
63
bit) moved to the C. After the rotation the result can be in file register or working register,
depending on the d bit.
Syntax: RRF f, d ;rotate file register right.
Exp:
MYREG EQU 0X20
BCF STATUS, C ;make C=0
MOVLW 0X26 ;WREG=h’26’= b’00100110’, C=0
MOVWF MYREG
RRF MYREG,F ; MYREG=00010011, C=0
RRF MYREG,F ; MYREG=00001001, C=1
RRF MYREG,F ; MYREG=10000100, C=1
RRF MYREG,F ; MYREG=11000010, C=0
DATA SERIALIZATION
Serializing data is one of the most widely used applications of the rotate instruction. We can
use rotate instruction to transfer a byte of data serially (one bit at a time).
Exp: Write a program to transfer value 41H serially (one bit at a time) via pin RB1 (bit_1 of
PORTB). Put one high at the start and put one low end of the data via pin RB2 . Send the LSB
first. Put delay between each issue.
SWAPF instruction SWAPF : Another useful instruction is the SWAPF instruction. It works on the file register. It
swaps the lower nibble and the higher nibble. In other words, the lower 4 bits are put into the
higher 4 bits, and the higher 4 bits are put into the lower 4 bits. The result can be in file
register or working register, depending on the d bit.
Syntax:SWAPF f, d ;rotate file register left.
Exp:
a)Find the contents of the MYREG register in the following code.
Solution:
a)
MYREG EQU 0X20
MOVLW 0X72 ;WREG=72
MOVWF MYREG ;MYREG=72
SWAPF MYREG,F ;MYREG=27
64
b) In the absence of a swapf instruction, how would you exchange the nibbles? Write a simple
program to show the process.
LOOKUP TABLE
Lookup table is used to convert the PIC output code for real-world applications. For example,
if PORTB is connected to the seven-segment display, we can control the seven-segment
display using the PIC. Firstly we should define the lookup table for seven-segment display.
Lookup table for seven-segment diplay
a
f b
g
e c
d
Hex.num output bits data in 7-segment pins number in 7-segment display
for PORTB
gfedcba
h’00’ h’3F’ 00111111 0
h’01’ h’06’ 00000110 1
h’02’ h’5B’ 01011011 2
h’03’ h’4F’ 01001111 3
h’04’ h’66’ 01100110 4
h’05’ h’6D’ 01101101 5
h’06’ h’7D’ 01111101 6
h’07’ h’07’ 00000111 7
h’08’ h’7F’ 01111111 8
h’09’ h’6F’ 01101111 9
h’0A’ h’77’ 01110111 A
h’0B’ h’7C’ 01111100 B
h’0C’ h’39’ 00111001 C
h’0D’ h’5E’ 01011110 D
h’0E’ h’79’ 01111001 E
h’0F’ h’71’ 01110001 F
NOKTA h’80’ 10000000 .
PROGRAM COUNTER
•A 13-bit Program counter which acts as an Instruction pointer addressing the instruction
currently being fetched into the pipeline. The Program counter potentially can address up to
2^13 = 8K = 8192 instructions, although the PIC16F84A has only 1,024 = 1K instruction
capacity. The Program counter normally increments up from instruction 1 at location h’000’,
but can skip or jump if commanded by a relevant instruction.
•Program counter (PC) is 13-bit; low 8-bit is PCL and high 5-bit is PCH. 10-bits are used for
PIC16F84A.
•PCLATH is used to write data to PCH
65
RETLW instruction RETLW (Return with literal in W); The working register is loaded with the 8-bit literal ‘k’.
The program counter is loaded from the top of the stack (the return address)
syntax: RETLW k ; W=k
Exp: Write a program to show ‘5’ in 7-segment display.
;=======show ‘5’ in7-segment display=======
LIST P=16F84A
INCLUDE ‘’P16F84A.INC’’
CLRF PORTB
BSF STATUS, 5 ; in BANK1
CLRF TRISB ;PORTB is output
BCF STATUS, 5 ; in BANK0
BEGIN
MOVLW h’05’ ; W=h’05’ (test number)
CALL LOOKUP_TABLE
MOVWF PORTB ;PORTB=6D
LOOP
GOTO LOOP
LOOKUP_TABLE
ADDWF PCL,F ;PCL=W(h’05’)
RETLW h’3F’
RETLW h’06’
RETLW h’5B’
RETLW h’4F’
RETLW h’66’
RETLW h’6D’ ;W=h’6D’
RETLW h’7D’
......
END
STEPPER MOTORS Objectives
•To investigate stepper motors.
•To describe how to interface a stepper motor to the PIC16 with lookup table.
STEPPER MOTORS
•A stepper motor is a widely used device that translates electrical pulses into mechanical
movement. Such as disk drivers, the stepper motor is used for position control.
•Stepper motors commonly have a permanent magnet rotor (also called the shaft) surrounded
by a stator.
66
•Another type of stepper motor have four stator windings that are paired with a center-tapped
common as shown in following figure.
•This type of stepper motor is commonly referred to as a unipolar stepper motor.
Step angle
•How much movement is associated with a single step? This depends on the internal
construction of the motor, in particular the number of teeth on the stator.
•The step angle is the minimum degree of rotation associated with a single step. Various
motors have different step angles.
•Following table shows some step angles for various motors. This is the total number of steps
needed to rotate one complete rotation or 360 degrees.(e.g., 180 steps x 2 degrees = 360)
67
Stepper Motor Step Angles
The stepper motor discussed here has total 4 leads. As the sequence of power is applied to
each stator winding, the rotor will rotate right with half step. (There are several widely used
sequences, each of which has a different degree of precision.)
•Step angle for full step: 90 degree (for 4-polars stepper motor)
•Step angle for half step: 45 degree (for 4-polars stepper motor)
68
8_step sequence (half step; 45 _degree angle)
STEP A B C D 1 1 0 0 0
2 1 0 0 1
3 0 0 0 1
4 0 1 0 1
5 0 1 0 0
6 0 1 1 0
7 0 0 1 0
8 1 0 1 0
9(1) equals step_1
If PORTB is connected to leads of step motor, we can design a lookup_table. For this
example,
RB0 is connected to A
RB1 is connected to B
RB2 is connected to C
RB3 is connected to D
Lookup_table;
For step_1, PORTB=‘0001’
For step_2, PORTB=‘1001’
For step_3, PORTB=‘1000’
For step_4, PORTB=‘1010’
For step_5, PORTB=‘0010’
For step_6, PORTB=‘0110’
For step_7, PORTB=‘0100’
For step_8, PORTB=‘0101’
Exp: Write a program to rotate stepper motor 45 degree angle. For each step first bit of
PORTA sould be pressed. (Stepper motor inputs are connected to outputs of PORTB from
RB0 to RB3.)
;=======rotate stepper motor 45 degree right=======
LIST P=16F84A
INCLUDE ‘’P16F84A.INC’’
COUNT1 EQU h’0C’
COUNT2 EQU h’0D’
STEP EQU h’0E’
CLRF PORTB
BSF STATUS, 5 ; in BANK1
MOVLW h’FF’ ;W=h’FF’
MOVWF TRISA ;PORTA is input
CLRF TRISB ;PORTB is output
BCF STATUS, 5 ; in BANK0
MOVLW h’FF’
MOVWF STEP ;STEP=h’FF’
69
TEST
BTFSC PORTA,1
GOTO TEST
BEGIN
INCF STEP,F ;STEP=h’FF’+1=h’00’
MOVF STEP,W ;W=STEP
ANDLW b’00000111’ ; high 5 bits of W equal 0
CALL STEP_TABLE ;select bit pattern
ANDLW b’00001111’ ; high 4 bits of W equal 0
MOVWF PORTB ;bit pattern is sent to PORTB
CALL DELAY
GOTO TEST
STEP_TABLE
ADDWF PCL,F ;PCL=W+PCL
RETLW b’0001’ ;step_1
RETLW b’1001’ ;step_2
RETLW b’1000’ ;step_3
RETLW b’1010’ ;step_4
RETLW b’0010’ ;step_5
RETLW b’0110’ ;step_6
RETLW b’0100’ ;step_7
RETLW b’0101’ ;step_8
DELAY
MOVLW h’FF’
MOVWF COUNT1
LOOP1
MOVLW h’FF’
MOVWF COUNT2
LOOP2
DECFSZ COUNT2,F
GOTO LOOP2
DECFSZ COUNT2,F
GOTO LOOP1
RETURN
END
Exp: Write a program to rotate stepper motor 45 degree angle. If we press the first bit of
PORTA stepper motor turns to left. If we press the first bit and second bit of PORTA stepper
motor turns to right.(Stepper motor inputs are connected to outputs of PORTB from RB0 to
RB3.)
;=======rotate stepper motor 45 degree right and left=======
LIST P=16F84A
INCLUDE ‘’P16F84A.INC’’
COUNT1 EQU h’0C’
COUNT2 EQU h’0D’
STEP EQU h’0E’
CLRF PORTB
BSF STATUS, 5 ; in BANK1
MOVLW h’FF’ ;W=h’FF’
MOVWF TRISA ;PORTA is input
70
CLRF TRISB ;PORTB is output
BCF STATUS, 5 ; in BANK0
MOVLW h’FF’
MOVWF STEP ;STEP=h’FF’
TEST
BTFSC PORTA,1
GOTO TEST
BTFSC PORTA,2
GOTO LEFT
RIGHT
INCF STEP,F ;STEP=h’FF’+1=h’00’
MOVF STEP,W ;W=STEP
ANDLW b’00000111’ ; high 5 bits of W equal 0
CALL STEP_TABLE ;select bit pattern
ANDLW b’00001111’ ; high 4 bits of W equal 0
MOVWF PORTB ;bit pattern is sent to PORTB
CALL DELAY
GOTO TEST
LEFT
DECF STEP,F ;STEP=h’FF’+1=h’00’
MOVF STEP,W ;W=STEP
ANDLW b’00000111’ ; high 5 bits of W equal 0
CALL STEP_TABLE ;select bit pattern
ANDLW b’00001111’ ; high 4 bits of W equal 0
MOVWF PORTB ;bit pattern is sent to PORTB
CALL DELAY
GOTO TEST
STEP_TABLE
ADDWF PCL,F ;PCL=W+PCL
RETLW b’0001’ ;step_1
RETLW b’1001’ ;step_2
RETLW b’1000’ ;step_3
RETLW b’1010’ ;step_4
RETLW b’0010’ ;step_5
RETLW b’0110’ ;step_6
RETLW b’0100’ ;step_7
RETLW b’0101’ ;step_8
DELAY
MOVLW h’FF’
MOVWF COUNT1
LOOP1
MOVLW h’FF’
MOVWF COUNT2
LOOP2
DECFSZ COUNT2,F
GOTO LOOP2
DECFSZ COUNT2,F
GOTO LOOP1
RETURN
END
71
INTERRUPTS
•A single microcontroller can serve several devices. In the interrupt method, whenever any
device needs the microcontroller’s service, the device notifies it by sending an interrupt
signal.
•Upon receiving an interrupt signal, the microcontroller stops whatever it is doing and serves
the device.
•The program associated with the interrupt is called the interrupt service routine (ISR).
Interrupt Service Routine
•For every interrupt, there must be a interrupt service routine (ISR), or interrupt handler.
When an interrupt is invoked, the microcontroller runs the interrupt service routine.
•Generally, in most microprocessors, for every interrupt there is a fixed location in memory
that holds the address of its ISR. In PIC16F84 there is only one location for the interrupt,
location 004 (program memory address of the location).
Steps in executing an interrupt
Upon activation of an interrupt, the microcontroller goes through the following steps:
1.It finishes the instruction it is executing and saves the address of the next instruction
(program counter) on the stack register.
2.It jumps to a fixed location in memory (address of the ISR)
3.The microcontroller gets the address of the ISR. It starts to execute the interrupt service
subroutine until it reaches the last instruction of the subroutine, which is RETFIE (return from
interrupt exit).
4.Upon executing the RETFIE instruction, the microcontroller returns to the place where it
was interrupted. First, it gets the program counter (PC) address from the stack then it starts to
execute from that address.
Sources of Interrupts in the PIC16F84A There are many sources of interrupts in PIC16F84, depending on which peripheral is
incorporated into the chip. The following are some of the most widely used sources of
interrupts in the PIC16F84.
1. External hardware interrupt. Pin RB0 (PORTB. 0) is for the external hardware interrupt
INT.
2. There is an interrupt for timer overflow. This is the software interrupt or internal interrupt
(when timer register TMR0 counts from h’FF’ to h’00’).
3. The PORTB-Change interrupt.( RB4,RB5,RB6, and RB7 can be used as interrupt sources.
If any bit is changed, interrupt occurs.)
4. EEPROM-interrupt.(It occurs when the writing process is finished)
INTCON REGISTER
The interrupts must be enabled by software in order for the microcontroller to respond to
them. The D7 of the INTCON (Interrupt Control) register is responsible for enabling and
disabling the interrupts globally. The following figure shows the INTCON register with all
interrupt control bits.
72
GIE (Global interrupt enable)
GIE=0, disables all interrupts.
GIE=1, interrupts are allowed to happen. Each interrupt source is anabled by setting the
corresponding interrupt enable bit.
EEIE (EEPROM interrupt enable)
EEIE=0, disables EEPROM interrupt
EEIE=1, enables EEPROM interrupt
TOIE (TMR0 interrupt enable)
TOIE=0, disables TMR0 overflow interrupt
TOIE=1, enables TMR0 overflow interrupt
INTE (external interrupt enable)
INTE=0, disables external interrupt
INTE=1, enables external interrupt
RBIE (PORTB interrupt enable for RB4,RB5,RB6,RB7)
RBIE=0, disables PORTB interrupt
RBIE=1, enables PORTB interrupt
These bits, along with the GIE, must be set high for an interrupt to be responded to. Upon
activition of the interrupt, the GIE bit is cleared by the PIC16 itself to make sure another
interrupt cannot interrupt the microcontroller while it is servicing the current one. At the end
of the ISR, the RETFIE instruction will make GIE=1 to allow another interrupt to come in.
FLAGS OF INTERRUPTS If TOIF =1 there is TMR0 interrupt .
If INTF=1 there is external interrupt.
If RBIF=1 tehre is PORTB interrupt.
;==GENERAL STRUCTURE FOR AN ASSEMBLY PROGRAM WITH EXTERNAL
INTERRUPT SUBROUTINE
LIST P=16F84A
INCLUDE "P16F84A.INC"
ORG 0X000 ; address of the main program
GOTO START
ORG 0X004 ;address of the ISR
GOTO MY_ISR
START
BSF INTCON, GIE ;global interrupt enable
BSF INTCON, INTE ; external interrupt enable
................
LOOP
GOTO LOOP
MY_ISR
BCF INTCON, INTF ; clear interrupt flag
.......................
RETFIE
END
73
External interrupts and OPTION register For external interrupts,
1. RB0 must be input.
2. INTE must be 1.
3. Bit_6 of the OPTION register (INTEDG) is the interrupt edge select bit;
If INTEDG= 1, interrupt occurs rising edge of the signal.
If INTEDG= 0, interrupt occurs falling edge of the signal.
Depends on the hardware, INTEDG must be 0 or 1.
** To protect the contents of the W register and STATUS register, interrupt subroutine should
be written as;
........
ORG h’004’
GOTO MY_ISR
........
MY_ISR
MOVWF SAVE_W ; SAVE_W=W_initial
SWAPF STATUS,W ;W=SWAP STATUS_initial MOVWF SAVE_S ; SAVE_S=SWAP
STATUS_initial
..........
SWAPF SAVE_S, W ;W=STATUS
MOVWF STATUS ;STATUS=STATUS_initial
SWAPF SAVE_W, F ;W=SWAP W_initial
SWAPF SAVE_W, W ;W=W_initial
RETFIE
Exp. Write a program that when RA1 is pressed, RB1 is on. If there is an interrupt from
RB0/INT (for falling edge), RB2 is toggled.
Exp: Trace the following program and write the output.
LIST P=16F84A
INCLUDE "P16F84A.INC"
ORG 0X000 ; address of the main program
GOTO START
ORG 0X004 ;address of the ISR
BTFSS PORTA,2
GOTO MY_ISR1
BTFSS PORTA,4
GOTO MY_ISR2
GOTO MY_ISR3
START
CLRF PORTB
BSF STATUS,RP0
CLRF TRISB
MOVLW h’FF’
MOVWF TRISA
74
BCF OPTION_REG,INTEDG
BCF STATUS,RP0
BCF INTCON,INTF
BSF INTCON, GIE ;global interrupt enable
BSF INTCON, INTE ; external interrupt enable
LOOP
GOTO LOOP
MY_ISR1
BCF INTCON, INTF ; clear interrupt flag
BSF PORTB,1
RETFIE
MY_ISR2
BCF INTCON, INTF ; clear interrupt flag
BSF PORTB,2
RETFIE
MY_ISR3
BCF INTCON, INTF ; clear interrupt flag
BSF PORTB,3
RETFIE
END
Exp: Write a program that checks all the interrupt sources and executes the related interrupt
subroutines.
LIST P=16F84A
INCLUDE "P16F84A.INC"
ORG 0X000 ; address of the main program
GOTO START
ORG 0X004 ;address of the ISR
BTFSC INTCON,INTF
GOTO MY_ISR_RB0_INT
BTFSC INTCON,RBIF
GOTO MY_ISR_RB
BTFSC INTCON,TOIF
GOTO MY_ISR_TO
GOTO MY_ISR_EE
START
BSF INTCON, GIE ;global interrupt enable
BSF INTCON, INTE ; external interrupt enable
BSF INTCON, RBIE ;PORTB_change interrupt enable
BSF INTCON, TOIE ; Timer overflow interrupt enable
BSF INTCON, EEIE ;eeprom interrupt enable
..............................
LOOP
GOTO LOOP
MY_ISR_RB0_INT
BCF INTCON, INTF ; clear interrupt flag
BSF PORTB,1
RETFIE
75
MY_ISR_RB
BCF INTCON, RBIF ; clear interrupt flag
BSF PORTB,2
RETFIE
MY_ISR_TO
BCF INTCON, TOIF ; clear interrupt flag
BSF PORTB,3
RETFIE
MY_ISR_EE
BSF PORTB,0
RETFIE
END
TIMERS & COUNTERS
TIMER PROGRAMMING
The PIC16F84 has two timers depending on the family member. They are referred to as Timer
0 and Watchdog timer (WDT). they can be used either as timers to generate a time delay or as
counters to count events happening outside the microcontroller.
Every timer needs a clock pulse to tick. The clock source can be internal or external. If we use
the internal clock source, then 1/4th of the frequency of the crystal oscillator on the OSC1
(Fosc/4) pin is fed into the timer. Therefore it is used for time delay generation and for that
reason is called a timer.
By choosing the external clock option, we feed pulses through one of the PIC16’s pins: this is
called a counter.
TIMER 0 (TMR0) register
TMR0 is an 8-bit special function register in the RAM. It has the following features;
•8-bit timer/counter
•Readable and writable
•It has prescaler value
•Internal or external clock can be selected
•Edge can be selected for external clock (rising or falling edge)
•Interrupt occurs when TMR0 counts from h’FF’ to h’00’ (Timer overflow interrupt)
OPTION REGISTER
•It is an 8-bit special function register in the RAM. It controls the prescaler value of TMR0
and WDT. Also it controls the edge of the external interrupt signal and clock signal. The
following figure shows the OPTION register with all control bits.
76
TOCS: TMR0 clock source select bit
1=External clock from RA4/TOCK1
0=Internal clock (Fosc/4 from OSC1)
TOSE: TMR0 source edge select bit
1= Increment on H-to-L transition on RA4/TOCK1
0= Increment on L-to-H transition on RA4/TOCK1
PSA: Prescaler assignment bit,
1=Prescaler is assigned to the WDT
0=Prescaler is assigned to the TMR0
Prescaler value for TMR0 and WDT
TMR0 or WDT rate determines the increment period. If TMR0=1/2, TMR0 increases every 2
instruction cycle. If TMR0=1/128, TMR0 increases every 128 instruction cycle.
Exp:If prescaler value is b’000’, what is the increment period of TMR0 and maximum
interrupt delay. (Oscillator frequency 4 MHz)
Sol: internal frequency=4MHz/4=1MHz
ICT (Instruction cycle time)=1/1MHz=1us
Prescaler value=000, TMR0_rate=1/2
IP(Increment period)=2x1us=2us
Timer overflow Interrupt occurs when TMR0 counts from h’FF’ to h’00’. There are 256
numbers between h’00’ to h’FF’ for maximum interrupt delay.
ID(Interrupt delay)=IPx256=2usx256=512us
Exp: To generate 1.28ms interrupt delay, what will be the first number of the
TMR0.(Fosc=4MHz, Prescaler=110)
Sol: Internal frequency=4MHz/4=1MHz
ICT (Instruction cycle time)=1/1MHz=1us
For 1.28ms ID, 1.28ms/1us=1280 instruction.
Prescaler=110; TMR0 increases every 128 instruction cycle. 1280 /128=10 ,
To create 1.28ms interrupt delay, TMR0 should count 10 number.
Timer overflow Interrupt occurs when TMR0 count from h’FF’ to h’00’. 256-10=246;First
number of the TMR0=246.
77
Exp: Write a program to make the flash the bit_0 of PORTB. Use TMR0 for delay between
each flash. Signal source is the internal clock and TMR0_rate=1/256.
TMR0_INTERRUPT
•Exp: Write a program to increment the value of PORTB at each timer overflow. (Use TMR0
interrupt)
WATCHDOG TIMER
The primary function of the Watchdog Timer (WDT) is to reset the microcontroller, in the
event of a software malfunction, by resetting the device if it has not been cleared in software.
It can also be used to wake the device from Sleep mode.
The WDT is a free-running timer which uses the low-power RC oscillator and requires no
external components. Therefore, the WDT will continue to operate even if the system’s
primary clock source (e.g., the crystal oscillator) is stopped under normal operation (e.g., in
Sleep mode)
WDT OPERATION
When enabled, the WDT will increment until it overflows or “times out”.
A WDT time-out will force a device Reset, except during Sleep modes.
To prevent a WDT Time-out Reset, the user must periodically clear the Watchdog Timer
using the instructions, CLRWDT.
If the WDT times out during Sleep modes, the device will wake-up and continue code
execution from where the CLRWDT instruction was executed.
In either case, the TO_bit (4_bit of STATUS register) will be set to indicate that the device
Reset or wake-up event was due to a WDT time-out.
If the WDT wakes the CPU from Sleep mode, the SLEEP status bit (bit_3 of status register)
will also be set to indicate that the device was previously in a Power-Saving mode
STATUS REGISTER
TO:Time out bit
1= When PIC is energized or CLRWDT is executed.
0= When WDT overflow occurs.
PD: Power down bit
1=When PIC is energized or CLRWDT is executed.
0= When SLEEP command is executed.
78
OPTION REGISTER
•It is an 8-bit special function register in the RAM. It controls the prescaler value of TMR0
and WDT. The following figure shows the OPTION register with WDT control bits.
TOCS: TMR0 clock source select bit
1=External clock from RA4/TOCK1
0=Internal clock (Fosc/4 from OSC1)
TOSE: TMR0 source edge select bit
1= Increment on H-to-L transition on RA4/TOCK1
0= Increment on L-to-H transition on RA4/TOCK1
PSA: Prescaler assignment bit,
1=Prescaler is assigned to the WDT
0=Prescaler is assigned to the TMR0
Prescaler value for TMR0 and WDT
With no prescaler, time-out period of the WDT is 18ms. The table shows the bit assignments
with the division rates for the WDT to time out. For exp; 1/128 WDT_rate, time_out period=
128*18ms=2,3 second.
Exp: If presclalar value is b’100’, what is the time out period of WDT.
Sol:
Time out occurs when WDT counts from h’FF’ to h’00’. This takes 18 ms with no prescaler.
If presclalar value is b’100’, WDT_rate= 1/16 (from the table)
Time out period= 16*18ms= 288 ms.
Exp: Write a program to increment the value of PORTB from 00. Every 1152 ms, PORTB
get started counting again from 00.
79
EEPROM DATA MEMORY
EEPROM DATA MEMORY
The EEPROM data memory is readable and writable during normal operation. This memory
is not directly mapped in the register file space. It is indirectly addressed through the Special
Function Registers. There are four SFRs used to read and write this memory. These registers
are:
• EECON1
• EECON2 (not a physically implemented register)
• EEDATA
• EEADR
EEDATA holds the 8-bit data for read/write, and EEADR holds the address of the EEPROM
location being accessed. EECON1 is used to control read/write operation. EECON2 is used
when writing something to EEPROM.
PIC16F84A devices have 64 bytes of data EEPROM with an address range from 0Oh to 3Fh.
The EEPROM data memory allows byte read and write. A byte write automatically erases the
location and writes the new data (erase before write).
80
EECON1 REGISTER (ADDRESS 88h)
bit 7-5 Unimplemented: Read as '0'
bit 4 EEIF:EEPROM Write Operation Interrupt Flag bit
1 = The write operation completed (must be cleared in software)
0 = The write operation is not complete or has not been started
bit 3 WRERR: EEPROM Error Flag bit
1= A write operation is prematurely terminated (any MCLR Reset or any WDT Reset during
normal operation)
0 = The write operation completed
bit 2 WREN: EEPROM Write Enable bit
1= Allows write cycles
0= Inhibits write to the EEPROM
bit 1 WR: Write Control bit
1= Initiates a write cycle. The bit is cleared by hardware once write is complete. The WR bit
can only be set (not cleared) in software.
0= Write cycle to the EEPROM is complete
bit 0 RD: Read Control bit
1= Initiates an EEPROM read RD is cleared in hardware. The RD bit can only be set (not
cleared) in software.
0 = Does not initiate an EEPROM read
81
Reading the EEPROM Data Memory
To read a data memory location, the user must write the address to the EEADR register and
then set control bit RD (EECON1<0>). The data is available, in the very next cycle, in the
EEDATA register; therefore, it can be read in the next instruction. EEDATA will hold this
value until another read or until it is written to by the user (during a write operation).
Exp:
BCF STATUS, RP0 ; Bank 0
MOVLW CONFIG_ADDR ;
MOVWF EEADR ; Address to read
BSF STATUS, RP0 ; Bank 1
BSF EECON1, RD ; EE Read
BCF STATUS, RP0 ; Bank 0
MOVF EEDATA, W ; W = EEDATA
MOVWF PORTB ; PORTB = EEDATA
Writing to the EEPROM Data Memory
To write an EEPROM data location, the user must first write the address to the EEADR
register and the data to the EEDATA register. Then the user must follow a specific sequence
to initiate the write for each byte.
Exp:(Bold part is the required sequence)
BSF STATUS, RP0 ; Bank 1
BCF INTCON, GIE ; Disable INTs.
BSF EECON1, WREN ; Enable Write
MOVLW 55h ;
MOVWF EECON2 ; Write 55h
MOVLW AAh ;
MOVWF EECON2 ; Write AAh
BSF EECON1,WR ; Set WR bit begin write BSF INTCON, GIE ; Enable INTs
Additionally, the WREN bit in EECON1 must be set to enable write. This mechanism
prevents accidental writes to data EEPROM due to errant (unexpected) code exe- cution (i.e.,
lost programs). The user should keep the WREN bit clear at all times, except when updating
EEPROM. The WREN bit is not cleared by hardware.
At the completion of the write cycle, the WR bit is cleared in hardware and the EE Write
Complete Interrupt Flag bit (EEIF) is set. The user can either enable this interrupt or poll this
bit. EEIF must be cleared by software.
Exp: Write h’E3’ to location 0X03 of EEPROM.
MOVLW 0X03
MOVWF EEADR
MOVLW h’E3’
MOVWF EEDATA
BSF STATUS, RP0 ; Bank 1
BCF INTCON, GIE ; Disable INTs.
82
BSF EECON1, WREN ; Enable Write
MOVLW 55h ;
MOVWF EECON2 ; Write 55h
MOVLW AAh ;
MOVWF EECON2 ; Write AAh
BSF EECON1,WR ; Set WR bit begin write
BSF INTCON, GIE ; Enable INTs
Program: If RA1 is pressed, write h’8F’ to location 0X01 of EEPROM, If RA2 is pressed,
write h’3D’ to location 0X01of EEPROM, If RA4 is pressed, show the data of EEPROM
(location 0X01) to PORTB.