1. Trang chủ
  2. » Công Nghệ Thông Tin

PROGRAMMING AND CUSTOMIZING THE PIC MICROCONTROLLER 3rd phần 6 pdf

130 647 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 130
Dung lượng 1,37 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The address data write is similar to the address write but does not force the two linesinto IDLE mode, and it passes along a data byte before stopping the transfer:Idle – Start – 1010000

Trang 1

MID-RANGE BUILT-IN EEPROM/FLASH ACCESS 623

may be accessed incorrectly, causing problems with subsequent reads You should neveruse the instruction

to take place, the read/write bit is reset

After a byte is sent, the SDA line is pulled low to indicate an acknowledgment (ACK

or just A in the bitstream representations below) This bit is set low (as an edgment) when the operation has completed successfully If the acknowledgment bit ishigh (NACK), it does not necessarily mean there was a failure; if it is issued by theEEPROM, then it indicates a previous write has not completed The PIC microcontrollerwill issue the acknowledgment to stop the EEPROM from preparing to send additionalbytes out of its memory in a multibyte read

acknowl-There are five operations that can be carried out with the EEPROM that is built intothe PIC12CE5xx They are

1 Current address set

2 Current address set/data byte write

3 Data byte read at current address

4 Sequential (multibyte) read at current address

5 Write completion poll

The EEPROM in the PIC12CE5xx is only 16 bytes in size Each byte is accessed using

a 4-bit address This address is set using a control byte, with the R bit reset followed bythe address The bitstream looks like this:

idle – Start – 1010000A – 0000addrA – DataByteA – Stop - idle

In the second byte sent, the 0b00000addr pattern indicates that the four addraddress bits become the address to set the EEPROM’s internal address pointer to forsubsequent operations

After the 2 bytes have been sent, the SCL and SDA lines are returned to IDLE forthree cycles using the instruction

movlw 0xC0

before another operation can complete

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 2

The address data write is similar to the address write but does not force the two linesinto IDLE mode, and it passes along a data byte before stopping the transfer:

Idle – Start – 10100000A – 0000addrA – DataByteA – Stop - idle

Data bytes can be read singly or sequentially depending on the state of ACK from thePIC microcontroller to the EEPROM after reading a byte To halt a read, when the lastbyte to be read has been received, the PIC microcontroller issues a NACK (or N in thebitstream listing) to indicate that the operation has completed

A single-byte read looks like this:

idle – Start – 10100001A – DataByteN – Stop – idle

whereas a 2-byte read looks like this:

idle – Start – 10100001A – DataByteA – DataByteN – Stop - idle

The last operation is sending dummy write control bytes to poll the EEPROM to seewhether or not a byte write has completed (10 ms is required) If the write has completed,then an ACK will be returned; otherwise, a NACK will be returned

This is a pretty cursory explanation of how the PIC12CE5xx’s built-in EEPROMworks In later chapters I will include a more comprehensive explanation of accessingI2C and provide you with code examples to do it

I do want to make one point on the flash15x-ASM code you will see referenced inthe 12CE5xx datasheet and on the Microchip web page This file is designed to belinked into your application and provide the necessary I2C routines to access theEEPROM memory Unfortunately, this file is quite difficult to set up correctly, andthere are no instructions for using it

If you do want to use the flash15x.ASM file, then there are a few things to do:

1 Install it so that it occupies memory in the first 256 bytes of the PIC microcontroller.The file should not be put at the start of program memory because this will interferewith the PIC microcontroller’s reset

2 Declare EEADDR and EEDATA in your file register variable declarations

3 Make sure that the #define emulated line is commented out If this line is left

in, code will be generated that will attempt to write to the SDA and SCL bits (whichdon’t exist) and in the process will set all the GPIO bits to output

TMR1

Along with TMR0, many PIC microcontrollers have an additional 16-bit (TMR1) and8-bit (TMR2) timer built into them These timers are designed to work with the compare/capture program hardware feature Along with enhancing this module, they also can beused as straight timers within the application TMR1 (Fig 16.3 shows the block diagram

Trang 3

TMR1 625

of the timer) is a 16-bit timer that has four possible inputs What is most interesting aboutTMR1 is that it can use its own crystal to clock the timer This allows TMR1 to run whilethe PIC microcontroller’s processor is “asleep.”

To access TMR1 data, the TMR1L and TMR1H registers are read and written Just

as in TMR0, if the TMR1 value registers are written, the TMR1 prescaler is reset ATMR1 interrupt request (TMR1IF) is made when TMR1 overflows TMR1 interruptrequests are passed to the PIC microcontroller’s processor when the TMR1IE bit is set.TMR1IF and TMR1IE normally are located in the PIR and PIE registers To request

an interrupt, along with TMR1IE and GIE being set, the INTCON PIE bit also must beset To control the operation of TMR1, the T1CON register is accessed with its bitsdefined as shown in Table 16.2

The external oscillator is designed for fairly low-speed real-time clock applications.Normally, a 32.768-kHz watch crystal is used, along with two 33-pF capacitors Additionally,

1

0 FOsc/4

Timer1 Prescaler

1

0

OF

Figure 16.3 TMR1 block diagram.

TABLE 16.2 T1CON REGISTER BIT DEFINITION

5–4 T1CPS1–T1CPS0—Select TMR1 prescaler value

11—1:8 prescaler 10—1:4 prescaler 01—1:2 prescaler 00—1:1 prescaler

3 T10SLEN—Set to enable TMR1’s built-in oscillator.

2 T1SYNCH—When TMR1CS is reset, the MR1

clock is synchronized to the instruction clock.

1 TMR1CS—When set, external clock is used.

0 TMR1ON—When set, TMR1 is enabled.

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 4

100- or 200-kHz crystals could be used with TMR1, but the capacitance required for thecircuit changes to 15 pF The TMR1 oscillator circuit is shown in Fig 16.4.

When TMR1 is running at the same time as the processor, the T1SYNCH bit should

be reset This bit will cause TMR1 to be synchronized with the instruction clock If theTMR1 registers are to be accessed during processor execution, resetting T1SYNCH willmake sure that there are no clock transitions during TMR1 access T1SYNCH must beset (no synchronized input) when the PIC microcontroller is in sleep mode In sleepmode, the main oscillator is stopped, stopping the synchronization clock to TMR1

In the PIC18 devices, TMR1 can be specified as the processor clock This feature isone way to implement a low-current operating mode (the PIC microcontroller will runwhile drawing less than 1 mA of current) without disabling the entire device and its built-

in functions Note that returning to the normal program oscillator will require the1024-instruction-cycle and optional 72-ms power-up reset delay that occurs when thePIC microcontroller clock starts up

The TMR1 prescaler allows 24-bit instruction cycle delay values to be used withTMR1 These delays can be either a constant value or an overflow, similar to TMR0

To calculate a delay, the formula

Delay = (65,536 – TMR1Init) x prescaler / T1frequency

is used, where the T1frequency can be the instruction clock, TMR1 oscillator, or anexternal clock driving TMR1 Rearranging the formula, the TMR1init initial value can

be calculated as

TMR1Init = 65,536 – (Delay x T1Frequency / prescaler)

When calculating delays, the prescaler will have to be increased until the calculatedTMR1Initis positive—this is similar as to how the TMR0 prescaler and initial valueare calculated for TMR0

Cext

Figure 16.4 TMR1 can be driven by its

