Файл: The quintessential PIC microcontroller (S. Katzen, 2000).pdf

ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 15.06.2025

Просмотров: 5349

Скачиваний: 0

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

13. Time is of the Essence 385

A speed of 12,000 rpm translates to a maximum pulse count of 200 rps (revolutions per second). Thus we propose to use Timer 0 as the pulse counter driven from pin T0CKI with no prescaler.

Timer 1 in conjunction with CCP1 set to a Compare mode will give a 1-second time-out if it uses its own oscillator and a 32.768 kHz watch crystal together with a count spanning 0000–7FFFh. However, to simplify the mathematical relationship rpm = rps × 60 it is proposed to shorten the timebase by the factor 6064 to implement the equivalent relationship

rps×60 × 64. The final ×64 can easily be implemented by either shifting

64

left six times (>>6) or more e ciently placing the rps count as the high byte of the double-byte rpm datum and shifting right twice; i.e.:

rpm = (rps × 256)> >2

This is considerably more e cient that using a 1 second timebase and multiplying by 60.

One possible solution is shown in Program 13.6. Here the initialization code implements the following task list:

• Set Timer 0 to count \ events at T0CKI.

Set CCP1 to Compare mode 1011 to reset Timer 1 on equality.

Enable an interrupt from this event.

Set up the CCPR1H:L to set the timebase to 6064 s.

The ISR itself simply copies the rps reading from Timer 0, zeroing it and then converts the reading to rpm as described above. After the two shift right operation >>2, the top two bits of RPM are cleared to remove erroneous carry-ins. The resulting 14-bit datum in RPM:RPM+1 is the required outcome which can then perhaps be used by the background program to activate the display or maybe transmit the data to a computer over a serial link.

Example 13.3

A PIC16C74 is to be used to measure the duration of an event. This duration is the time a signal is high, as shown in Fig. 13.11. You an assume that the main crystal is 8 MHz and the duration of the event is guaranteed to be no more than 100 ms.

Solution

One way of tacking this problem is to feed the signal shown in the diagram into both pins RC1 and RC2 in parallel. Using one CCP module to capture the rising edge and the other to capture the falling edge gives the duration as the di erence in the two captured values. In Program 13.7 Timer 1 is zeroed on a rising edge and thus the second captured Timer 1 state is our duration. If we use a prescale ratio of 1:4 and the internal clock

386 The Quintessential PIC Microcontroller

Program 13.6 Tachometer software.

MAIN movlw

77h

; Setting 77FFh to give

movwf

CCPR1H

; a time base of 60/64 seconds

movlw

0FFh

movwf

CCPR1L

bsf

STATUS,RP0

; To Bank1

movlw

b’00111000’

; Timer0 external -ve edge

movwf

OPTION_REG

; No prescale

bsf

PIE1,CCP1IF

; Enable interrupts from CCP1

bcf

STATUS,RP0

; Back to bank0

movlw

b’00001011’

; CCP Compare mode 1011

movwf

CCP1CON

; resets Timer1

movlw

b’00001011’

; Timer1 PS1:1, oscillator synched

movwf

T1CON

; and enabled

bsf

INTCON,PEIE

; Enable Timer/CCP interrupts

bsf

INTCON,GIE

; Global enable mask bit on

;<<<< More background code >>>>

;*************************************************************

;First save context in usual way

ISR

movwf

_work

;

Put

away W

swapf

STATUS,w

;

and

the Status register

movwf

_status

;************************************************************

;The core code

btfss

PIR1,CCP1IF

; Did CCP register Timer1 reset?

goto

ISR_EXIT

; IF no THEN false alarm

movf

TMR0,w

; Get totalized pulse count

clrf

TMR0

; Zero pulse count

movwf

RPM

; Save totalized count away

; Now multiply by 64

clrf

RPM+1

; Clear lower byte

rrf

RPM,f

; RPM as MSB; i.e. X256

rrf

RPM+1,f

; >>2 to convert rps to rpm

rrf

RPM,f

rrf

RPM+1,f

bcf

RPM,7

; Zero top two bits

bcf

RPM,6

bcf

PIR1,CCP1IF

; Reset interrupt flag

; ************************************************************

ISR_EXIT swapf

_status,w

; Untwist

the original Status reg

movwf

STATUS

swapf

_work,f

; Get

the

original W reg back

swapf

_work,w

;

leaving

STATUS unchanged

retfie

;

and

return from interrupt


13. Time is of the Essence 387

CCP1

CCP2

Capture 1

Capture 2

Fig. 13.11 An event manifesting itself as a pulse duration.

