1Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Assembly Programming for
Mid‐Range PIC
2Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Producing Executable Code
Develop code on PC Edit / assemble / link / debug
Assembly Convert assembly language code to machine languageAbsolute (executable) code
Single module systemsReal (absolute) addresses
Relocatable (object) code Complex multiple module systemsRelative addresses
Linking Combine + convert multiple object modules to executable codeSet real addresses
Assembly Code
Executable Code
Assembly Code Executable
Code
Object Code
Assembler
AssemblerLinker
Assembly Code
Object Code
Assembler
Assembly
3Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Producing Executable Code
Develop code on PC Edit / assemble / compile / link / debug
CompileConvert C language code to object codeC compiler available for Mid-Range PICs and higher
Linking Combine + convert multiple object modules to executable codeSet real addresses
Assembly Code Executable
Code
Object Code
AssemblerLinker
Assembly Code
Object Code
Assembler
Compiling
C Code
Object Code
Compiler
LibraryCode
4Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
MPLAB
Text editorColorized formatting of PIC assembly code + directives
Assembler MPASM.EXE / MPASMWIN.EXE
Linker MPLINK.EXE
Library manager MPLIB.EXE
Creates library (.lib) from several assembler programsSimulator/Debugger
Simulates microcontroller on PCPermits (limited) testing and debugging
ProgrammerProgram microcontroller deviceRequires additional hardware
Integrated Development Environment (IDE)
5Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Elements of an Assembly ProgramInstructions
Assembly language instructions in PIC ISAAssembly language instruction ↔ machine language instruction
LabelsConstant
Symbolic literal
Variable Pointer to data register holding value
Line labelPointer to location of instruction wordGOTO label ⇒ GOTO address_of_instruction_at_label
DirectivesCommands to assembler executed at assembly timeExamples
Arithmetic operations on addresses and labelsAssembly configuration
6Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Program OrganizationAbsolute code
DirectivesInclude header filesSet up constants + variables + macros
Reset and interrupt code sectionsMain code section
Specify absolute (real) addresses of code sections Absolute addresses ⇒ direct addressing modes
Subroutine code sectionsEND directive
Relocatable codeSimilar to absolute codeDifferences
Variables defined in separate data sectionNo address specification for code sectionsDirect / indirect addressing permitted
7Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Assembler Input / Output Files
Generated byContentsExtensionFile
Assembler
Assembler (absolute code)
or Linker
(relocatable code)
Microchip
User
Relocatable object code
Listing of symbols
Binary executable file
Error listing
Program listing
Device‐specific definitions
Assembly program
.oObject File
.xrfCross Reference
.hex, .hxl, .hxhHex File
.errError File
.lstListing
.incInclude file
.asmSource
8Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Constants
Defining constantAssign value to symbolAssembler converts symbol to literalDirectives
equ — no reassignmentset — reassignment as constant
ExampleCONST1 equ 0xA5 ; assignBIT equ 3 ; assignprog1:
movlw CONST1 ; W ← A5haddlw BIT ; W ← 3 + W
Specifying constant values May be preceded by + or –
A'Z' 'Z'
ASCII
B'10100111'Binary
O'247' 247O
Octal
H'A7' 0xA7 0A7H
Hexadecimal
D'167' .'167'
Decimal
Symbolic literal — no change at run time
9Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Variables
Defining variableRelocatable code
Reserve memory space in data section
Absolute codeAssign pointer to symbolUse symbols as register name
Example (absolute)CONST1 equ 0xA5 ; assignREG1 equ 20h ; assignBIT equ 3 ; assignprog1:
movlw CONST1 ; W ← A5hmovwf REG1 ; REG1 (address 20h) ← Wbcf REG1, BIT ; REG1<BIT> = bit 3 in reg 20h ← 0
Pointer to data register holding value
10Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Operations on Constants
ExampleCONST1 equ 0xA5 ; assignREG1 equ 20h ; assignINDEX equ 4 ; assignBIT set 3 ; assign BIT ← 3BIT set BIT + INDEX ; reassign BIT ← 7prog1:
movlw CONST1 ; W ← A5hmovwf REG1 ; REG1 (address 20h) ← Wbcf REG1, BIT ; REG1<BIT> = bit 7 in reg 20h ← 0
Arithmetic at assembly time
11Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Operators on constantsEvaluated at assembly time
+ Addition A1 + A2 – Subtraction A1 – A2 * Multiplication A1 * A2 / Division A1/A2 % Modulo A1%A2
Evaluate arithmetically
~ NOT ~A1 & AND A1 & A2 | OR A1 | A2 ^ XOR A1 ^ A2 >> Right shift A1 >> 1 << Left shift A1 << 2
Evaluate bitwise
! NOT !A1 && AND A1 && A2 || OR A1 || A2 > Higher than A1 > A2 < Less than A1 < A2 > Higher or equal to A1 >= A2 < Less or equal to A1 <= A2 = Equal to A1 == A2 != Different than A1 != A2
Evaluate to TRUE = 1 or FALSE = 0
12Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Operators on Variable PointersEvaluated at assembly time
= Logic or arithmetic assignment var = 0 var = 0 ++ Increment var ++ var = var + 1 -- Decrement var -- var = var – 1 += Add and assign var += k var = var + k -= Subtract and assign var -= k var = var – k *= Multiply and assign var *= k var = var * k /= Divide and assign var /= k var = var / k %= Mod and assign var %= k var = var % k &= AND and assign var &= k var = var & k |= OR and assign var |= k var = var | k ^= XOR and assign var ^= k var = var ^ k >>= Right shift and assign var >>= k var = var >> k <<= Left shift and assign var <<= k var = var << k
Notevar = 0 equivalent to var set 0
13Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Define Block of ConstantsFor absolute code
Specify starting absolute addressDefines list of named symbols at sequential addressesUsed as variable pointers
Syntax cblock [expr]
label[:increment][,label[:increment]]endc
Examplecblock 0x20 ; name_0 ← 20hname_0, name_1 ; name_1 ← 21hname_2, name_3 ; name_2 ← 22h
endc ; name_3 ← 24h
14Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Address Operators and General Directives
movlw high label ; W ← 000.label<12:8>Address high bytehigh
movlw low label ; W ← label<7:0> Address low bytelow
goto $ ; loop in placeCurrent address$
ExampleOperationOperator
radix
processor
org
#include
list
Directive
org 20 ; set next instruction address ; 20h
org 4 ; set next instruction address 4 ; (interrupt section)
org 0 ; set next instruction address 0 ; (reset section)Assign address to
instruction in absolute coding
Start of code section
#include <file>
#include "file"
#include fileInclude file in source code
radix dec
processor 16f84a
list p = 16f84a, r = decDefine device and default number system
ExampleOperation
15Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Device Header File (Fragment); P16F84.INC Standard Header File, Version 2.00 Microchip Technology, Inc. ; This header file defines configurations, registers, and other useful bits of ; information for the PIC16F84 microcontroller. These names are taken to match ; the data sheets as closely as possible. ; = = = = = = = = = = = = = = = = = = = = = = = = = = ; Register Definitions ; = = = = = = = = = = = = = = = = = = = = = = = = = = W EQU H'0000' F EQU H'0001' ;----- Register Files------------------------------ INDF EQU H'0000' TMR0 EQU H'0001' PCL EQU H'0002' STATUS EQU H'0003' FSR EQU H'0004' PORTA EQU H'0005' PORTB EQU H'0006' : ;----- STATUS Bits ---------------------------------- IRP EQU H'0007' RP1 EQU H'0006' RP0 EQU H'0005' NOT_TO EQU H'0004' NOT_PD EQU H'0003' Z EQU H'0002' DC EQU H'0001' C EQU H'0000' ;----- INTCON Bits ---------------------------------- :
Special Function Registers (SFR) Not reserved namesDefined in header files
16Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Skeleton for Absolute Code — 1list p = 16f873 ; Declare device#include <p16f873.inc> ; include header file;; Define constants;DATA1 EQU 0x1DATA2 EQU 0x2;; Define variables;w_temp equ 0x20status_temp equ 0x21X equ 0x22Y equ 0x23
Alternative:cblock 0x20w_tempstatus_temp X, Y
0x20endc
17Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Skeleton for Absolute Code — 2;; Body of program;org 0x000 ; Reset vector addressmovlw high PP ; W ← 000.PP<12:8>movwf PCLATH ; PCLATH ← PP<12:8>goto PP ; PCL ← PP<7:0> = start of main
;
18Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Skeleton for Absolute Code — 3org 0x004 ; Interrupt vector addressmovwf w_temp ; w_temp ← W (no flags)movf STATUS, W ; W ← STATUS (write Z)bcf STATUS, RP0 ; Select bank 0movwf status_temp ; status_temp ← W = STATUS
; (no write Z); Interrupt Service Routine Here;bcf STATUS, RP0 ; Select bank 0movf status_temp, W ; Restore STATUS (write Z)movwf STATUS ; (no write Z)swapf w_temp, f ; swap nibbles to w_tempswapf w_temp, W ; re-swap nibbles to W
; (no write Z)retfie ; Return from interrupt
19Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Skeleton for Absolute Code — 4PP:clrf X ; zero variablesclrf Y
;; main program;; subroutine call;movlw high SR1 ; W ← 000.SR1<12:8>movwf PCLATH ; PCLATH ← SR1<12:8>call SR1 ; push PC
; PCL ← SR1<7:0>goto $ ; spin loop (jumps to here)
SR1:; code of subroutine SR1return ; Return to main
20Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Section Declarations for Relocatable Code
Syntax [label] idata [RAM_address]
Defaults label = .idataRAM_address set by linker
Example idata
LimitL dw 0LimitH dw D'300'Gain dw D'5'Flags res 1String db 'Hi there!'
Initialized data section
Data Directives
dbInserts data byte at next memory address
dwInserts 2 data bytes in little endian order
res nInserts n data 0 bytes
21Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Section Declarations for Relocatable Code
Syntax [label] udata [RAM_address]
Defaults label = .udataRAM_address set by linker
Example udata
Var1 res 1Double res 2
Uninitialized Data Section
Data Directive
res nreserves n data bytes
22Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Section Declarations for Relocatable Code
Syntax [label] udata_shr [RAM_address]
Registers shared across memoryValues copied to file address in all banks
Default label = .udata_shr
Example udata_shr
Var1 res 1Double res 2
Shared Uninitialized Data Section
Bank 3Bank 2Bank 1Bank 0
DoubleDoubleDoubleDouble
Var1Var1Var1Var1
23Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Section Declarations for Relocatable Code
Syntax[label] udata_ovr [RAM_address]
Registers declared in section overlayed Other udata_ovr sections with same name overwrite same spaceMultiple temporary variable sets declared at one memory location
Default label = .udata_ovr
Example Temps udata_ovr Temp1 res 1 Temp2 res 1;; work with Temp1, Temp2;Temps udata_ovr NewTemp1 res 1 ; reallocate location Temp1 NewTemp2 res 1 ; reallocate location Temp2
Overlayed Uninitialized Data Section
24Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Section Declarations for Relocatable Code
Syntax [label] code [RAM_address]
Defaults label = .codeRAM_address set by linker
Example RST CODE 0x0 ; placed at address 0x0
pagesel startgoto start
PGM CODE ; relocatable code sectionstart:clrwgoto $
CODE ; relocatable code section nop ; default section name .codeend
Code Section
Code Directivepagesel start
Generates code:movlw high start movwf PCLATH
25Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Skeleton for Relocatable Code — 1list p = 16f873 ; Declare device#include <p16f873.inc> ; include header file;; Define constants;DATA1 EQU 0x1DATA2 EQU 0x2;; Define variables;udata_shr ; data shared across banksw_temp res 1status_temp res 1X res 1Y res 1
26Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Skeleton for Relocatable Code — 2;; Body of program;Rst_vector code 0 ; Reset vector addresspagesel PPgoto PP
;Intr_vector code 4 ; Interrupt vector addressgoto SR_Int
;
27Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Skeleton for Relocatable Code — 3Intr_Prog code 5 ; ISRSR_Int:movwf w_temp ; w_temp ← W (no flags)movf STATUS, W ; W ← STATUS (write Z)bcf STATUS, RP0 ; Select bank 0movwf status_temp ; status_temp ← W = STATUS
; (no write Z); Interrupt Service Routine Here;bcf STATUS, RP0 ; Select bank 0movf status_temp, W ; Restore STATUS (write Z)movwf STATUS ; (no write Z)swapf w_temp, f ; swap nibbles to w_tempswapf w_temp, W ; re-swap nibbles to W
; (no write Z)retfie ; Return from interrupt
28Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Skeleton for Relocatable Code — 4Prog_Principal codePP:clrf X ; zero variablesclrf Y
;; main program;; subroutine call;pageselcall SR1goto $ ; spin loop (jumps to here)
Subroutines codeSR1:; code of subroutine SR1return ; Return to main
29Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Define — Single Line MacrosSyntax
#define name [string]
Text substitution name in assembly code replaced by stringPermits parameter substitution
Example #define length 20#define width 30#define depth 40#define circumference(X,Y,Z) (X + Y + Z):Size equ circumference(length, width, depth)
Size evaluates to 20+30+40 = 90
30Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
MacrosSyntax
macro_name macro [arg_def1, arg_def2,…][ local label [, label, label,…]]
; ; Body of macroinstruction ; endm
Optional argumentsarg_def1, arg_def2 local labels — local to macro definition
Call macro macro_name [arg1, arg2,…]
31Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Macro ExampleConvert macro HEXA, ASCII ; Declare macro local add30, add37, end_mac ; local labelsmovf HEXA, W ; HEXA ← Wsublw 9 ; W ← 9 - W
; C ← (W > 9)movf HEXA, W ; C not changedbtfsc STATUS, C ; if (C == 0){goto add30 ; W ← W + 37h
add37: ; }addlw 37h ; else {
goto end_mac ; W ← W + 30hadd30: ; }
addlw 30h end_mac:movwf ASCII ; ASCII ← Wendm ; End of macroConvert HX, ASC ; insert macro code here
C = 0
C != 0
32Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Macros for Register Save / RestorePUSH_MACRO MACRO ; Save register contentsMOVWF W_TEMP ; Temporary register ← WSWAPF STATUS,W ; W ← swap STATUS nibblesMOVWF STATUS_TEMP ; Temporary register ← STATUS
ENDM ; End this Macro
POP_MACRO MACRO ; Restore register contentsSWAPF STATUS_TEMP,W ; W ← swap STATUSMOVWF STATUS ; STATUS ← WSWAPF W_TEMP,F ; W_Temp ← swap W_TempSWAPF W_TEMP,W ; W ← swap W_Temp s
; no affect on STATUSENDM ; End this Macro
33Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Typical Interrupt Service Routine (ISR) — 1org ISR_ADDR ; store at ISR address
PUSH_MACRO ; save context registers W, STATUS
CLRF STATUS ; Bank0
; switch implementation in PIC assembly language
BTFSC PIR1, TMR1IF ; skip next if (PIR1<TMR1IF> == 1)
GOTO T1_INT ; go to Timer1 ISR
BTFSC PIR1, ADIF ; skip next if (PIR1<ADIF> == 1)
GOTO AD_INT ; go to A/D ISR
BTFSC PIR1, LCDIF ; skip next if (PIR1<LCDIF> == 1)
GOTO LCD_INT ; go to LCD ISR
BTFSC INTCON, RBIF ; skip next if (PIR1<RBIF> == 1)
GOTO PORTB_INT ; go to PortB ISR
GOTO INT_ERROR_LP1 ; default ISR
34Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Typical Interrupt Service Routine (ISR) — 2T1_INT ; Timer1 overflow routine
:BCF PIR1, TMR1IF ; Clear Timer1 overflow interrupt flagGOTO END_ISR ; Leave ISR
AD_INT ; Routine when A/D completes:BCF PIR1, ADIF ; Clear A/D interrupt flagGOTO END_ISR ; Leave ISR
LCD_INT ; LCD Frame routine: BCF PIR1, LCDIF ; Clear LCD interrupt flagGOTO END_ISR ; Leave ISR
PORTB_INT ; PortB change routine:
END_ISR ; Leave ISRPOP_MACRO ; Restore registersRETFIE ; Return and enable interrupts
35Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Accessing External ModulesImport Label
extern label [, label...]
Declare symbol Used in current module Defined as global in different module
Must appear before label used
Export Labelglobal label [, label...]
Declare symbol Defined in current module Available to other modules
Example; in module 1
global Var1, Var2global AddThree
;udata
Var1 res 1Var2 res 1
codeAddThree:
addlw 3return
; in module 2extern Var1, Var2extern AddThree
clrf Var1clrf Var2call AddThree
36Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Start MPLAB IDE
37Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Configure > Select Device
38Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Project > Project Wizard
Wizard Select PIC Device Select Language Tools
Save Project by Pathname Add Device Template File
39Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Build ProjectEither
Project > Build AllRight click on project name in Project Window > Build AllClick Build All icon on Project toolbar
Output window shows result of build processShould be no errors or warnings for default template file
CodeAdd constants / variables / code / directives / macros Rebuild
40Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Testing Code with SimulatorDebugger > Select Tool > MPLAB SIM
Debug toolbar opensDebugger > Reset > Processor Reset
Assembly code editor opensGreen arrow points to program start (main)
Step Into Run program in trace mode (single step)
41Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
View > WatchChoose + Add items to watch list
SFRs Symbols
42Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
BreakpointsSet breakpoint
Double-click on line of codeRight click > choose Set Breakpoint from menu
RunProgram stops before breakpoint
43Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
StopwatchAt breakpoint
Reports clock cyclesEstimates runtime
44Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Delay Timer with Timer0 — 1Internal RC oscillator
TCY = 4 × 1 / (4 MHz) = 1 μs = 0.001 ms1 ms = 1000 counts
PrescalePS<2:0> ← 010 for 1 / 8 division ⇒ 125 counts2 cycle delay in synchronizer ⇒ 123 counts
PresetTimer0 interrupts when FFh = 256 rolls over to 0Preset counter to 256 – 123 = 133
N ms delayAUX ← N for N × 1 ms delay
45Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Delay Timer with Timer0 — 2 List p = 16F873 include "P16F873.INC" AUX equ 0x20 ; Auxiliary variable InitTimer0: bcf INTCON, T0IE ; Disable Timer0 interrupt bsf STATUS, RP0 ; Bank 1 movlw 0xC2 ; Configure timer mode movwf OPTION_REG ; Prescaler = 8 bcf STATUS, RP0 ; Bank 0 clrf TMR0 ; TMR0 ← 0 bcf INTCON, T0IF ; Clear overflow flag return Del1ms: movlw .133 ; Preset value = 133 (decimal) movwf TMR0 ; TMR0 ← preset Del1ms_01: btfss INTCON, T0IF ; Skip next if (T0IF == 1) goto Del1ms_01 ; Keep waiting bcf INTCON, T0IF ; Clear T0IF = 0 return ; Return after 1 ms DelNms: movwf AUX ; AUX ← number of ms DelNms_01: ; Call Del1ms AUX times call Del1ms ; Wait 1 ms. decfsz AUX, f ; AUX-- Skip next if (AUX == 0) goto DemNms_01 ; Keep waiting return ; Return after AUX interations end
46Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Measure Interval Between External Pulses — 1Internal RC oscillator
TCY = 4 × 1 / (4 MHz) = 1 μs = 0.001 ms
Timer1Synchronous timer modePrescale ← 1 TMR1++ every microsecond
CPP1 in capture modeCapture values of Timer1
CCP1CON ← 00000101 (capture mode on rising edge)
Trigger at 2 external pulsesCCP1IF ← 1 on rising edge
Capture2 – Capture1 = interval (in microseconds)
47Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Measure Interval Between External Pulses — 2 List p = 16F873
include "P16F873.INC"
N1H equ 20h ; High byte of first capture
N1L equ 21h ; Low byte of first capture
NH equ 22h ; High byte of difference
NL equ 23h ; Low byte of difference
Init_capture: clrf T1CON ; Timer mode with prescaler = 1
clrf CCP1CON ; Reset module CCP1
bsf STATUS, RP0 ; Bank 1
bsf TRISC, 2 ; Set CCP1 pin as input
bcf PIE1, TMR1IE ; Disable Timer1 interrupt
bcf PIE1, CCP1IE ; Disable CCP1 interrupt
bcf STATUS, RP0 ; Bank 0
clrf PIR1 ; Clear interrupt flags
movlw 0x05 ; Capture mode on raising edge
movwf CCP1CON ;
bsf T1CON, TMR1ON ; Start Timer1
return
48Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Measure Interval Between External Pulses — 3Capture: bcf PIR1, CCP1IF ; Clear capture flag btfss PIR1, CCP1IF ; Skip next if (CCP1IF == 1) goto Capture bcf PIR1, CCP1I ; Clear capture indicator movf CCPR1L, W ; Store captured value in N1H and N1L movwf N1L movf CCPR1H, W movwf N1H Capture2: btfss PIR1, CCP1IF ; Skip next if (CCP1IF == 1) goto Capture2 bcf PIR1, CCP1IF ; Clear capture indicator movf N1L, W subwf CCPR1L, W ; Subtract captured values movwf NL btfss STATUS, C goto Subt1 goto Subt0 Subt1: decf CCPR1H, f Subt0: movf N1H, W subwf CCPR1H, W movwf NH return end
16‐bit arithmeticAH:AL = BH:BL – CH:CL
AL ← BL – CLif (C == 1) BH--AH ← BH – CH
49Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Real Time Clock (RTC) — 1Internal RC oscillator
TCY = 4 × 1 / (4 MHz) = 1 μs = 0.001 msTimer0
Timer0 interrupts when FFh = 256 rolls over to 0Prescale = 32Interrupt every 0.001 ms × 256 × 32 = 8.192 ms
Seconds1 second per clock tick(1 second / tick) / (8.192 ms / interrupt) = 122.07 interrupts / tick1 second = 122 interrupts
Minutes1 minute = 60 clock ticks
Hours1 hour = 60 minutes
Days1 day = 24 hours
50Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Real Time Clock (RTC) — 2
INT
51Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Real Time Clock (RTC) — 3 list p = 16f873 #include <p16f873.inc> TICKS equ 0x20 ; Ticks counter SEC equ 0x21 ; Seconds counter MIN equ 0x22 ; Minutes counter HOUR equ 0x23 ; Hours counter TEMP_W equ 0x24 TEMP_ST equ 0x25 org 0 goto init org 4 goto rtc init: clrf INTCON ; Disable interrupts bsf STATUS, RP0 ; Bank 1 movlw 0xC4 ; Prescaler 32 movwf OPTION_REG ; Assigned to Timer0 bcf STATUS, RP0 ; Bank 0 movlw 0 ; Count module = 256 movwf TMR0 ; in Timer0 movlw .122 ; Ticks per second movwf TICKS ; in tick counter clrf SEC ; Clear Seconds counter clrf MIN ; Clear Minutes counter clrf HOUR ; Clear Hour counter bsf INTCON, T0IE ; Enable Timer0 interrupt bsf INTCON, GIE ; Enable global interrupts
52Dr. Martin LandMid-Range PIC ProgrammingEmbedded Systems — Hadassah College — Spring 2011
Real Time Clock (RTC) — 4prog: nop goto prog ; Infinite loop rtc: bcf STATUS, RP0 ; Bank 0 PUSH_MACRO ; Save STATUS, TEMP_ST bcf INTCON, T0IF ; Clear overflow flag for Timer0 decfsz TICKS, f ; TICKS-- Skip next if (TICKS == 0) goto end_rtc rtc_sec: movlw .122 ; Re-init TICKS movwf TICKS incf SEC, f ; seconds++ movf SEC, W xorlw .60 ; Z ← 1 if (SEC == 60) btfsc STATUS, Z ; Skip next on (Z == 1) goto end_rtc rtc_min: clrf SEC ; Clear seconds incf MIN, f ; minutes++ movf MIN, W xorlw . 60 ; Z ← 1 if (MIN == 60) btfsc STATUS, Z ; Skip next on (Z == 1) goto end_rtc rtc_hour: clrf MIN ; Clear minutes incf HOUR, f ; hours++ movf HOUR, W xorlw .24 ; Z ← 1 if (HOUR == 60) btfsc STATUS, Z ; Skip next on (Z == 1) goto end_rtc rtc_day: clrf HOUR ; Clear hours end_rtc: POP_MACRO ; Retrieve STATUS, TEMP_ST retfie ; Return to interrupted program. end ; End of source code.