Timing and Counting. USING PIC® MICROCONTROLLERS

1,595 237 21MB

English Pages 225 Year 2002

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

Timing and Counting. USING PIC® MICROCONTROLLERS

Citation preview

-...r-

FROM

David Benson

USING PIC® MICROCONTROLLERS

Tirne'n and Count'n

USING PIC® MICROCONTROLLERS

FROM

DAVID BENSON VERSION 2.0

NOTICE The material presented in this book is for the education and amusement of students, hobbyists, technicians and engineers. Every effort has been made to assure the accuracy of this information and its suitability for this purpose. Square 1 Electronics and the author assume no responsibility for the suitability of this information for any application nor do we assume any liability resulting from use of this information. No patent liability is assumed for use of the information contained herein. All rights reserved. No part of this manual shall be reproduced or transmitted by any means (including photo copying) without written permission from Square 1 Electronics and the author. Copyright © 1999 and 2002 David Benson

TRADEMARKS Registered trademarks of Microchip Technology, Inc : PIC MPLAB MPASM MPSIM

PUBLISHER Square 1 Electronics P.O. Box 501 Kelseyville,CA 95451

U.S.A.

Voice (707)2 79-8881 FAX (70 7)279-8883 EMAIL sqone@pacific .net http://www.sq-1.com

USING PIC® MICROCONTROLLERS FROM

PREFACE

1

INTRODUCTION

3

TEST EQUIPMENT FOR TIMING AND COUNTING EXPERIMENTS

4

Test equipment for detecting a short single pulse and measuring it's width Pulse generator - 32 microseconds Pulse generator - 128 microseconds Pulse generator - 2000 microseconds Pulse generator - 65280 microseconds Test equipment for generating a frequency output

4

10 11 11 14 17

USING TIMER 1, TIMER 2 AND THE CAPTUREICOMPARElPWM (CCP) MODULE 20

PIC16F870 test circuit Before we take off TMR2: 8-bit timer TMR2 description How to choose/select mode of operation Interrupts TMR2 applications Free running mode (via TMR2 interrupt) Free running mode (via period register) TMR1: 16-bit timer/counter and capture/compare module TMR1/CCP module simplified TMR1 description CCP module - capture mode CCP module - compare mode CCP module - PWM mode

20 25 26 26 27 27 28 28 32 36 36 38 40 41 41

CCP1 pin 42 How to choose/select mode of operation 42 T1CON register CCP1CON register Interrupts 43 Reading and writing TMR1 43 Long time intervals 44 Controlling the CCP1 pin in compare mode 44 More than one way to do timing stuff 45 Timing and counting experiments 46 Free running output (via TMR1 interrupt) 46 Event counting (via TMR1) 50 Count events, read TMR1 contents 50 Capture TMR1 count when external event occurs 53 Count events up to predetermined number and generate an output (compare) 57 Single time interval output (via TMR1 and CCP, compare mode) 61 Start TMR1, auto end 61 500 milliseconds 61 128 microseconds 65 Free running output (via TMR1 and CCP, compare mode) 67 Clear TMR1 each cycle 67 Free running TMR1, add interval value to compare register each cycle 71 Time measurement (period/interval/time between events) (via TMR1 read) (interval input via port pin) 76 (via TMR1 and CCP, capture mode) (interval input via CCP1 pin, two captures, subtract) 81 Frequency measurement (via TMR1, gate via TMRO) 87 External 32,768 Hz watch crystal-based clock - TMR1 93 Pulse width modulation (PWM) using TMR2 and the CCP module 101 Analog output - increase/decrease buttons - PWM 8-bit mode 105 Duty cycle - 10-bit mode 110 Analog output - increase/decrease buttons - PWM 10-bit mode 118 DESIGNING AND BUILDING YOUR OWN TEST EQUIPMENT

Keypad/LCD user interface 5-digit decimal to 16-bit binary entry program Using the 5-digit decimal to 16-bit binary entry program Digital pulse generator

124

124 126 136 148

Digital frequency generator Time interval measurement instrument Frequency measurement instrument Creating your own combination signal generator and measurement instrument

148 160 173 184

APPENDIX A· Program listings vs. page number

185

APPENDIX B • PIC16F870 control registers