then we have as our counting rate 500 kHz; i.e. the system resolution is 2 µs. The overall maximum duration that can be measured in this way is 216 × 2 = 131, 077µs which is large enough not to overflow.

The ISR in Program 13.7 simply tests each CCP interrupt flag in turn and goes to the appropriate routine. If CCP1 has signalled a / event

then the timer is zeroed to restart the count. Timer 1 has been configured to increment at a 500 kHz rate and when the next \ occurs the CCP2 module captures the state of this timebase and places it in the 16-bit CCPR2 register. The ISR then copies it into the two file registers TIME:TIME+1 and this is the period in 2 µs ticks.

Actually resetting Timer 1 on the first event introduces some inaccuracy into the process as the clearing event takes some time. In our application this is of little consequence but it may cause some problems in shorter high-resolution situations. In this case Timer 1 can be left to run continually and the two captured 16-bit data subtracted to give the required di erence at relative leisure.

Self-assessment questions

13.1Using Timer 1 and CCP1, design a system to generate a continuous square wave with a total period of 20 ms from RC2/CCP1. You may assume that the main crystal is 8 MHz. Hint: Remember that the state of the CCP pin will only change when a match occurs so the Compare mode will have to be changed on the fly each 10 ms.

13.2The echo sounding hardware shown in Fig. 7.6 on page 195 uses an external 1.72 kHz oscillator to interrupt the PIC once per 5.813 ms, that is once every time sound travels 1 cm through air. Assuming that a 20 MHz PIC is used, show how Timer 2 could be used to generate this interrupt rate to an accuracy better than 0.1%.

13.3The PIC family has only one hardware input, namely INT/RB0. Suggest

some way to use Timer 0 to simulate another hardware interrupt with pin T0CKI/RA4.


388 The Quintessential PIC Microcontroller

Program 13.7 Measuring the duration of a pulse.

MAIN movlw

b’00000101’

; CCP1 module captures rising

edge

movwf

CCP1CON

movlw

b’00000100’

; CCP2 module captures falling edge

movwf

CCP2CON

bsf

STATUS,RP0

; To Bank1

bsf

PIE1,CCP1IE

; Enable interrupts from CCP1

bsf

PIE2,CCP2IE

; Enable interrupts from CCP2

bcf

STATUS,RP0

; Back to bank0

movlw

b’00100001’

; Timer1 enabled (1), int osc

(0)

movwf

T1CON

; Synched (0), prescale 2:1 (10)

clrf

NEW

; Clear the New flag

bsf

INTCON,PEIE

; Enable Timer/CCP interrupts

bsf

INTCON,GIE

; Global enable mask bit on

;<<<< More background code >>>>

;*************************************************************

;First save context in usual way

ISR

movwf

_work

;

Put

away W

swapf

STATUS,w

;

and

the Status register

movwf

_status

;************************************************************

;The core code

btfsc

PIR1,CCP1IF

; A CCP1 rising edge capture?

goto

CAPTURE1

; IF yes THEN go to it!

btfss

PIR2,CCP2IF

; A CCP2 falling edge capture?

goto

ISR_EXIT

; IF not THEN false alarm!

CAPTURE2

movf

CCPR2L,w

; Get low byte of captured time

movwf

TIME+1

; and put away

movf

CCPR2H,w

; Get high byte of captured time

movwf

TIME

; and put away

bcf

PIR2,CCP2IF

; Clear flag

incf

NEW,f

; Tell the world: A new time datum

goto

ISR_EXIT

CAPTURE1

clrf

TMR1L

; Zero time count

clrf

TMR1H

bcf

PIR1,CCP1IF

; Reset interrupt flag

; ************************************************************

ISR_EXIT swapf

_status,w

; Untwist

the original Status reg

movwf

STATUS

swapf

_work,f

; Get

the

original W reg back

swapf

_work,w

;

leaving

STATUS unchanged

retfie

;

and

return from interrupt


13. Time is of the Essence 389

13.4As part of a software implementation of an asynchronous serial channel running at 300 baud a delay of 3.3˙ ms is to be generated. Assuming that a 8 MHz PIC16F84 is the host processor, show how you could use a timer to generate an interrupt each baud period. Extend your routine to enable baud rates up to 19,200 in doubling geometric progression.

13.5Show how you would use Timer 1 with its separate integral oscillator with a 32.768 kHz watch crystal, to keep the central heating real time clock array HOURS:MINUTES:SECONDS of Example 7.4 on page 191 up to date.

