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

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

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

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

Добавлен: 15.06.2025

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

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

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

344 The Quintessential PIC Microcontroller

mode for older devices, such as the PIC16C74/74A,13 as receive errors can occur.

Actually, the SPBRG produces higher frequencies than the base baud rate, to enable the USART to take three samples around bit midpoints and adopt a majority decision. In the low-speed mode a sampling rate of ×16 is used, as is the case for newer devices in the high-speed mode. Older devices use ×4 for the high-speed mode.

To illustrate how to use the USART we will repeat our GETCHAR and PUTCHAR subroutines using hardware. Firstly, in the main program we have to set up the Serial Port Baud Rate Generator and both Transmit and Receive Status/Control registers. Assuming, as in Program 12.10, the programmer has defined the constants XTAL and BAUD then we can let the assembler evaluate the arithmetic to give us the value of X to put in the SPBRG. With this in mind, the initialization code would look something like:

include "p16c74b.inc"

#define

BAUD

d’4800’

; For example 4800 baud rate

#define

XTAL

d’8’

; 8MHz crystal

#define

X

((XTAL*d’1000000’)/(d’64’*BAUD))-1

START bsf

STATUS,RP0

; Change to Bank1

bsf

TRISC,7

; RX pin is set as an input

bcf

TRISC,6

; TX is set as an output

movlw

X

; Move X to Baud Rate Generator

movwf

SPBRG

movlw

b’00100000’

; 8 data bits, TX enabled

movwf

TXSTA

; Low speed SPBRG mode

bcf

STATUS,RP0

; Back again to Bank0

movlw

b’10010000’

; USART enabled, 8 data bits

movwf

RCSTA

; Receiver enabled

With the USART enabled the subroutines are coded in Program 12.12. PUTCHAR is simply a matter of polling TXIF waiting for it to go to 1 and then copying the datum to the TranSmitter REGister.

The input GETCHAR is a little more complex if some error checking is to be incorporated. The subroutine polls the state of RCIF which goes to 1 whenever there is data to be read. Also returned is the variable ERR which is 00h if there is no problem, −1 if a Framing error occurred, −2 if a Overflow situation is sensed and −3 if both errors occurred. In these latter situations OERR is zeroed by resetting the receiver logic. After the error conditions have been checked the data is read from the ReCeive REGister. This is done after checking to avoid altering the appropriate error flags.

13For example, the receive logic sampling rate of the PIC16C74B has been altered to eliminate these errors.


12. One Bit at a Time 345

Program 12.12 The USART-based I/O subroutines.

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

;* FUNCTION: Transmits one 8-bit byte in asynchronous format *

; *

RESOURCE:

PIC USART

*

;

*

ENTRY

:

8-bit datum in DATA_OUT

*

;

*

EXIT

:

Contents of DATA_OUT unchanged, byte TXed

*

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

PUTCHAR btfss

PIR1,TXIF

; Check,

is TX buffer full?

goto

PUTCHAR

; IF not

THEN try again

movf

DATA_OUT,w

;

ELSE get

datum

movwf

TXREG

;

and copy

to USART TX register

return

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

; * FUNCTION:

Receives one 8-bit byte in asynchronous format

*

; * RESOURCE:

PIC USART

*

; * ENTRY

:

None

*

; * EXIT

:

DATA_IN holds the received byte.

*

; * EXIT

:

ERR is 00 if no error. Framing ERRor only = -1

*

; * EXIT

:

ERR = -2 if Overflow ERRor and -3 if both types *

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

GETCHAR clrf

ERR

; Zero flag byte

btfss

PIR1,RCIF

; Check, is there a char ready?

goto

GETCHAR

; IF not THEN try again

; Error return

btfss

RCSTA,FERR

; Was there a Framing error?

goto

CHECK_OERR

; IF not THEN check for Overflow

movlw

-1

; ELSE record a Framing error

CHECK_OERR

btfsc

RCSTA,OERR

; Check for Overflow ERRor

goto

GET_EXIT

; IF none THEN complete

decf

ERR,f

; Otherwise register error

decf

ERR,f

bcf

RCSTA,CREN

; and reset the logic

bsf

RCSTA,CREN

GET_EXIT

movf

RCREG,w

; Get datum

movwf

DATA_IN

; and put away

return

Some systems may not wish the processor to hang up waiting for a character which is a long time in coming. In such cases an alternative input subroutine, perhaps called getch, could return an ERR of −1 if the return was empty handed. Another approach would be to generate an interrupt each time an incoming character is sensed rather than using a polling technique.

In the case of the CCS C compiler the #use rs232 directive tells the compiler which pins are to be used for RX and TX. The normal C I/O functions, such as printf(), use these pins as their link to the standard


346 The Quintessential PIC Microcontroller

channel. If these pins are specified as PIN_C6 and PIN_C7 then where the part has a built-in USART this will be used instead of a software technique.

There is more to setting up a communication link than establishing a suitable protocol. PIC devices have normal logic voltage and current levels which are not intended for connections greater than 30 cm (1 ). Although with care14 distances considerably in excess of this can be employed, in situations with relatively fast bit rates di erent signalling techniques have to be used.