186

APPENDIX C • '84 on a board

193

APPENDIX D • PIC/LCD schematic and code

195

APPENDIX E· Keypad

207

APPENDIX F • Using the ICD

209

APPENDIX G • Sources

217

PREFACE This material presented in this book is the timing and counting information which previously appeared in PIC'n Techniques. Unfortunately, because of trademark issues, it has become mandatory that we change the titles of four of our books . The old and new titles appear on our web site. Since the titles are changing, we are using this as an opportunity to move some topics from one book to another to improve the flow from one topic to the next. Again, the details appear on our web site. We regret any inconvenience and confusion that results from these changes. The more current PIC16F870 is substituted here for the PIC16C63 that was used in some of the examples in PIC'n Techniques. The F870 has in-circuit debugging (ICD) capability which is very useful. If you choose to use the lCD, the test/demo circuit must be modified slightly to make use of Microchip's ICD possible (via ports RB7,6) . The code must be modified slightly for the same reason. Details appear in Appendix F - Using The ICD. The examples based on the PIC16F84 remain essentially unchanged. The PIC16F84A is the current version of this device. I will simply refer to it as the F84. The demonstration circuit module is called the '84 on a board to be compatible with our previous books which use the same circuit. Other small PIC ® devices may be used instead if you prefer as long as the code is adapted as necessary. Finally, "Thank You" to all the readers who have made suggestions over the years which have contributed to the refinement of this material.

GENERAL INFORMATION See our web site at http://www.sq-l.com for updates, for errata, and for downloading the code in this book at no cost.

1

2

INTRODUCTION 'nme'n and Count'n is an intermediate level book. I am assuming you know all the beginner information included in Easy PIC'n or Easy MlC1'OCOntrol'n (our beginner books) either from using the book or from other experience. Some of the circuits used in PIC'n Up The Pace orMicrocontrol'n Apps are used in this book as well. These circuits are shown in appendices in the back of this book. Complete explanations may be found in PIC'n Up The Pace or MiCl'OCOntrol'n A~ The programs included in this book are examples to help you learn. My hope is that you will study the examples in this book and write your own borrowing from what you see here. If you want to borrow from the code in this book, it is currently available for downloading at the Square 1 website (no charge) . For those of you who already know a little bit about PIC microcontrollers, here is my philosophy about some of the topics to be covered : Include files are not used in this book because if you use someone else's include file (this includes those provided by Microchip), you won't know precisely what's in it and will spend a lot of time scratching your head because your program isn't working because you didn't pay attention to what the author of the include file had in mind. If you write the code, you know what's in it and what it does . Use of macros and most assembler directives is avoided because they confuse people who are learning more often than not. If you end up doing a lot of PIC microcontroller programming, you may find them useful. My objective is to write code that you can understand rather than try to optimize for minimum number of program steps and/or for fastest possible execution . Where programs used previously in this book or borrowed from PIC'n Up The Pace or Microcontrol'n Apps are combined for use in a more exotic application, I did not rewrite the code to achieve double duty (shared) use of file registers. The PIC 16F870 test circuit and code examples in this book are presented as they would be when using a device programmer to program the F870 . The circuit and code examples may be easily changed for ICD use per the instructions in Appendix F - Using The ICD. The F870 is used as the example in this book, however the material is device independent. I think you will particularly enjoy the test equipment projects which combine the techniques you will learn in functional equipment. The real fun, however, is to take all this a step further on your own by using these techniques to design and build PIC microcontroller based systems for your own applications.

3

TEST EQUIPMENT FOR TIMING AND COUNTING EXPERIMENTS TEST EQUIPMENT FOR DETECTING A SHORT SINGLE PULSE AND MEASURING Irs WIDTH Since I don't have a storage oscilloscope, I built a PIC microcontroller-based pulse detector which measures the width of a single pulse . This device can be used to test the output of an example circuit when a short pulse (4 to 255 microseconds range) is produced. To develop this, I used two '84 on a board circuits, one to generate a pulse of known length and the other to detect it and measure (verify) the pulse width . The '84 on a board circuit for experimenting is presented in Appendix C.

128.asm

pgenlsl.asm

PIC16F84A