13.6The CCS C compiler has integral functions dealing with the timers and CCP modules. For example, Timer 1 can be written to using set_timer1(datum); and read from using get_timer1();. The function setup_timer_1(mode); is used to initialize the timer. Similarily setup_ccp1(mode); initializes the CCP1CON register. Mode

values for Timer 1 and the CCP Compare configuration are:

T1_DISABLED T1_INTERNAL T1_EXTERNAL T1_EXTERNAL_SYNCH T1_CLK_OUT T1_DIV_BY_1 T1_DIV_BY_2 T1_DIV_BY_4 T1_DIV_BY_8 CCP_COMPARE_RESET_TIMER

Where separate modes can be separated by the operator |.

Show how you would code your solution to SAQ 13.5 in C. In CCS C a function can be turned into a CCP1 interrupt service routine by preceeding it by the directive #INT_CPP1 – see Program 14.9 on page 427 for details. You an also assume that the reserved variable CCP_1 represents the 16-bit CCPR1H:L register.


CHAPTER 14

Take the Rough with the Smooth

Given that digital microcontrollers are in the business of monitoring and controlling the real environment — which is commonly analog in nature

— we need to consider the interconversion between the analog and the digital world. Analog input signals need conversion to a digital equivalent, that is analog to digital conversion (ADC). Thereafter the digital patterns can be processed in the normal way. Conversely, if the outcome is to be in the form of an analog signal, then a digital to analog conversion (DAC) stage will be necessary.

Digital processing

The analog

A/D

MCU-based system

D/A

The analog

world

world

Fig. 14.1 Analog world – digital processing.

Of these two processes, illustrated in Fig. 14.1, A/D conversion is by far the more complex. Some PIC devices, notably the PIC16C7XX and 12C67X lines, feature integral multi-channel A/D facilities. However, analog outputs require external circuitry to implement the D/A process.

In this chapter we will look at the properties of analog and digital signals and the conversion between them as relevant to the PIC MCU. After completion you will:

Understand the quantization relationship between analog and digital signals.

Appreciate the need to sample an analog signal at least twice the highest frequency component.

Appreciate how the successive approximation technique can convert an analog voltage to a binary equivalent.

Be able to select the correct ADC clocking source and frequency.

392 The Quintessential PIC Microcontroller

Be able to select the analog channel for conversion.

Be able to configure I/O pins as either analog or digital.

Be able to write assembly-level programs to acquire analog data using polling, interrupt-driven and Sleep techniques.

Be able to code high-level C programs to interface to the analog module.

Know how to interface in parallel to a proprietary DAC.

The information content of an analog signal lies in the continuously changeable worth of some constituent parameters, such as amplitude, frequency or phase. Although this definition implies that an analog variable is a continuum between ±∞, in practice its range is restrained to an upper and lower limit. Thus a mercury thermometer may have a continuous range between, say, −10◦C and +180◦C. Below this the mercury disappears into the bulb. Above and the top of the tube is blown o !

Theoretically the quantum mature of matter sets a lower limit to the smooth continuous nature of things. However, in practice noise levels and the limited accuracy of the device generating the signal sets an upper limit to the resolution that processing needs to take account of.

Digital signals represent their information content in the form of arrangements of discrete characters. Depending on the number and type of symbols making up the patterns, only a finite totality of value portrayals are possible. Thus in a binary system, an n-digit pattern can at the most represent 2n levels. Although this grainy view of the world seems inferior to the infinity of levels that can be represented by an analog equivalent, the quantizing grid can be tailored to be fit for the accuracy of the task to be undertaken. For example, a telephone speech circuit will tolerate a resolution of around 1%. This can use an 8-bit depiction, which gives up to 256 discrete values — ≈ 0.5%. A music compact-disk uses a 16-bit scheme, giving a one part in 65,636 grid — an ≈ 0.0015% resolution.

From this discussion it can be seen that any process involving interconversion between the analog and digital domains will involve transition through the quantization state. Therefore we need to look at how this a ects the information content of the associated signals.

As an example, consider the situation shown in Fig. 14.2, where an input range is represented as a 3-bit code. In essence the process of quantizing a signal is the comparision of the analog value with a fixed number of levels – eight in this case. The nearest level is then taken as expressing the original in its digital equivalent. Thus in Fig. 14.2 an input voltage of 0.4285 of full scale is 0.0536 above quantum level 3. Its quantized value will then be taken as level 3 and coded as 011b in our 3-bit system.

The residual error of −0.0536 will remain as quantizing noise, and can never be eradicated (see Fig. 14.3(d)). The distribution of quantization error is given at the bottom of Fig. 14.2, and is a ected only by the number