own separate 32.768-kHz oscillator.

Trang 5

incre-The timer itself is not synchronized with the instruction clock like TMR0 and TMR1because it can be used only with the instruction clock This means that TMR2 can beincremented on a 1:1 instruction clock ratio

PR2 contains the reset, or count up to value The delay before reset is defined asDelay = prescaler x (PR2 + 1) / (Fosc / 4)

TMR1IF

TMR2ON

FOsc/4

TMR2 Prescaler T2CKPS1:

TOUTPS0

Figure 16.5 TMR2 block diagram.

TABLE 16.3 T2CON REGISTER BIT DEFINITION

6–5 TOUTPS3–TOUTPS0—TMR2 postscaler select

1111—16:1 postscaler 1110—15:1 postscaler

0000—1:1 postcaler

2 TMR2ON—When set, TMR2 is enabled 1–0 T2CKPS—TMR2 prescaler selection bits

1x—16:1 prescaler 01—4:1 prescaler 00—1:1 prescalerSimpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 6

If PR2 is equal to zero, the delay is

Delay = (prescaler x 256) / (Fosc / 4)

I do not usually calculate TMR2 delays with an initial TMR2INIT value Instead, Itake advantage of the PR2 register to provide a repeating delay and just reset TMR2before starting the delay

To calculate the delay between TMR2 overflows (and interrupt requests), the followingformula is used:

Delay = (prescaler x [PR2 + 1|256]) /((Fosc / 4) x postscaler)

Interrupts use the TMR2IE and TMR2IF bits that are similar to the ding bits in TMR1 These bits are located in the PIR and PIE registers Because ofthe exact interrupt frequency, TMR2 is well suited for applications that provide “bitbanging” functions such as asynchronous serial communications and PWM signaloutputs

correspon-Compare/Capture/

PWM (CCP) Module

Included with TMR1 and TMR2 is a control register and a set of logic functions (known

as the CCP) that enhances the operation of the timers and can simplify your

applica-tions This hardware may be provided singly or in pairs, which allows multiple tions to execute at the same time If two CCP modules are built into the PIC

func-microcontroller, then one is known as CCP1 and the other as CCP2 In the case where two CCP modules are built in, then all the registers are identified with the CCP1 or CCP2

prefix The CCP hardware is controlled by the CCP1CON (or CCP2CON) register,which is defined in Table 16.4

The most basic CCP mode is capture, which loads the CCPR registers (CCPR14,CCPR1C, CCPR2H, and CCPR2L) according to the mode the CCP register is set in.This function is illustrated in Fig 16.6 and shows that the current TMR1 value is savedwhen the specified compare condition is met

Before enabling the capture mode, TMR1 must be enabled (usually running withthe PIC microcontroller clock) The “edge detect” circuit in the figure is a 4:1 multi-plexor, which chooses between the prescaled rising-edge input or a falling-edge inputand passes the selected edge to latch the current TMR1 value and optionally request

an interrupt

In capture mode, TMR1 is running continuously and is loaded when the condition

on the CCPx pin matches the condition specified by the CCPxMS:CCPxM0 bits When

a capture occurs, then an interrupt request is made This interrupt request should beacknowledged and the contents of CCPRxH and CCPRxL saved to avoid having themwritten over and the value in them lost

Trang 7

Pin

Prescaler

Edge Detect 1:1 1:4 1:16

CCP Interrupt Request

CCPR1H CCPR1L

CCP1M3:CCP1M0

Figure 16.6 Block diagram of CCP capture circuitry.

Capture mode is used to time-repeating functions or in determining the length of aPWM pulse If a PWM pulse is to be timed, then when the start value is loaded, thepolarity is reversed to get to the end of the pulse When timing a PWM pulse, the TMR1clock must be fast enough to get a meaningful value with a high enough resolution thatthere will be an accurate representation of the timing

Compare mode changes the state of the CCPx pin of the PIC microcontroller whenthe contents of TMR1 match the value in the CCPRxM and CCPRxL registers asshown in Fig 16.7 This mode is used to trigger or control external hardware after aspecific delay

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 8

The most interesting use I’ve seen for the compare mode of the CCP is to turn thePIC microcontroller into a “watchdog” for a complex system As is shown in Fig 16.8,the PIC microcontroller controls reset to the system processor On power-up, the PICmicrocontroller holds the processor reset until Vcc has stabilized, and then the TMR1

is reset each time the system writes to the PIC microcontroller System reset is enabled

if after a time-out delay Vcc falls below a specific level

Using event-driven code, the PIC microcontroller application would look like this:

{

CCPRx = PowerUpDelay; // Put in Watchdog Delay

CCPxCON = 0b000001000; // Drive Pin Low and /then High

CCP2M3:CCP2M0 CCP2IF

Figure 16.7 Block diagram of CCP compare

circuitry.

PC System Processor PIC Micro

Figure 16.8 PC watchdog timer using PIC

microcontroller with the CCP compare circuitry

enabled.

Trang 9

When the PWM circuit executes, TMR1 counts until its most significant 8 bits are equal

to the contents of PR2 When TMR2 equals PR2, TMR2 is reset to 0, and the CCPx pin isset high TMR2 is run in a 10-bit mode (the 4:1 prescaler is enabled before PWM opera-tion) This 10-bit value is then compared with a program value in CCPRxM (along with thetwo DCxBx bits in CCPxCON), and when they match, the CCPx output pin is reset low

To set up a 65 percent duty cycle in a 20-kHz PWM executing in a PIC microcontrollerclocked at 4 MHz, the following steps are taken: First, the CCPRxM and PR2 values arecalculated for TMR2; the 4:1 prescaler must be enabled, resulting in a delay of

Trang 10

Then, 65 percent of 200 is 130, which is loaded into CCPRxM.

The code for creating the 65 percent 20-kHz PWM is

Note that in this code I don’t enable interrupts or have to monitor the signal output

In addition, you should notice that I don’t use the fractional bits To use the 2 leastsignificant bits, I assume that they are fractional values For the preceding example,

if I wanted to fine-tune the PWM frequency to 65.875 percent, I would recalculatethe value as a fraction of the total period

For a period of 200 TMR2 counts with a prescaler of 4, the CCPRxH valuebecomes 131.75 To operate the PWM, I would load 130 into CCPRxh (subtracting

1 to match TMR2’s zero start) and then the fractional value 0.75 into DCxB1 andDCxB0 bits I assume that DCxB1 has a value of 0.50 and that DCxB0 has a frac-tional value of 0.25 Thus, to get a PWM in this case, CCPRxH is loaded with 130,and DCxB1 and DCxB0 are both set Table 16.5 gives the fractional DCxBX bitvalues

CCPxPinCCPRxH

TMR2 Comparator

Reset

Figure 16.9 CCP PWM generation circuitry block

diagram.

Trang 11

SERIAL I/O 633

The least significant 2 bits of the PWM obviously are not that important unless a verysmall PWM “on” period is used in an application A good example of this is using thePWM module for an R/C servo In this case, the PWM period is 20 ms with an “on”time of 1 to 2 ms This gives a PWM pulse range of 5 to 10 percent, which makes theDCxB1 and DCxB0 bits important in positioning the servo accurately

Serial I/O

As with many microcontrollers, the PIC microcontroller has optional built-in serial I/Ointerfacing hardware These interfaces, which are available on certain PIC microcon-troller part numbers, allow a PIC microcontroller to interface with external memory andenhanced I/O functions (such as ADCs) or communicate with a PC using RS-232 As withother enhanced peripheral features, the serial I/O hardware is available on different PICmicrocontrollers, and the hardware may be available differently in different devices

SYNCHRONOUS SERIAL PORT (SSP)

SPI (its data stream is shown in Fig 16.10) is an 8-bit synchronous serial protocolthat uses 3 data bits to interface with external devices Data is clocked out, with the most

TABLE 16.5 CCP DCXBX BIT DEFINITION

Trang 12

significant bit first, on rising or falling edges of the clock The clock itself is generatedwithin the PIC microcontroller (master mode), or it is provided by an external deviceand used by the PIC microcontroller (slave mode) to clock out the data

The clock can be positive, as shown in the figure with a 0 idle or negative (high lineidle) with a 1 idle and the clock pulsing to 0 and back again The data receive latch isgenerally on the return to idle state transition

The BSSP module is the basic SSP module and provides data pulling on the return

to idle clock edge The original SSP module provides the ability to vary when data isoutput and read

Controlling the operation of the different SSP modules is the SSPCON register Indescribing the operational bits, note that I only describe the SPI-specific operations inTable 16.6

TABLE 16.6 SSP/BSSP SSPCON REGISTER BIT DEFINITION

7 WCOL—Write collision, set when new byte written to SSPBUF

while transfer is taking place.

6 SSPOV—Receive overflow, indicates that the unread byte is

SSPBUF overwritten while in SPI slave mode.

5 SSPEN—Set to enable the SSP module.

4 CKP—Clock polarity select, set to have a high idle.

3–0 SSPM3–SSPMO—SPI mode select

1xxx—I2C and reserved modes 011x—I2C slave modes 0101—SPI slave mode, clock = SCK pin, _SS not used 0100—SPI slave mode, clock = SCK pin, _SS enabled 0011—SPI master mode, TMR2 clock used

0010—SPI master mode, INSCK/16 0001—SPI master mode, INSCK/4 0000—SPI master mode, INSCK

Figure 16.10 SPI data and clock waveform.

Trang 13

SERIAL I/O 635

The block diagram for the SSP module is shown in Fig 16.11 In master mode, when

a byte is written to SSPBUF, an 8-bit most-significant-bit-first data transfer process isinitiated The status of the transfer can be checked by the SSPSTAT register BF flag;the SSPSTAT register is defined as shown in Table 16.7

The connection of a PIC microcontroller to an SPI bus is quite straightforward

In Fig 16.11, two PIC microcontrollers are shown with the SDO and SDI sides nected To initiate a byte transfer, a byte is written to the SSPBUF of the master.Writing to the SSPBUF of the slave will not initiate a transfer When SPI mode isenabled, the SDI, SDO, and SCK bits’ TRIS functions are set appropriately This isshown in Fig 16.12

con-The SSP SPI transfers can be used for single-byte synchronous serial transmits ofreceivers with serial devices In Fig 16.13 I show the circuit to TX a byte to a 74LS374

Reset

Reset

Figure 16.11 Block diagram of SSP SPI module.

TABLE 16.7 SSP/BSSP SSPSTAT BIT DEFINITION

7 SMP—Set to have data sampled after active to

idle transition; reset to sample at active-to-idle transition; not available in BSSP.

6 CKE—Set to TX data on idle-to-active transition;

else TX data on active-to-idle transition; not available in BSSP

0 BF—Busy flag, reset while SPI operation active.

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 14

wired as a serial in, parallel out shift register In Fig 16.14 I show a 74LS374 beingused with a 74LS244 as a synchronous parallel in, serial out register Both these oper-ations are initiated by a write to SSPBUF.

The SPI data receive operation may be immediately obvious To latch data into the74LS374, the I/O pin is driven high; this disables the 74LS374’s drivers, allowing theparallel data to be latched in When the I/O pin is low, the 74LS244’s drivers are dis-abled, and the 74LS374 behaves like a shift register

Figure 16.12 SPI master/slave connection.

Bit 0 Bit 1 Bit 7

Figure 16.13 Wiring connection to pass SPI data from

the PIC microcontroller to a serial-to-parallel converter.

Trang 15

SERIAL I/O 637

To show this, here is some code to read the input state of Fig 16.14 Note that I able the SSPEN bit when a transfer is not taking place to allow the I/O pin and SCK tostrobe in the data

bcf SCKbsf STATUS, RPObcf IOpinbcf SCKbcf STATUS, RP0

btfss SSPTAT, BF

; Data Ready in SSPBUF when Execution

; Here

When using the SSP, the data rate either can be selected as a multiple of the ing clock or use the TMR2 overflow output The actual timing depends on the hardwarethe PIC microcontroller SSP master is communicating with

Bit 0 Bit 1 Bit 7

I/O

6D 7Q

_OE

‘244

Figure 16.14 Wiring to bring data from a parallel-to-serial

converter into a PIC microcontroller.

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 16

When in slave mode, along with an external clock being provided, there is a mit reset pin known as _SS When this pin is asserted high, the SSP output is stopped(the SDO TRIS bit is changed to input mode), and the SSP is reset with a count of zero.When the bit is reset, the clock will start up again, and the original most significant bit

trans-is reset, followed by the remaining 7 bits

MASTER SSP AND I2C OPERATION

When I wrote the first edition of this book, one of the most significant concerns people hadwith the PIC microcontroller’s built-in hardware was the lack of master and multimaster-ing I2C capability This concern has been resolved with the availability of the MSSP(master SSP) module that is included in new PIC microcontroller devices The original SSPand BSSP will continue to be available in devices that currently have them, but the enhancedMSSP will be designed into all new devices that have the SSP module

When you look at the MSSP datasheets, you’ll see that there are 33 pages documentinghow the function works When you actually work with the MSSP, you will find that veryfew instructions are actually required to implement the function, and their use is quite easy

to understand In this section I will concentrate on a single master I2C interface and pointout the issues that you will have to be aware of when working in a multimaster system Five registers are accessed for MSSP I2C operation; they are the SSP control registers(SSPCON and SSPCON2 in Tables 16.8 and 16.9), the SSP status register (SSPSTAT), theSSP receive/transmit register (SSPBUF), and the SSP address register (SSPADD) Theseregisters are available in the SSP and BSSP but are slightly different for MSSP

The status of the transfer can be checked by the SSPSTAT register BF flag; the STAT register is defined in Table 16.10

SSP-I2C connections between the PIC microcontroller’s SSP-I2C SDA (data) and SCL (clock)pins is very simple, with just a pull-up on each line, as shown in Fig 16.15 I typicallyuse a 1-k resistor for 400-kHz data transfers and a 10k resistor for 100-kHz data rates.Note that before any of the I2C modes are used, the TRIS bits of the respective SDA

and SCL pins must be in input mode Unlike many of the other built-in advanced I/O

functions, MSSP does not control the TRIS bits Not having the TRIS bits in inputmode will not allow the I2C functions to operate

In master mode, the PIC microcontroller is responsible for driving the clock (SCL)line for the I2C network This is done by selecting one of the SPI master modes andloading the SSPADD register with a value to provide a data rate that is defined by theformula

I2C Data Rate = Fosc / (4 * (SSPADD + 1))

This can be rearranged to

SSPADD = (Fosc / (4 * I2C Data Rate)) - 1

Thus, in a 4-MHz PIC microcontroller, to define a 100-kHz I2C data rate, the ceding formula would be used to calculate the value loaded into SSPADD:

Trang 17

pre-SERIAL I/O 639

TABLE 16.8 MSSP SSPCON BIT DEFINITION

7 WCOL—Write collision, set when new byte written to SSPBUF

while transfer is taking place.

6 SSPOV—Receive overflow, indicates that the unread byte is

SSPBUF overwritten.

4 In I2C modes, if bit is reset, the I2C SCL clock line is

low—Keep this bit set.

1111—I2C 10-bit master mode/start and stop bit interrupts 1110—I2C 7-bit master mode/start and stop bit interrupts 1101—Reserved

1100—Reserved 1011—I2C master mode with slave idle 1010—Reserved

1001—Reserved 1000—I2C master mode with SSPADD clock definition 0111—I2C slave mode, 10-bit address

0110— I2C slave mode, 7-bit address 0101—SPI slave mode, clock = SCK pin, _SS not used 0100—SPI slave mode, clock = SCK pin, _SS enabled 0011—SPI master mode, TMR2 clock used

0010—SPI master mode, INSCK/16 0001—SPI master mode, INSCK/4 0000—SPI master mode, INSCK

SSPADD = (Fosc / (4 * I2C Data Rate)) – 1

Trang 18

TABLE 16.9 MSSP SSPCON2 BIT DEFINITION

7 GCEN—Enable interrupt when “general

call address” (0x0000) is received.

6 ACKSTAT—Received acknowledge status;

set when acknowledge was received.

5 ACKDT—Acknowledge value driven out on data write.

4 ACKEN—Acknowledge sequence enable bit, which

when set will initiate an acknowledge sequence on SDA/SCL; cleared by hardware.

3 RCEN—I2C receive enable bit

2 PEN—Stop condition initiate bit; when set, stop

condition on SDA/SCL; cleared by hardware.

1 RSEN—Set to initiate the repeated start condition on

SDA/SCL; cleared by hardware.

0 SEN—When set, a start condition is initiated on the

SDA/SCL; cleared by hardware.

TABLE 16.10 MSSP SSPSTAT BIT DEFINITION

7 SMP—Set to have data sampled after active-to-idle transition; reset to

sample at active-to-idle transition; not available in BSSP.

6 CKE—Set to TX data on idle-to-active transition; else TX data on

active-to-idle transition; not available in BSSP.

0 BF—Busy flag; reset while SPI operation active.

To send data from the PIC microcontroller to an I2C device using the MSSP, the lowing steps must be taken:

fol-1 The SDA/SCL lines must be put into input mode (i.e., their respective TRIS bitsmust be set)

2 I2C master mode is enabled This is accomplished by setting the SSPEN bit ofSSPCON and writing 0b01000 to the SSPM3–SSPM0 bits of the SSPCON register

Trang 19

7 The R/_W bit of SSPSTAT is polled until it is reset.

8 The ACK bit from the receiving device is checked by reading the ACKDT bit ofthe SSPCON2 register

9 A new start condition may have to be initiated between the first and subsequent databytes This is initiated by setting the SEN bit of SSPCON2 This bit is then polleduntil it is reset

10 Operations 6 through 8 are repeated until all data is sent or a NACK (negativeacknowledge) is received from the receiving device

11 A stop condition is initiated by setting the PEN bit of SSPCON2 This bit is thenpolled until it is reset

This sequence of operations is shown in Fig 16.16 Note that in the figure the SSPIFinterrupt request flag operation is shown In the preceding sequence, I avoid interrupts,but the SSPIF bit can be used either to request an interrupt or to avoid the need to polldifferent bits to wait for the various operations to complete

To receive data from a device employs a similar set of operations, with the only ference being that after the address byte(s) have been sent, the MSSP is configured toreceive data when the transfer is initiated:

dif-1 The SDA/SCL lines must be put into input mode (i.e., their respective TRIS bits must

1 K to

10 K Device 1 Device 2

Vcc Vcc

Figure 16.15 Typical I2C connection to a PIC

microcontroller with separate pull-up resistors.

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 20

3 A start condition is initiated by setting the SEN bit of SSPCON2 This bit is thenpolled until it is reset.

4 SSPBUF is loaded with the address of the device to access Note that for many I2Cdevices, the least significant bit transmitted is the read/write bit The R/_W bit ofSSPSTAT is polled until it is reset (which indicates that the transmit has beencompleted)

5 The ACK bit from the receiving device is checked by reading the ACKDT bit ofthe SSPCON2 register

6 SSPBUF is optionally loaded with the secondary address within the device beingread from The R/_W bit of SSPSTAT is polled until it is reset

7 If a secondary address was written to the device being read from, reading theACKDT bit of the SSPCON2 register checks the ACK bit from the receiving device

8 A new start condition may have to be initiated between the first and subsequent databytes This is initiated by setting the SEN bit of SSPCON2 This bit is then polleduntil it is reset

9 If the secondary address byte was sent, then a second device address byte (with theread indicated) may have to be sent to the device being read The R/_W bit of SSP-STAT is polled until it is reset

10 The ACKDT will be set (NACK) or reset (ACK) to indicate whether or not the databyte transfer is to be acknowledged in the device being read

11 The RCEN bit in the SSPCON2 register is set to start a data byte receive The BFbit of the SSPSTAT register is polled until the data byte has been received

Figure 16.16 MSSP I2C data address/transmission.

Trang 21

Figure 16.17 show the data receive operation waveform

Along with the single master mode, the MSSP is also capable of driving data in timaster mode In this mode, if a data write “collision” is detected, it stops transmitting

mul-data and requests an interrupt to indicate that there is a problem An I2C collision is the

case where the current device is transmitting a high data value, but there is a low datavalue on the SDA line This condition is shown in Fig 16.18 The WCOL bit of theSSPCON register indicates that the collision has taken place

When the collision occurs, the I2C software must wait some period of time (I use thetime required to transmit 3 bytes) before polling the SDA and SCL lines to ensure thatthey are high and then initiating a “repeated start condition” operation A repeated startcondition is the process of restarting the I2C data transfer right from the beginning (even

if it was halfway through when the collision occurred)

Figure 16.17 MSSP I2C data address/read.

Figure 16.18 I2C MSSP collision response.

SDA

SCL

BCLIF

Expected “High” Data Value

Actual “Low” Data Value

Request Interrupt for Bus Collision Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 22

USART ASYNCHRONOUS SERIAL COMMUNICATIONS

The PIC microcontroller’s universal asynchronous synchronous receiver transmitter (USART)hardware allows you to interface with serial devices such as a PC using RS-232 or for syn-chronous serial devices, with the PIC microcontroller providing the clock or having anexternal clock drive the data rate The USART module is best suited for asynchronous serialdata transmission, and in this section, I will be concentrating on its capabilities

Asynchronous data has been discussed elsewhere in more detail in this book The PICmicrocontroller transmits and receives NRZ (no return to zero) asynchronous data inthe format shown in Fig 16.19 The figure shows 5 bits of serial data—the PIC micro-controller can transfer 8 or 9 bits although by setting the high-order bits of the outputword; smaller data packets can be sent

If the USART is used for synchronous data, the bits can be latched into the tion on the failing edge of the clock In both these cases, a byte is sent within a packet.While I have discussed packet decoding in detail elsewhere in this book, in this sectionI’ll tend to treat the packet encoding and decoding as a “black box” part of the USARTand deal with how the data bytes are transmitted and received

destina-There are three modules to the USART: the clock generator, the serial data mission unit, and the serial data reception unit The two serial I/O units require the clockgenerator for shifting data out at the write interval The clock generator’s block diagram

Start Bit

Data

Parity Bit

Stop Bit Bit 0 Bit 1 Bit 0 Bit 3 Bit 4

Figure 16.19 Baudot asynchronous serial data.

Clock Output

SPBRG

/4

Receiver Sensor Clock

1

0 1

0

Figure 16.20 USART clock block diagram.

Trang 23

SERIAL I/O 645

Unfortunately, in the PIC microcontroller USART, the bits used to control the ation of the clock generator, transmit unit, and receive unit are spread between theTXSTA and RCSTA registers, along with the interrupt enable and acknowledge regis-ters The individual bits will be defined at the end of this section, after the three func-tions of the USART are explained

oper-For asynchronous operation, the data speed is specified by the formulaData Rate = Fosc / (16 x (4 ** (1 – BRGH)) x (SPBRG + 1))

This formula can be rearranged so that the SPBRG value can be derived from thedesired data rate:

SPBRG = Fosc / (Data Rate x 16 x (4 ** (1 - BRGH))) – 1

Thus, for a PIC microcontroller running at 4 MHz, the SPBRG value for a 1,200 bpsdata rate with BRGH reset is calculated as

SPBRG = Fosc / (Data Rate x 16 x (4 ** (1 – BRGH))) – 1

= 4 MHz / (1200/sec x 16 (4 ** (1 – 0))) – 1

= 4 (10**6) / (1200 x 16 x 4) – 1

= 52.0833 – 1

= 51.0833

With 51 stored in SPBRG, there will be an actual data rate of 1,201.9 bps, which has

an error rate of 0.16 percent to the target data rate of 1,200 bps This error is well withinlimits to prevent any bits from being read in error

There is one thing that I should note about the USART clock generator, and that isthat for many “early” PIC microcontroller part numbers, the BRGH bit does not workproperly when it is set This is not an issue with PIC microcontroller part numbersissued after 2000, but you should be aware of this if you are working with somethinglike a PIC16C74, which was released around 1996—the USART will not work prop-erly with the BRGH bit set If you are working with EPROM (C technology indicator

in the part number), I recommend that you always develop your applications with theBRGH bit reset If you need data rates faster than what is possible for the PIC micro-controller clock (2,400 bps is the maximum for a 4-MHz clock), I recommend that youincrease the PIC microcontroller’s clock speed rather than risk setting BRGH in a device

in which it may not work properly

The transmission unit of the USART can send 8 or 9 bits in a clocked nous) or unclocked (synchronous) manner The block diagram of the hardware isshown in Fig 16.21 If the synch bit is set, then data is driven out on the PIC micro-controller’s RX pin, with the data clock being either driven into or out of the TX pin.When data is loaded into the TXREG, if CSRC is reset, then an external device willclock it out If CSRC can be shifted 8 or 9 bits at a time, with the operation stoppingwhen the data has been shifted out An interrupt can be requested when the opera-tion is complete

(synchro-Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 24

In asynchronous mode, once data is loaded into the TXREG, it is shifted out with a

0 leading start bit in NRZ format The transmit hold register can be loaded with a newvalue to be sent immediately following passing of the byte in the transmit shift regis-ter This single buffering of the data allows data to be sent continuously without the soft-ware polling the TXREG to find out when is the correct time to send out another byte.USART transmit interrupt requests are made when the TX holding register is empty.This feature is available for both synchronous and asynchronous transmission modes.The USART receive unit is the most complex of the USART’s three parts This com-plexity comes from the need for it to determine whether or not the incoming asyn-chronous data is valid or not using the pin buffer and control unit built into the USARTreceive pin The block diagram for the USART’s receiver is shown in Fig 16.22

If the port is in synchronous mode, data is shifted in either according to the USART’sclock or using an external device’s clock

For asynchronous data, the receiver sensor clock is used to provide a polling clockfor the incoming data This 16 time data rate clock’s input into the pin buffer and

TX9

TX Shift Register

TX Holding Register (TXREG)

TXIF

Synch TX RX

Synch

Synch CSRC

Figure 16.21 USART transmit hardware block diagram.

Figure 16.22 USART receive hardware block diagram.

Pin Buffer and Control

Synch 0 1

Receive Holding Register (RCREG)

Receive Shift Register

RCIF

ERROR Indicator CREN

Trang 25

SERIAL I/O 647

control unit provides a polling clock for the hardware When the input data line is lowfor three receive sensor clock periods, data is then read in from the “middle” of the nextbit, as shown in Fig 16.23 When data is being received, the line is polled three times,and most states read is determined to be the correct data value This repeats for the 8 or

9 bits of data, with the stop bit being the final check

As with the TX unit, the RX unit has a holding register, so if data is not processedimmediately and an incoming byte is received, the data will not be lost However, if the

data is not picked up by the time the next byte has been received, then an overrun error will occur Another type of error is the framing error, which is set if the stop bit of the

incoming NRZ packet is not 0 These errors are recorded in the RCSTA (receiver status)register and have to be reset by software

In some PIC microcontrollers, the USART receive unit also can be used to receivetwo synchronous bytes in the format data:address, where address is a byte des-tined for a specific device on a bus When the adden bit of the RCSTA register is set,

no interrupts will be requested until both the address and data bytes have been received

To distinguish between the bytes, the ninth address bit is set (while the ninth bit of databytes is reset) When this interrupt request is received, the interrupt handler checks thedevice address for its value before responding to the data byte

To control the USART, two registers are used explicitly The TXSTA (transmitterstatus) register is defined in Table 16.11, and the RCSTA (receiver status) register isdefined in Table 16.12

To set up an asynchronous serial communication transmit, the following code is used:bsf STATUS, RPO

bcf TXSTA, SYNCH ; Not in Synchronous mode

bcf TXSTA, BRGH ; BRGH =0

Start Bit

Overspeed Clock

Glitch Check

Bit Read

Bit Read

Bit Read

Bit Read

Bit Read

Parity Read

Data Process

Figure 16.23 Asynchronous packet detection and data reading are mented using a clock that runs at 16 times the data rate and samples the data

imple-at whimple-at it calculimple-ates as the middle of each dimple-ata bit.

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 26

movlw DataRate ; Set USART Data Rate

movwf SPBRG

bcf STATUS, RPO ; Enable serial port

bsf RCSTA ^ 0x080, SPEN

bsf STATUS, RPO

bcf TXSTA, TX9 ; Only 8 bits to send

bsf TXSTA, TXEN ; Enable Data Transmit

bcf STATUS, RPO

TABLE 16.11 USART TXSTA BIT DEFINITION

7 CSRC—Clock source select used in synchronous mode;

when set, the USART clock generator is used.

6 TX9—Set to enable 9-bit serial I/O.

5 TXEN—Set to enable data transmission.

4 SYNC—Set to enable synchronous transmission.

2 BRGH—Used in asynchronous mode to enable fast data

transmission; it is recommended to keep this bit reset.

1 TRMT—Set if the transmission shift register is empty.

0 TXD—Nine-bit of transmitted data.

TABLE 16.12 USART RCSTA BIT DEFINITION

7 SPEN—Set to enable the USART.

6 RX9—Set to enable 9-bit USART receive.

5 SREN—Set to enable single-byte synchronous data

receive; reset when data has been received.

4 CREN—Set to enable continuous receive.

3 ADDEN—Set to receive data address information; may be

unused in many PIC microcontroller part numbers.

2 FERR—Framing error bit.

1 OERR—Overrun error bit.

0 RX9D—Received ninth bit.

Trang 27

ANALOG I/O 649

To send a byte in WREG, use the following code:

btfss TXSTA, TRMTgoto $ - 1 ; Wait for Holding Register to

; become Free/Empty

; When the Transmit Shift Register

; is Empty, byte will be sent

In the data send code, the TRMT bit, which indicates when the TX holding register

is empty, is polled When the register is empty, the next byte to send is put into the mit shift register This polling loop can be eliminated by setting the TXIE bit in the inter-rupt control register and then in your interrupt handler, checking to see if the TXIF flag

trans-is set before saving a byte in TXREG

To set up an asynchronous read, the following code is used:

bsf STATUS, RPO

bcf TXSTA, SYNCH ; Want Asynch Communications

bcf TXSTA, BRGH ; Low Speed Clock

movwf SPBRG

bsf RCSTA ^ 0x080, SPEN ; Enable Serial Port

bcf TCSTA ^ 0x080, RX9 ; Eight Bits to Receive

To wait to receive data and then store the incoming byte in WREG, you can use thefollowing code:

btfss PIR1, RXIF ; Wait for a Character to be

The ADC built into the PIC microcontrollers can sample and process signals as fast

as 25 kHz or so accurately Looking at the ADC’s specifications, you might feel that thebest analog signal frequency that can be processed is 50 kHz (because the examples inSimpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 28

the datasheet show a 19-ms acquisition/processing time) I specify 25 kHz because ofNyquist’s sampling theorem, which says that to sample an analog signal properly, youmust sample at twice the highest data frequency expected in the signal.

Thus 25 kHz may seem like a reasonably fast signal to sample; after all, speechonly requires 2.5 kHz, and full-spectrum audio is only up to about 18 kHz For mostelectronic signals, though, 25 kHz is actually quite a low speed and not very useful(e.g., the AM radio band starts at 66 kHz and NTSC monochrome composite videoruns at 3.5 MHz)

Along with the slow ADC sampling and processing speeds, digital signal ing (DSP) algorithms are difficult to implement on the PIC microcontroller because

process-of the processor’s ability to interface with only 8 bits process-of data and lack process-of multiply tions except in the PIC18 Limited DSP functions can be implemented, but they will

instruc-be challenging for data input waveforms that are faster than 1 kHz or so For these sons, I don’t recommend that the PIC microcontroller’s built-in ADCs be used foranything other than measuring dc voltages With up to 12 bits available with built-inADCs, the PIC microcontroller is very well suited for making accurate measurement

rea-of dc analog voltages

Personally, I find the Microchip documentation to be quite complex and difficult tofigure out how to use the built-in ADC hardware for applications In the following sec-tions I’ll go through how the analog input and processing works on the PIC microcon-troller, and I provide some hints for using the features without having to wade throughall the documentation

VOLTAGE COMPARATORS

The simplest way of inputting analog voltages in the PIC microcontroller is to use theoptional comparators that indicate when a voltage is greater than another voltage Theinputs compared can be switched between different I/O pins as well as ground or a ref-erence voltage that can be generated inside the PIC microcontroller chip Enablingbuilt-in comparators is a very straightforward operation, with the only prerequisitebeing that the pins used for the analog compare must be in input mode Comparatorresponse is virtually instantaneous, which allows alarm or other fast responses fromchanges in the comparator inputs

The comparator works very conventionally, as shown in Fig 16.24 If the value of the+inputis greater than the –input, the output is high There are two comparators inthe PIC16C82X controlled by the CMCON register, which is defined in Table 16.13 TheCIS and CM2–CM0 bits work together to select the operation of the comparators, andthe resulting I/O pin configurations are listed in Table 16.14

On power-up, the comparator CM bits are all reset, which means that RA0 to RA3are in analog input mode If you want to disable analog input, the CM bits must be set(write 0x007 to CMCOM)

Interrupts can be enabled that will interrupt the processor when one of the comparatoroutput changes This is enabled differently for each PIC microcontroller with built-in com-parators Like the PORTB change on interrupt, after a comparator change interrupt requesthas been received, the CMCOM register must be read to reset the interrupt handler

Trang 29

ANALOG I/O 651

Along with comparing to external values, the PIC16C62x also can generate a ence voltage (Vref in the preceding table) using its own built-in 4-bit digital-to-analogconverter The digital-to-analog converter circuit is shown in Fig 16.25

refer-The Vref control bits are found in the VRCON register and are defined in Table 16.15 The Vref output depends on the state of the VRR bit The Vref voltage output can beexpressed mathematically if VRR is set as

Vref = Vdd*(Vfcon & 0x00F)/24

or if it is reset as

Vref = Vdd*(8 + (Vrcon & 0x00F))/32

Note that when VRR is set, the maximum voltage of Vref is 15/24 of Vdd, or just lessthan two-thirds Vdd When VRR is reset, Vref can be almost three-quarters of Vdd

Input Signal

Vref

Comparator

Output

+ – ComparatorOutputComparator

VrefInput Signal

Figure 16.24 A comparator returns a digital value

each time an analog voltage is at a specific value.

TABLE 16.13 COMPARATOR CMCON REGISTER

BIT DEFINITIONS

BIT DESCRIPTION

7 C2OUT—Comparator 2 output (high if + > –).

6 C1OUT—Comparator 1 output (high if + > –).

Trang 30

TABLE 16.14 COMPARATOR MODULE I/O SPECIFICATION

a For CM2–CM0 equal to 000, RA3 through RA0 cannot be used for digital I/O.

b For CM2–CM0 equal to 000, RA2 and RA1 cannot be used for digital I/O.

c RAO and RA3 can be used for digital I/O.

d RA3 can be used for digital I/O.

e RA3 is a digital output, same as comparator 1 output.

f RA4 is the open-drain output of comparator 2.

g RA0 and RA3 can be used for digital I/O.

h RA1 and RA2 can be used for digital I/O.

Vdd

Figure 16.25 The comparator Vref circuit selects an

analog voltage from a resistor divider.

Trang 31

ANALOG I/O 653

Vref can be output on RA2, but you probably will want it to be used internally onlywith the comparators because using it to drive RA2 requires extra current from theapplication If an analog voltage output is required, I have used the comparator module’sVref in several applications, and I also have used a PWM output driving a resistor andcapacitor network In either case, the resulting analog voltage will have to be bufferedusing something like a unity gain op-amp circuit because the current output capabili-ties are very modest

ANALOG INPUT

When I first started using the analog-to-digital converter (ADC) built into the PIC16C7xdevices, I felt like the feature was very complex and difficult to work with When youread through the Microchip datasheets on the ADC that is built into the different PICmicrocontroller part numbers, you will find that there are multiple 20-page descriptions

of the ADC Each of these descriptions is slightly different in terms of register locationsand bit operations depending on the part number and its features (such as the number

of I/O pins that can provide ADC input), but they all work essentially the same way Inthis section I want to give you a brief overview of the basics of ADCs, along with theimportant concepts that you will have to know to use them in your applications At theend of this section I have provided some sample code to help guide you in using theADC successfully in your own applications

Some time ago, it was easy to tell which PIC microcontroller part numbers had anADC built into them; they were the ones with a 7 as the character after the C or F ofthe part number Now, many different PIC microcontrollers have a built-in ADC thatwill indicate an analog voltage level from 0 to Vdd with 8- or 10-bit accuracy, and youwill have to look at their datasheets to understand which ones have this capability The ADC inputs usually are situated in the PORTA I/O pins and can be used as eitherdigital I/O or analog inputs The actual bit accuracy, utilization of pins, and operatingspeed are a function of the PIC microcontroller part number and the clock speed at which

TABLE 16.15 COMPARATOR VRCON REGISTER

BIT DEFINTIONS

7 VREN—Vref, enable when set.

6 VROE—Vref output, enable when set RA2–Vref.

5 VRR—Vref range select.

1—Low range.

0—High range.

3–0 VR3–VR0—Voltage selection bits.

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 32

the PIC microcontroller runs When a pin is configured for analog input, it follows themodels shown in Fig 16.26.

Rs in the Vsource circuit is the in-line resistance of the power supply In order to get

reasonable times for charging the ADC’s holding capacitor, this value should be less than

10 k If you look through the ADC documentation, you will find that the time requiredfor the holding capacitor to load the analog voltage and to stabilize is

Tack = 5 ms + [(temp – 25C) x 0.05 ms/C] + (3.19C x 10**7) x (8k + Rs)

which works out to anywhere from 7.6 to 10.7 µs at room temperature I usually avoidthis calculation altogether and assume that at least 12 µs is required for the holding capac-itor voltage to stabilize to the input voltage

Once the voltage is stabilized within the holding capacitor, a test for each bit is made;9.5 cycles are required to do an 8-bit conversion The bit conversion cycle time (known

as TAD) can be anywhere from 1.6 to 6.4 µs and can use either the PIC

microcon-troller’s instruction clock or a built-in 250-kHz RC oscillator To get a valid TAD timeusing the PIC microcontroller’s instruction clock, a 2, 8, or 32 prescaler is built into theADC For example, a 4-MHz clock using the divide by 8 prescaler will have a 2-µs TADtime, which is acceptable for the ADC If the divide by 2 counter were used, the TADwould be 500 ns, which is much too fast for the ADC to work correctly

The built-in 250-kHz oscillator is used to carry out the ADC conversion when the PICmicrocontroller is asleep Microchip recommends that the PIC microcontroller be put tosleep during the ADC conversion for maximum accuracy (and minimum internal voltage

or current upsets) If the PIC microcontroller is put to sleep, then the minimum conversiontime is much longer than what is possible using the built-in clock because the PIC micro-controller has to restart when the ADC completion interrupt has been received

The minimum conversion time is defined as the total time required for the holdingcapacitor to stabilize at the input voltage and for the ADC operation to complete.Assuming that a 12-s holding time could be implemented along with a 15-s ADCconversion time, the maximum time is about 27 s, or 37,000 ADC samples per secondcan be implemented

RIC = 1 K

Rs = 7K “On Resistance”

Holding Cap = 51.2 pF Switch

Figure 16.26 The equivalent to the PIC microcontroller ADC input circuitry.

Trang 33

ANALOG I/O 655

This is not fast enough for most electronics operations and probably not fast enoughfor audio decoding (especially with the slow digital processing capabilities of the PICmicrocontroller’s processor) I’m pointing this out to indicate that the PIC microcon-troller’s ADC is best used for relatively slowly changing inputs

To measure analog voltages, the analog input pins of the PIC microcontroller, whichare usually in port A, have to be set to analog input on power-up; the analog input pinsnormally are set to analog input and not digital I/O To specify the modes, the ADCON1register is written to For example, in Table 16.16 I have listed the different ADCON1bit values and corresponding PORTA pin operational modes in the PIC16C71 When I use an ADC-equipped PIC microcontroller in an application where all thePORTA pins have to be digital I/O, I normally set the pins to digital operations right atthe start of the application, before writing to the TRISA register or initializing the state

of the pins Until the pins are changed to digital I/O, they always will return 0 and cannot

be set to an output value of 1

Normally, when the ADC is used in a PIC microcontroller, the voltage reference isfrom ground to Vdd If this range is not acceptable, or if the power supply is unreliable,

a new reference voltage can be specified In some devices that are equipped with ADCs,the lower-voltage reference can be specified externally as well The bit definition ofADCON1 is part-number-specific and changes based on the device part number, number

of PORTA pins, and the number of bit resolution provided by the ADC There is onegenerality that you should be aware of: When the ADCON1 bits are all set, the PORTAI/O pins are all put into digital operation

The ADCON0 register is used to control operation of the ADC The bits of the registertypically are defined as in Table 16.17

The ADC consumes power even when it is not being used, and for this reason, if theADC is not being used, ADON should be reset

If the PIC microcontroller’s ADC is capable of returning a 10-bit result, the data isstored in the two ADRESH and ADRES registers When 10-bit ADC results are avail-able, the data can be stored in ADRESH/ADRESL in two different formats The first is

to store the data “right justified” with the most significant 6 bits of ADRESH loaded with

0 and the least two significant bits loaded with the two most significant bits of the result.This format is useful if the result is going to be used as a 16-bit number, with all the bitsused to calculate an average

TABLE 16.16 PORTA BIT MODES AS DEFINED BY THE

ADCON1 BITS OF A PIC16C71

00 Analog<P> Analog Analog AnalogSimpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 34

The second 10-bit ADC result format is “left justified,” and the 8 most significant bitsare stored in ADRESH This format is used when only an 8-bit value is required in theapplication, and the two least significant bits can be “lopped” off or ignored

To do an analog to digital conversion, the following steps should be taken:

1 Write to ADCON1 indicating what the digital I/O pins are and which are the analogI/O pins At this time, if a 10-bit conversion is going to be done, then set the formatflag in ADCON 1 appropriately

2 Write to ADCON0, setting ADON, resetting ADIF and GO/_DONE, and specifyingthe ADC TAD clock and the pin to be used

3 Wait for the input signal to stabilize

4 Set the GO/_DONE bit If this is a high-accuracy measurement, ADIE should beenabled for interrupts and then the PIC microcontroller put to “sleep.”

5 Poll GO/_DONE until it is reset (conversion done)

6 Read the result from ADRES and optionally ADRESH

To read an analog voltage from the RAO pin of a PIC167C1 running a 4-MHz PICmicrocontroller, the following code would be:

01—FOSC/8 00—FOSC/2 5–3 CHS2–CHS0—Bits used to select which analog input is to

be measured; these bits and their operation are part number specific.

2 GO/_DONE—Set bit to start ADC conversion; reset by

hardware when ADC conversion is complete.

1 ADIF—Set on completion of ADC conversion and requests

an interrupt.

0 ADON—Set to enable the ADC.

Trang 35

PARALLEL SLAVE PORT (PSP) 657

movlw 5

goto $ - 2

As you read the Microchip datasheets on the ADC, you will see that there are methods

of implementing shorter, less accurate conversions I do not recommend implementing theseconversions because they decrease the accuracy of the ADC conversion but do not affectthe biggest delay to doing the ADC conversion—the delay for the holding capacitor Thismeans that while the ADC can operate with a modest increase in speed, the total number

of samples per second that can be made with the ADC cannot be increased substantially

Parallel Slave Port (PSP)

One of the most interesting features of the 40-pin mid-range and PIC18 PIC controllers is the parallel slave port (PSP) that is built into the PORTD and PORTE I/Opins This feature allows the PIC microcontroller to act like an intelligent peripheral toany 8-bit data bus device

micro-The PSP is very easy to wire up with separate chip select and read/write pins forenabling the data transfer The block diagram of the PSP is shown in Fig 16.27

_CS-To Address Decode _WR- Negative Active Write Strobe _RD- Negative Active Read Strobe

8x Bi-Directional Data Bits

In Reg Out Reg

Figure 16.27 The hardware internal to the PIC

micro-controller that implements the parallel slave port (PSP).

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 36

The actual read/write I/O operations take place as you would expect for a typical I/Odevice connected to a microprocessor’s address/data control bus A read and write oper-ation waveform is shown in Fig 16.28 The minimum access time is one clock (notinstruction clock) cycle For a PIC microcontroller running at 20 MHz, the minimumaccess time is 50 ns.

To enable the parallel slave port, the PSP mode bit of the TRISE register must be set.When this bit is set, port D becomes driven from the _CS, _RD, and _WR bits, whichare RE2, RE1, and RE0, respectively When the PSP mode bit is set, the values inPORTD, PORTE, TRISD, and TRISE are ignored

PSP mode should be enabled the whole time the PIC microcontroller is active.Changing the pins between modes could cause bus operation problems with the con-trolling device and the device connected to PORTD and PORTE bits In addition, thecontents of PORTD and PORTE are unknown on return from PSP mode

When PSP mode is enabled and _CS and _RD are active, PORTD drives out the tents of OUTREG When OUTREG (which is at PORTD’s address) is written to, the

con-OBF (output buffer full) bit of TRISE is set This feature, along with the input data flags

in TRISE, is not available in all devices The PBF bit will become reset automaticallywhen the byte in the OUTREG is read by the device driving the external parallel bus.When a byte is written into the parallel slave port (_CS and _WR are active), the value

is saved in INREG until it is overwritten by a new value If the optional status registersare available, the IBF bit is set when the INREG is written to and cleared when the byte

in INREG is read If the byte is not read before the next byte is written into INREG, theIBOV bit, which indicates the overwrite condition, is set

In older PIC microcontrollers that have a PSP port, the IBF, OBF, and IBOV bits arenot available in TRISE While I recommend only using parallel slave port devices thathave the IBF, OBF, and IBOV flags, there will be times when this is not possible If youuse a part that doesn’t have these bits, make sure that you create a method or protocolfor sending data that ensures that no data byte transfers are missed This can be done

by sending the complement of the previous byte to the PIC microcontroller before the

Data Out

of PIC Micro

“_RD” Ignored

by PIC Micro

Figure 16.28 The waveform input from the host

proces-sor to the PSP-enabled PIC microcontroller.

Trang 37

IN-CIRCUIT SERIAL PROGRAMMING (ICSP) 659

next byte is sent and responding to reading the byte in OUTREG by writing its plement back into INREG

com-With the parallel slave port working, all the other PIC microcontroller resourcesare available This means that you can use ADCs (making sure that the PORTE bitsare not set for analog input, which will cause problems with the parallel slaveport), serial I/O, and other features that allow advanced I/O to and from the PICmicrocontroller In Chap 21 I use the PSP to implement a custom serial interface

pro-The ICSP connector for mid-range PIC microcontrollers is a 5-pin, 0.100” “spacing”IDC connector with the pin-out listed in Table 16.18 The ICSP connector can beadded to any application circuit, and it allows even simple programmers to load PICmicrocontrollers with application code without the need of ZIF sockets or SMT partadapters

In Chap 4, operation of the pins was described; I do want to bring to your attentionthe LVP pin, which allows the PIC microcontroller to be programmed without a highprogramming voltage This feature can be useful if you have enough I/O pins availablefor your application because both the _MCLR and LVP pins will be unusable, whereaswith high-voltage programming, LVP will act as a normal digital I/O pin, and _MCLRcould be used as an input (if this feature is available in the PIC microcontroller partnumber)

TABLE 16.18 ICSP CONNECTOR PINOUT

Trang 38

This page intentionally left blank

Trang 39

to work with Under the covers of the various products around your home are anotherset of very common devices with standard interfaces These devices and their interfacesprovide additional functionality to the microcontrollers built into the products, andbeing standard devices with standard interfaces, the amount of effort to add them to appli-cations is actually quite minimal.

In this chapter I will be introducing you to a number of user interface and hardware tion expansion devices that you can use in your own applications Later in this book when

func-I start introducing you to different applications, you will see these devices in action Thepurpose of this chapter is to give you a more generic perspective on this aspect of PICmicrocontroller application development and help you to understand the requirements ofthese devices and what impact they will have on the application development process

LEDs

The most common form of output from a microcontroller is the LED As an output device,

it is cheap and easy to wire to a microcontroller Generally, LEDs require anywhere from

5 to 25 mA of current to light (which is often within the output sink/source specificationfor most microcontrollers) What you have to remember, though, is that LEDs are diodes,which means current flows in one direction only The typical circuit that I use to control

an LED from a PIC microcontroller input-outpur (I/O) pin is shown in Fig 17.1

Copyright © 2008, 2002, 1997 by The McGraw-Hill Companies, Inc Click here for terms of use

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com

Trang 40

With this circuit, the LED will light when the microcontroller’s output pin is set to

0 (ground potential) When the pin is set to input or outputs, a 1, the LED will be turnedoff This is a general convention for operation that came about owing to simple tran-sistor logic and the Intel 8051, which could not source a significant amount of current;

it could only sink enough current to turn on an LED The popularity of this approachhas lead to a generation of engineers who design circuitry that turns on LEDs when thelogic output is low If you are new to electronics, this will definitely seem counterintu-itive, but it is something that you are going to have to accept (like the fact that current

is measured in the direction opposite to electron flow)

The 220- resistor is used for current limiting and will prevent excessive currentthat can damage the microcontroller, LED, and power supply The reason why I use a220- resistor is because when I was a student, I was told that I could never go wrongwith it—this is true, but it is also equally true for 330 and 470  in most applications.When you are designing your own applications, you should look at the LED’s datasheet

to understand its forward voltage as well as “on current” to properly calculate the bestcurrent-limiting resistor value

To calculate the correct voltage, start with the formula:

Vapplied VLED ILED Rcurrent limiting

or rearranged to find Rcurrent limiting, the formula becomes

Rcurrent limiting (Vapplied– VLED)/ILED

Using this formula for an LED that has a 1.5-V forward voltage and lights at 5 mA

in a system that provides 3.3 V of power, the current-limiting resistor can be calculated:

Rcurrent limiting (3.3 V – 1.5 V)/5 mA  360 

In this situation, I would use a 330- current-limiting resistor

Figure 17.1 The basic circuit for driving

an LED consists of a current-limiting resistor

and a PIC microcontroller I/O pin capable of

sinking enough current to turn on the LED.

220 Ohms Microcontroller

Vcc

Ngày đăng: 12/08/2014, 23:21

TỪ KHÓA LIÊN QUAN