PIC16F84A 8 LEDs

RBO

.....r---L...

RAO

Port B

r--

.. ~

-680

::! !!:

For initial test purposes, the sending '84 generates a 128 microsecond pulse and the receiving '84 counts up in microseconds while the pulse is high and displays the result via LEDs at port B. Simple! Then the detection/measuring device can be used to look for a short pulse generated by a PIC16F870 using the techniques we will develop later in this book.

4

The pulse generator (sender) looks like this:

ROO +5VDC 10K .. ~

PIC16F84A RB1

The program used to generate the 128 microsecond test pulse is:

Setup Send

No

Test

No Count = 128?

5

i=======128.ASM=====================================4/17/02== itimer/counter demo single time interval internal clock 128 microsecond pulse out

i----------------------------------------------------- - - - - - - list p=16f84a __config h'3ffl' radix hex j----------------------------------------------------- - - - - - - cpu equates (memory map) tmrO equ OxOl status equ Ox03 portb equ Ox06 intcon equ OxOb opt reg equ Ox8l trisb equ Ox86

j--------------------- -------------------------------- - - - - - - rpO

bit equates equ 5

j------ --------------- ----------------- --------------- - - - - - - org start

send

test

circle

OxOOO

bsf status,rpO movlw b'OOOOOOlO' movwf trisb bcf status,rpO portb,O bcf bcf portb,2 bcf portb,3 portb,4 bcf bcf portb,5 bcf portb,6 bcf portb,7 bcf intcon,2 bcf intcon,7 bcf intcon,5 clrf tmrO clrwdt bsf status,rpO movlw b'llOlllll' movwf opt reg bcf status,rpO btfss portb,l goto send clrf tmrO bsf portb,O btfss tmrO,7 goto test bcf portb,O goto circle

iswitch to bank 1 iport Bin/out iback to bank 0 ilow ilow ilow ilow ilow ilow ilow iclear TMRO interrupt flag idisable global interrupts idisable TMRO interrupts iclear TMRO iclr WDT prep prescale assign ito bank 1 iset up timer/counter iback to bank 0 iswitch open? inot yet istart timer/c, clr prescaler istart pulse ilook for count=128 inot yet iend pulse idone

end j--------------------------------------------- -------- - - - - - - -

6

iat device program time, select: code protection off watchdog timer disabled (default is enabled) standard crystal XT (using 4 MHz osc for test) power-up timer on ;============================================================

The width of the pulse is actually 129 microseconds because an additional microsecond is needed to clear port B, bit 0 after the timer times out. The pulse detection/measuring device (receiver) looks like this :

Signal

+SVDC

RAO

PIC16F84A SLEDs

10K

.-----1 RA1

Port B 680

No

~'~l -.

The object is to count pulses from a source of known frequency (internal instruction clock, 1 MHz) while the incoming pulse to be measured is high. The count will be the pulse width in microseconds. This is similar in concept to using an AND gate . An unknown time interval may be measured by using the time interval signal to gate a second signal of known frequency.

Count Pulses Which Arrive During Unknown TIme Interval Known Frequency

Unknown TIme Interval

TIme Interval

=

Pulses Frequency

=

Pulses PulseslTime

The signal of known frequency will appear at the output of the AND gate only while both signals are high. The pulses appearing at the output of the AND gate are then counted . The number of pulses divided by the frequency (multiplied by the period) of the reference signal is the time interval.

7

The flow chart for the program is:

Setup

No

Yes

No

--r-

?

No

~?

DisplayTMRO At Port B LEOs

8

The code follows: ;=======PGENTST.ASM=================================4/17/02== list p=16f84a __config h'3ff1' radix hex j----------------------------------------------------- - - - - - - cpu equates (memory map) tmrO equ Ox01 status equ Ox03 porta equ OxOS portb equ Ox06 opt reg equ Ox81 trisa equ Ox8S trisb equ Ox86

j----------------------------------------------------- - - - - - - rpO ,

bit equates equ S

e

start

ready p_hi

p_lo

circle

_

org

OxOOO

bsf movlw movwf movlw movwf bcf clrf

status,rpO b'OOOOOOl1' trisa b'OOOOOOOO' trisb status,rpO portb