In the era of electromechanical TTYs the de facto 20 mA loop standard was in common use. This uses zero and 20 mA current to signal logic 0 and logic 1 respectively. Use of current means that line attenuation is not a problem (as current out must equal current in) and this level of current was su cient to directly activate the receiver solenoid relay.

Current sources are realized by using high voltages in series with a large resistance. The latter gives long time constants, which, while adequate in the area of 110 baud rates, did not transfer well to the introduction of electronic terminals, UARTs and modems. RS-23215 was introduced in 1969 as the standard interface for connecting an item of Data Terminal Equipment (DTE), such as a terminal, to approved Data Circuit terminating Equipment (DCE), typically a modem. Thus, not only did it define signalling levels, as shown in Fig. 12.20(a), but also various control and handshake lines, some of which are shown in Figs. 12.20(d) and 12.21. For example the modem would signal back to the DTE that a telephone link had been opened with the remote DTE by activating the Clear To Send (CTS) handshake signal. Two data lines plus a ground line are needed for a full duplex transmission circuit.

The RS-232 standard has a range of 15 m (50 ) at a maximum rate of 20 kbaud, which it achieves by mapping logic 0 (often called a space) to typically +12 V and logic 1 (often called a mark) to typically −12 V. The receiver can distinguish levels down to ±5 V. The RS-423 standard (1978) in Fig. 12.20(b) is similar but can manage 1.2 km (6000 ) at up to 80 kbaud and 10 Mbaud at 12 m (40 ) with up to ten receivers.

Both RS-232 and RS-423 are unbalanced (or single-ended) standards, where the receiver measures the potential between signal line and ground reference. Even though the transmitter and receiver grounds are usually connected through the transmission line return, the impedance over a long distance may support a significant di erence in the two ground potentials, which will degrade noise immunity. Furthermore, any noise induced from outside will a ect signal lines di erently from the ground return due to their dissimilar electrical characteristics – hence the name unbalanced.

14Or sometimes ignorance!

15Defined in USA as the Electronics Industries Association EIA 232-E standard and as the V24 interface by the CCITT in Europe.

RS-422A: 1

driver

and up to 10

receivers

Logic levels

1 driver and 1 receiver

Enable

RS-485: 32 driver/receiver pairs

Logic levels

Logic levels

Logic levels

B

B

±12 V

±3 V

D

R

D

±5 V

±200 mV

R

A

A

.Fig

15m @ 20kb

15m @ 10Mb

12

Enable

150m @ 1Mb

.

Logic levels

1km @ 100kb

Logic levels

20

B

Some

D

R

A

RS485 only

signalling

(a) RS-232C

(b) RS-422/485

1

driver and up to 10

receivers

Logic levels

Logic levels

.configurations

D

±12V

±200 mV

R

UART Logic levels

Logic levels UART

1070 Hz

TX_DATA

Modem

1270 Hz

Modem

TX_DATA

One .12

2025 Hz

RX_DATA

2225 Hz

RX_DATA

10m

@ 100kb

DCD

DCD

CTS

CTS

100m @ 10kb

Logic levels

RTS

RTS

1km

@ 1kb

Bit

R

Time a at

(b) RS-423A

(d) FSK

347


348 The Quintessential PIC Microcontroller

The RS-422 (1978) and RS-485 (1983) standards are described as balanced. Here each signal link comprises two conductors, normally twisted around each other, known as twisted pair. The logic level is represented as the di erence of potential across the conductors, not the di erence from ground. Calling the conductors A and B, then logic 0 is represented as A<B and logic 1 by A>B. A di erence of more than ±200 mV at the receiver is su cient to establish the logic level and the transmitter will typically generate a ∆V = ±5 V. As the A and B conductors have the same characteristics and are tightly wound together they represent similar targets for induced noise. As the same noise voltage appears in both conductors and the receiver only distinguishes di erences, rejecting commonmode voltages up to ±7 V, then the noise immunity of these balanced links is clearly superior to unbalanced schemes. Commercial twistedpair cables, used in Local Area Networks (LANs), often carry three or four pairs of conductors, each link having a di erent twist pitch to reduce induction between links.

The main di erence between the RS-422 and RS-485 standards is the provision in the latter case for multiple transmitters as well as receivers to implement multi-drop LANs. As only one transmitter can be active at any one time, an RS-485 transmitter bu er must have an enable input, to select the master device. The single RS-422 transmitter has no need to be disabled.

RS-232 was originally designed for DTE-modem interconnection, although its use is now much more varied – see Fig. 12.21. Figure 12.20(d) shows a simple Frequency Shift Keying (FSK) full duplex system with the mark/space of one channel being represented by the tones 1070/1270 Hz and the other by 2025/2225 Hz; frequencies which fit well inside the normal telephone link bandwidth of 300 – 3400 Hz. Handshake lines DCD (Data Carrier Detect), CTS (Clear TO Send) and RTS (Ready To Send) are used to control the sequence of operations prior to and terminating the communication of data.