clrf clrwdt bsf movlw movwf bcf

tmrO

btfss goto btfss goto clrf btfsc goto movf movwf goto

porta, 1 ready porta,O p_hi tmrO porta, 0 p_lo tmrO,w portb circle

;switch to bank 1 ;port A inputs/outputs ;port B outputs ;back to bank 0 ;LEDs off

;clear TMRO before assign wdt ;clr WDT prep prescale assign status,rpO ;to bank 1 b' 11011111' ;set up timer/counter opt reg status,rpO ;back to bank 0 ; ready? ;not yet ;monitor signal ;clear TMRO ;monitor signal ;read timer 0 ;display TMRO contents ; done

end , ;at device program time, select: code protection off watchdog timer disabled (default is enabled) standard crystal XT (using 4 MHz osc for test) power-up timer on e

_

j================================== =================== =======

9

Code for generating pulses of four different width follows. The code will be used in conjunction with an '84 on a board to test circuits presented later in the book. PULSE GENERATOR - 32 microseconds

ABO +5VDC 10K

PIC16F84A "10'

AB1

;=======32.ASM======================================4/17/02== ;timer/counter demo single time interval internal clock 32 microsecond pulse out j -------------- --------------------------------------- - - - - - - list p=16f84a __config h'3ff1' radix hex i----------------------------------------------------- - - - - - - cpu equates (memory map) tmrO equ Ox01 status equ Ox03 portb equ Ox06 intcon equ OxOb opt reg equ Ox81 trisb equ Ox86 i-------------------------------------------------- --- - - - - - - bit equates rpO equ 5

i---------------------- ------ - --- - ------ -------------- - - - - - - start

10

org

OxOOO

bsf movlw movwf bcf bcf bcf bcf bcf bcf bcf bcf

status,rpO ;switch to bank 1 b'00OOOO10' ;port B in/out trisb status,rpO ;back to bank 0 portb,O ;low portb,2 ;low portb,3 ;low portb,4 ;low portb,5 ;low portb,6 ;low portb,7 ;low

send

test

circle

bcf intcon,2 bcf intcon,7 bcf intcon,5 clrf tmrO clrwdt bsf status,rpO movlw b'l1011111' movwf opt reg bcf status,rpO btfss portb,l goto send clrf tmrO bsf portb,O btfss tmrO,5 goto test bcf portb,O goto circle

iclear TMRO interrupt flag idisable global interrupts idisable TMRO interrupts iclear TMRO iclr WDT prep prescale assign ito bank 1 iset up timer/counter iback to bank 0 iswitch open? inot yet istart timer/c, clr prescaler istart pulse ilook for count=32 inot yet iend pulse idone

end

;-----------------------------------------------------------iat device program time, select: code protection off watchdog timer disabled (default is enabled) standard crystal XT (using 4 MHz osc for test) power-up timer on j============================================================

The width of the pulse is actually 33 microseconds because an additional microsecond is needed to clear port B, bit 0 after the timer times out. The 33 microsecond pulse can be detected and its width measured using a second '84 on a board and pgentst.asm as was done for thel28 microsecond example. PULSE GENERATOR -128 microseconds See 128.asm presented previously. PULSE GENERATOR - 2000 microseconds We will use a PIC16F84 to generate a single pulse of known length, 2000 microseconds in this case. Timer 0 in the F84 is an 8-bit counter and won't hold 2000. We will use the prescaler to divide the internal clock signal by 8 and let TMRO count to 250 (250x8=2000). Since TMRO counts up, it will be loaded with 6 and will roll over when the count reaches 255 plus 1 generating an interrupt.

RBO +5VDC 10K .. ~

PIC16F84A RB1

11

Main Program

Clear TMRO Interrupt Flag

Send

No

Start Count

Port B, Bit 0 HI Start Pulse

Interrupt Service Routine

ClearTMRO Interrupt Flag

~ Port B, Bit 0 LO End Pulse

~ Return From Interrupt

12

i=======2000.ASM====================================4/17/02== itimer/counter demo single time interval internal clock divided by 8 2000 microsecond pulse out ,._----------------------------------------------------------list p=16f84a __config h'3ff1' radix hex , cpu equates (memory map) tmrO equ Ox01 status equ Ox03 portb equ Ox06 intcon equ OxOb opt reg equ Ox81 trisb equ Ox86 e

_

;-----------------------------------------------------------bit equates rpO equ 5 ;-----------------------------------------------------------org OxOOO goto start iskip over location pointed to by interrupt vector org Ox004 goto iserv start

send

circle

bsf movlw movwf bcf bcf bcf bcf bcf bcf bcf bcf bcf bsf bsf clrwdt bsf movlw movwf bcf btfss goto movlw movwf bsf goto

status,rpO b'00000010' trisb status,rpO portb,O portb,2 portb,3 portb,4 portb,5 portb,6 portb,7 intcon,2 intcon,7 intcon,5

iswitch to bank 1 iport Bin/out

iback to bank 0 ilow ilow ilow ilow ilow ilow ilow iclear TMRO interrupt flag ienable global interrupts ienable TMRO interrupts iclr WDT prep prescale assign status,rpO ito bank 1 b'1l010010' iset up time r/counte r opt reg status,rpO iback to ban k 0 portb, l iswitch ope n ? send inot yet Ox05 iinc 250 times to rollover tmrO istart timer/c, clr prescaler portb,O istart pulse circle iwait for interrupt

13

iserv

bcf bcf retfie

iclear TMRO interrupt flag iend pulse idone

intcon,2 portb,O

end

;-----------------------------------------------------------iat device program time, select: code protection off watchdog timer disabled (default is enabled) standard crystal XT (using 4 MHz osc for test) power-up timer on j===================================================== =======

As with the previous example, power up with the send switch closed. Open the switch to send the pulse. The pulse is too wide to be measured with the F84 pulse detector, so an oscilloscope is needed . PULSE GENERATOR - 65280 microseconds

Finally, we will need a program to output a pulse 65280 microseconds wide . This program uses timer 0 and a file register counter called "count" to count the number of times timer 0 rolls over. The sequence starts with timer 0 clear and the count register loaded with OxFF. When the number of pulses fed into timer 0 reaches 65,280, timer 0 rolls over for the 255th time and the count register contains zero . To look at this another way, the program decrements the count register each time timer 0 overflows . When the contents of count reaches zero, the game is over and the number of pulses received by timer 0 is 65,280 .

RBO +SVDC 10K ....

PIC16F84A RB1

14

Main Program

Port B Output Lines Low

Disable Global Interrupts

Load File Register Counter OxFF Send

No

Interrupt Service Routine

Start Count

ClearTMRO Interrupt Flag

Port B, Bit 0 HI Start Pulse DECFSZ

Clear TMRO Interrupt Flag Port B, Bit 0 LO End Pulse

15

i=======65280.ASM=================================== 4/17/02== itimer/counte r demo single time interval internal clock 65280 microsecond pulse out

;-- - - - -- - - ---- -- - - -- - ---- - - - - -- - -- - --- - - --- - - - - -- - - - - - --- - - -list p=1 6f84a __config h'3ff1' radix hex ;------------- ----- -------------- ---------------------------cpu equates (memory map) tmrO equ Ox01 status equ Ox03 portb equ Ox06 intcon equ OxOb count equ OxOc opt reg equ Ox81 trisb equ Ox86 ;----------------------- - - - - ---------- ----- -----------------bit equates z equ 2 rpO equ 5 ; ---- - -------------- ----- -------- ---------------------------org OxOOO goto start iskip over location pointed to by interrupt vector org OxOO4 goto iserv start

send

16

bsf movlw movwf bcf bcf bcf bcf bcf bcf bcf bcf bcf bcf clrf clrwdt bsf movlw movwf bcf movlw movwf btfss goto clrf bsf

status,rpO iswitch to bank 1 b'OOOOOO10' iport B in/out trisb status,rpO iback to bank 0 portb,O ilow portb,2 ilow portb,3 ilow portb,4 ilow portb,5 ilow portb,6 ilow portb,7 ilow intcon,7 idisable global interrupts intcon,5 idisable TMRO interrupts tmrO iprep assign iclr WDT prep prescale assign status, rpO ito bank 1 b' 11011 111' i s e t up timer/counter opt reg status,rpO iback t o bank 0 Oxff count iload c ount er portb,l iswitch open? send inot yet tmrO istart timer/c , cl r prescaler portb,O istart pulse