Many modem schemes currently use Phase Shift Keying (PSK) where typically at least eight di erent phases in 45◦ steps of a single tone are used to encode 3-binary bit code groups (tri-bits) in any one time slot. In this way the baud rate may be increased with the same signalling rate, albeit at the expense of noise immunity, as witnessed by the steady increase in PC-based home telephone internet data rates in recent years up to 56 kbaud.

As an example, Fig. 12.21 shows the connection between a PIC and the serial port of a PC – or any device with an asynchronous RS-232 port. The Maxim MAX233 dual RS-232 transceiver translates from +12 V to 0 V (logic 0) and −12 V to +5 V (logic 1). If handshake lines are not being used, as is usual in simple links, the PC can be ‘fooled’ into treating the interface as ready to accept data by linking as shown in the diagram. For

12. One Bit at a Time 349

Personal computer

[MAX233]

PIC

[MAX485]

Half-duplex

serial

port. Male

RS422/485

9-pin

D connector

C2+

communication

V+

C2+

DI

D

link

1

CD

V-

C2-

TX2

V-

C2-

9

RI

DE

B

2

RXD

TX1

DIR

8

CTS

RE

3

TXD

RX1

RO

A

7

RTS

RX2

R

4

DTR

6

DSR

GND

Carrier Detect

Transmit

Data

C1+

C1+

Ring Indicator

Request To Send

Logic/RS-232

Logic/RS-485

Receive

Data

Data Terminal

Ready

voltage

conversion

voltage

conversion

Clear To Send

Data Set Ready

Fig. 12.21 Communicating with a PC via an RS-232 link and the outside world.

instance, the serial port UART’s RTS is looped back to CTS. The MAX233 has two transmit and two receive bu ers in all and thus can be used to bu er some additional handshake lines if required.

In Fig. 12.21 the same PIC is shown driving a half duplex RS-485 link using a Maxim MAX485 voltage converter. Each bu er has a separate Enable of the opposite logic polarity. The PIC can activate the appropriate bu er depending on the communication direction. Alternatively the MAX485 can be used to implement a full duplex channel using two separate links.

The RS-485 link need not use the asynchronous protocol. Any suitable synchronous protocol can be bu ered to RS-485, but of course a separate clock channel will be needed.

Examples

Example 12.1

In Example 11.2 we designed a subroutine to compare a fixed number TRIP with the byte read in from Port B. In some cases it may be necessary to have the software adapt to changing circumstances, altering the trigger value by reading updates from outside. Rather than using up another eight port lines it is proposed that the update be fed in from an outside agency in series at pin RA4, with RA3 being used as the clock line. With the assumption that each data bit is set up when the Clock line is low write a subroutine to read in a new value into memory at TRIP.

Solution

One solution is shown in Program 12.13. The Clock line is monitored for high, during which time the Data is stable. By mirroring the state of the Data line into the Carry flag the datum is rotated bit by bit into memory.


350 The Quintessential PIC Microcontroller

After each shift the loop is not completed until the Clock line again goes low.

This is similar to subroutine SPI_READ in Program 12.2 except that the clock is generated from outside; that is the PIC is acting as a Slave. This causes problems in a real system where the PIC Slave must be able to tell the Master when it wants a new byte. This could be done by using another port line as a Clear To Send handshake which will interrupt the Master and initiate the conversion. Of course the Master could be another PIC and if so we have an economical way of connecting two PICs together. If PICs with integral serial ports are used then interrupts can be automatically generated and this is a frequently used way of implementing multi-processor networks.

Program 12.13 Updating Program 11.4’s trip value.

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

; FUNCTION:

Shifts in value for

TRIP

which is subsequently

*

; FUNCTION:

used as one operand

for

subroutine COMP

*

;

ENTRY

:

Data bit

changes at

RA4

when at RA3 is low

*

;

EXIT

:

COUNT is

00, datum is in

TRIP

*

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

SER_TRIP movlw

8

;

Bit loop count

movwf

COUNT

SER_TRIP_LOOP

btfss

PORTA,3

;

Wait for Clock to go high

goto

SER_TRIP_LOOP

bcf

STATUS,C

;

Carry = 0

btfsc

PORTA,4

;

Is Data line high?

bsf

STATUS,C

;

IF yes THEN Carry = 1

rlf

TRIP,f

;

Shift bit in

SER_TRIP_LOOP2

btfsc

PORTA,3

;

Wait for Clock to go low

goto

SER_TRIP_LOOP2

decfsz

COUNT,f

goto

SER_TRIP_LOOP

return

Example 12.2

Design and code the I2C_IN counterpart of the I2C_OUT subroutine of Program 12.7. You may assume that the same variables are available and that the output datum is in DATA_IN on entry.

Solution

The I2C_IN subroutine of Program 12.14 shifts the datum in file register DATA_IN through the Carry flag eight times with pin SDA mirroring this bit state. At the same time the Clock line SCL is toggled in according