circle iserv

round

bsf bcf bsf goto

intcon,7 intcon,2 intcon,5 circle

;enable global interrupts ;clear TMRO interrupt flag ;enable TMRO interrupts ;wait for interrupt

bcf decfsz retfie bcf goto

intcon,2 count,f

;clear TMRO interrupt flag ;dec count, = zero? ;no ;yes, end pulse ;done, circle

portb,O round

end

;-----------------------------------------------------------;at device program time, select: code protection off watchdog timer disabled (default is enabled) standard crystal XT (using 4 MHz osc for test) power-up timer on

;============================================================

As with the previous example, power up with the send switch closed . Open the switch to send the pulse. The pulse is too wide to be measured with the F84 pulse detector, so an oscilloscope is needed . TEST EQUIPMENT FOR GENERATING A FREQUENCY OUTPUT

An '84 on a board can be used easily to generate a 100 KHz square wave for test purposes. A simple software delay loop does the job.

REO

1------

PIC16F84A

The flow chart and code follow:

17

Initialize Again

4

2

10J,l.Sec

2 10 Cycles Total

i=======FREQOUT.ASM=================================4/17/02== itimer/counter demo 100 KHz out internal clock

i-------------------------------- - -------------------- - - - - - - list p=16f84a __config h'3ff1' radix hex

;-----------------------------------------------------------status portb opt reg trisb

cpu equates (memory map) equ Ox03 equ Ox06 Ox81 equ Ox86 equ

j----------------------------------------------- ------ - - - - - - rpO

bit equates equ 5

;-----------------------------------------------------------start

again

18

org

OxOOO

bsf movlw movwf bcf movwf bsf nop nop

status,rpO b'OOOOOOOO' trisb status,rpO portb portb,O

iswitch to bank 1 iport B outputs iback to bank 0 iall low ibit 0 high

nop nop bcf nop nop goto

portb,O

;output low

again

end ;-----------------------------------------------------------;at device program time, select: code protection off watchdog timer disabled (default is enabled) standard crystal XT (using 4 MHz osc for test) power-up timer on ;============================================================

19

USING TIMER 1, TIMER 2 AND THE CAPTURE/COMPARE/PWM MODULE TIME'n AND COUNT'n TEST CIRCUIT - TC BOARD Timer 1 (TMRl), timer 2 (TMR2), and capture/compare/PWM (CCP) modules are found in many PIC parts . A test circuit based on the PIC 16F870 is shown here as an example you may use for experiments. I elected to use a 16-pin DIP socket as a connector for port B so that the keypad board described in "PIC' n Up The Pace" or "Microcontrol'n Apps" (see Appendix E) can be connected via a 16-conductor ribbon cable with DIP plugs. This scheme requires putting the LEDs for port B on a separate small board with a 16-pin DIP socket used as a connector. The LED board is connected for all experiments except those utilizing the keypad .

20

Gnd +SV

T r t T T

I() () ,

t

DIP Socket

o 432 L..-.,---r-~----r-..-----r----r-.....,.~-.1 6

10!1.:

S

T

Tesl

0.1

EL

T

Point

==-

+SV.--t---1t-t---1_h Keypad Column

,---,_~_-

+SV

_

__e +SV

+SV

Pull~

RB7

RB6

RBS RB4

RB3 RB2

RB1

RBO

Vdd

Vss

RC7 RCG

RCS

RC4

PIC16F870 ~ Vpp RAO

+SV

RA2 RA3

RA1

TOCKI RM RAS

ClKI ClKO Vss OSC1 OSC2 RCO

RC1

CCP1 RC2 RC3

L ~ Reset

N.C.

"

1000,--_-+_t--I_t--I--it4.--f-----1t----+---.-+-_+-__-+----'

1 . ~ .. ~ . ~

+sv

.-

t--

cilp Serial Output To PIC/lCD, Input

All Pullup Resistors 10K

TMRO Input

+SV

i 4.0 MHz CIockOsc

1-i.

N.C.

Xtal Cap • Sockets

TMR1 Input

CCP1

• Cap = 22 pI (2 reqd' Xtal =32.768 KHz Sockets to allow removal. Parts used lor external clock experiment only

TC BOARD

21

LED BOARD

6800 8LEDs

Port B

I like to use SIP resistor networks (10-pin, 9 resistors bussed) and LED bargraph displays. The bargraphs I have found have 10 LEDs, so I cut two off with a hacksaw and filed the cut end smooth. The result is a neat, small board. The TC board has the following I/O: • Eight port B pins brought out to a 16-pin DIP socket for use with LED board or keypad board. • Three DIP switches with pullup resistors on port B for use with the keypad. • Connections for TMRO (input), TMR1 (input), and the CCP1 module (input/output). • Two DIP switches with pullup resistors for use as inputs (RAO, RA2). • Sockets for a 32.768 KHz crystal and two 22 pF capacitors for use with TMR1 . • Serial output pin for use with a PIC/LCD circuit (RA1)(see PIC'n Up The Pace or Microcontrol'nAppsz, and Appendi x D for details). • Pullup resistors on the unused pins . On my breadboard, I used the following DIP switch and terminal block assignments/layout. To help avoid confusion, a list of switch settings will be shown for each experiment so you won't have to think so hard about which switches should be open and which ones should be closed.

22

,.....-

RAO

-

RA1

-

RA2 ~

-

RA4ITOCKI RCOIT10S0 ,.....-

RC1/T10S1

+SVDC ~

T 10K"~

RC2ICCP1

.. ~

100001 .. ~

-

.....~_ ............ - . 10K -

! +SVDC

'--

CCP1 TMR11npul

TMROlnput Serial Output To PICIlCD Input

Pull Up Lines When Not Being Used Example: Not Using Any Lines.

DIP Switches

1234567

ococccc

I leave the LED board connected to the TC board for all experiments except those involving the keypad. This way, I know the port B lines are not left floating. The 3 port B DIP switches are open except when the keypad is connected.

23

The simple program shown may be used to see if your PIC16F870 circuit comes alive. The LEDs at port B bits 7, 6, 5,4 should be off and the remaining four should be on.

DIP Switches

1 2 345 6 7 o C 0 C C C C

i=======PGMR1.ASM==========================12/20/01== list p=16f870 __config h'3f71' radix hex

;---------------------------------------------------cpu equates (memory map) Ox03 status equ equ Ox05 porta equ Ox06 portb equ Ox07 portc equ Ox85 trisa equ Ox86 trisb equ Ox87 trisc adconl equ Ox9f i---------------------------------------------------bit equates rpO equ 5 i---------------------------------------------------org OxOOO start bsf status,rpO iswitch to bank 1 movlw iturn off A/D, port A b' 00000110' movwf adconl movlw b'OOOOOOOO' iinputs/outputs movwf trisa movwf trisb movwf trisc bcf status,rpO iback to bank 0 movlw iload w with bit pattern OxOf iload port B with contents of W movwf portb circle goto circle idone end i----------------------------------------------------iat device programming time, select: memory unprotected watchdog timer disabled (default is enabled) standard crystal (using 4 MHz osc for test) XT power-up timer on brown-out reset enabled lvp disabled debug mode disabled ;=====================================================

24

BEFORE WE TAKE OFF There are some details we need to be aware of. The register addresses used in the examples are for the PIC16F870. If you plan to use a different device, check the Microchip data book to be sure the addresses are correct for the device you intend to use. The PIC16F870 peripheral control register descriptions are in Appendix B called "Control Registers" in the back of the book so you can find them easily for reference. TMRl, TMR2 and the CCP modules are "peripherals" . The list of modules considered "peripherals" is device (part number) dependent. Note that timer 0 (TMRO) is not called a peripheral and that the register bits that control it are not in the peripheral control registers (they are in the status register). There is a peripheral interrupt enable (pIE) register and a peripheral interrupt (flag) register (pIR). Note that there is a peripheral interrupt enable bit in the interrupt control (INTCON) register which must be set to allow interrupts from any of the peripherals. Remember also that the global interrupt enable bit in the INTCON register must be set to allow peripheral interrupts. Remember that an "interrupt" flag may be polled to determine its status instead of using it to trigger an interrupt. The INTCON register in the PIC16F870 is not the same as for the PIC16F84. The difference is bit 6 which is the peripheral interrupt enable bit in the F870 where as in the F84 it is the EE write complete interrupt. The PIC16F870 has two CCP modules designated CCPl and CCP2 . We will use only CCPl (and will ignore the existence of CCP2) to simplify the learning process . Finally, the output of the timing and counting examples will, in general, be slightly inaccurate because of things like a program loop looking for a bit to change state catching it a cycle or two after it actually occurs or because of program steps taking a few extra instruction cycles. In most cases, the error will be very small and inconsequential. If these errors are significant in your particular application, you can analyze the code and compensate by changing the value(s) loaded into the timer to correct the results . Or you can simply change the values used to correct the output and forget about analysis (assuming your measuring equipment is more accurate than a crystal-controlled PIC microcontroller).

25

TIMER 2 (TMR2): 8-BIT TIMER TMR2 has the following features: • • • • • • • • • • •

8-bit timer. Source of pulses is the internal instruction clock (timing applications only). Prescaler divides the incoming pulse train by 1,4, or 16. Postscaler divides the comparator output by 1,2,3 .... 16 8-bit period register (PR2) . Comparator to look for TMR2/PR2 match . TMR2 may be cleared, written to, or read at any time. The period register may be written to or read. TMR2 may be used as a general purpose timer. TMR2 may be used with the CCP module for PWM. TMR2 may be used with the SSP module for baud rate generation.

TMR2 Description A simplified block diagram ofTMR2 follows:

CCP1 Pin High For CCP PWM SSP Baud Rate Reset Internal Clock

TMR2 Prescaler

Postscaler

1,4,6

1,2,3,---,16

Interrupt Flag

TMR2 is incremented by the internal instruction clock (fosc/4) (prescaled) from OxOO until it's contents match the period register. On the next increment, it is reset to OxOO. For each match of TMR2 and its period register, a pulse is output to a postscaler. The postscaler output sets the TMR2 interrupt flag in the PIRI register. The output of the TMR2 module may be : • Read TMR2. • TMR2 interrupt flag. The match output from the comparator (directly) is used to reset TMR2 in PWM applications (see PWM section), and is used in SSP serial applications (baud rate).

26

The interrupt generated by TMR2 is called both the TMR2 interrupt and the TMR2 match interrupt in the Microchip literature. The term match interrupt implies that an interrupt occurs at every match, which may not be true depending on the postscaler ratio. We will refer to this interrupt as the TMR2 interrupt. TMR2 can be turned on or off via a control bit in the TMR2 control register T2CON. TMR2 is cleared by any device reset (pOR, BOR, MCLR, WDT). The prescaler and postscaler are cleared by: • Write to TMR2. • Write to T2CON, the TMR2 control register. • Any device reset (pOR, BOR, MCLR, WDT). PR2 is filled with l's on reset (full count). A write to the T2CON register does not clear TMR2 .

How To Choose/Select Mode Of Operation T2CON register: Bit(s) Prescaler select Postscaler select TMR2 on/off

1,0 6,5,4,3 2

Interrupts Enable using PIEl register: Bit TMR2 interrupt enable

1

Enable using INTCON register: Bit Peripheral interrupt enable Global interrupt enable

6 7

Flag - PIRI register: Bit TMR2 interrupt flag

1

27

TMR2 Application· Free Running Mode (via TMR2 interrupt) The first example is similar to the TMRO free running mode with internal clock example in

Sug Ple'n or Sug Microcontrol'n. Use internal clock, prescaler 1:16, postscaler 1:16, period 255. Time interval 65 milliseconds. Output to port B, bit o.

PIC16F870

RBO 680

-...

28

Main Program

Interrupt Service Routine

Clear TMR2 Interrupt Flag

Disable Global Interrupts

Disable Peripheral Interrupts

Clear TMR2 Interrupt Flag

Set Up Prescaler And Postscaler, TMR2 Off

Load Period Register

PR2

29

Unimplemented

I T2CON

Postscaler 1:16

--------1

DIP Switches

I0

L

POR = OxOO

1 2 345 6 7 o C 0 C C C C