A Comparison of 8-Bit Microcontrollers. COP800 Byte/Words Cycles X SWAP OR A,[B] MC68HC05 LDA ROLA ROLA ROLA ROLA ADD STA 1 1 REGLO REGLO

Size: px
Start display at page:

Download "A Comparison of 8-Bit Microcontrollers. COP800 Byte/Words Cycles X SWAP OR A,[B] MC68HC05 LDA ROLA ROLA ROLA ROLA ADD STA 1 1 REGLO REGLO"

Transcription

1 A Comparison of 8-Bit Microcontrollers AN50 Author: INTRODUCTION Mark Palmer Microchip Technology Inc. The PIC6C5X/XX microcontrollers from Microchip Technology Inc., provide significant execution speed and code-compaction improvement over any other 8-bit microcontroller in its price range. The superior performance of the PIC6C5X/XX microcontrollers can be attributed primarily to its RISC architecture. The PIC6C5X/XX devices employ a Harvard architecture (i.e., has separate program memory space and data memory space [8-bit wide data]). It also uses a two stage pipelining instruction fetch and execution. All instructions are executed in a single cycle (00 0 MHz clock) except for program branches which take two cycles, and there are only 33 instructions to remember. Separation of program and data space allows the instruction word to be optimized to any size (-bit wide for PIC6C5X devices and 4-bit wide for PIC6CXX devices). This makes it possible, for example, to load an 8-bit immediate value in one cycle. First, because there is no conflict between instruction fetch and data fetch (as opposed to von Neumann architecture) and secondly because the instruction word is wide enough to hold the 8-bit data. In the following sections we will compare the PIC6C5X/XX 0 MHz with: SGS-Thomson 8 MHz Motorola 4. MHz Intel 0 MHz Zilog MHz National 0 MHz Several coding examples will be considered. While the comparisons are not entirely scientific, they will demonstrate to the reader the relative superior performance of the PIC6C5X/XX devices. The examples chosen are used frequently in microcontroller applications. PACKING BINARY CODED DECIMAL (BCD) This example will take two bytes in RAM or registers, each containing a BCD digit in the lower nibble and create a packed BCD data byte, which is stored back in the register or RAM location holding the low BCD digit. PIC6C5X/XX SWAPF IORWF ST6 LD RLC RLC RLC RLC ADD LD REGHI,W REGLO A,REGHI A A A A A,REGLO REGLO,A Byte/Words Byte/Words 0 Cycles 0.4 µs REGHI and REGLO are registers 45.5 µs addressable by short direct addressing mode. Z86CXX SWAP OR Cycles Byte/Words Cycles REGHI 8 REGHI,REGLO REGHI and REGLO are addressable via 5.33 µs the working register addressing mode. COP800 Byte/Words Cycles X SWAP A,[B+] A OR A,[B] X A,[B] 4 5 B is pointing to the higher BCD digit initially. 5 µs After auto-increment, it points to the lower BCD digit. MC68HC05 LDA ROLA ROLA ROLA ROLA ADD STA Byte/Words REGHI REGLO REGLO µs Cycles Byte/Words Cycles MOV SWAP A,Rx A ORL A,Ry MOV Ry,A 4 4 Register Rx contains higher BCD digit, Ry holds lower BCD digit..4 µs 997 Microchip Technology Inc. DS0050D-page

2 AN50 LOOP CONTROL This example is one of simple loop control where a register containing a loop count is decremented, tested for zero, and if not zero, then branched back to the beginning of the loop. PIC6C5X/XX DECFSZ GOTO COUNT BEG_LOOP Byte/Words Cycles / /- 3/ COP800 DRSZ JP COUNT BEG_LOOP Byte/Words Cycles µs/0.4 µs COUNT is Register (RAM F0h-FFh). 6 µs ST6 DEC JRZ X BEG_LOOP Byte/Words Cycles 4 6 MC68HC05 DECX BEQ BEG_LOOP Byte/Words 3 Cycles µs.86 µs Z86CXX Byte/Words Cycles DJNZ COUNT, BEG_LOOP 0/.67 µs/.0 µs 805 Byte/Words Cycles DJNZ Rx, BEG_LOOP. µs BIT TEST & BRANCH This example tests a single bit in a register or a RAM location and makes a conditional branch. We assume that the MSb is tested and a branch is to be taken if the bit is set. PIC6C5X/XX BTFSC GOTO REG, 7 NEWADD Byte/Words Cycles / /- 3/ COP800 IFBIT JP 7, [B] NEWADD Byte/Words Cycles µs/0.4 µs B points to the memory location under test. 4 µs ST6 Byte/Words Cycles JRR 7, NEWADD µs MC68HC05 Byte/Words Cycles BRCLR 7, NEWADD µs Z86CXX Byte/Words Cycles BTJRT NEWADD, REG, 7 3 6/8 805 Byte/Words Cycles MOV JB A.7, NEWADD µs/3.0 µs Register Rx is assumed to be pointing to the memory location under test..8 µs DS0050D-page 997 Microchip Technology Inc.

3 AN50 SHIFTING OUT 8-BIT DATA & CLOCK We will now consider the task of serially shifting out an 8-bit data and clock. Data and clock outputs are generated under program control by toggling two output pins. Data is transmitted on the rising edge of the clock. No attempt is made to make the clock output symmetrical in order to make the code efficient. Data out is guaranteed on the falling edge of the clock. These conditions are satisfactory for most applications. PIC6C5X/XX Byte Cycles XMIT MOVLW 08H ; Bit Count /Words Xmit 00h MOVWF BITCNT ; XM BCF BCF RRF BTFSC BSF BSF DECFSZ GOTO BCF PORTB, 0 PORTB, XDATA STATUS, CARRY PORTB, 0 PORTB, BITCNT XM PORTC, ; 0 Data Out Pin ; 0 Clock Out Pin ; Rotate Right thru Carry ; Test Carry Bit ; Data Out Pin ; Clock Out Pin ; Decrement Count ; Skip if Zero ; ; 0 Clock Transmit time is the same for 00h or FFh: 74 Tcyc = 4.8 µs. Note that there was no need to load the data into the Accumulator (W) since the PIC6C5X/XX can operate directly on file registers. 74 Cycles Xmit FFh 74 Loop COP800 Byte Cycles Cycles XMIT LD A, XDATA ; Load Data in Acc. /Words Xmit 00h 3 Xmit FFh 3 LD BITCNT #08H ; Load Bit Count 3 3 LD B, #D0H ; B Points to PORTL 3 3 XM RBIT RBIT RRCA IFC SBIT SBIT DRSZ JP RBIT 0,[B],[B],[B] 0,[B] BITCNT XM 0,[B] ; 0 Clock ; 0 Data ; Rotate A Right thru Carry ; ; Data ; 0 Clock ; Decrement Bit Count ; and Go Back if 0 ; Accumulator (A) is first loaded with the data word. Transmit time is maximum for data = FFh; 05 Tcyc = 05 µs Loop ST6 Byte Cycles LDI A, #08 ; Bit Count /Words Xmit 00h 4 LD X, A ; Xmit Data 4 LD A, W ; 0 Clock 4 XM RES 0, DRB 4 RES, DRB 4 SLA A 4 JRNC XM XM SET, DRB SET 0, DRB DEC X 44 JRNZ RES XM 0, DRB ; 0 Data ; ; ; Data ; CLK ; ; ; ; ; 0 Data Cycles Xmit FFh Loop Register W contains the Data Word. Transmit time for FFh = 40 cycles = 390 µs. 997 Microchip Technology Inc. DS0050D-page 3

4 AN50 SHIFTING OUT 8-BIT DATA & CLOCK (Cont. d) MC68HC05 Byte Cycles XMIT LDA XDATA ; Load Xmit Data /Words Xmit 00h 3 LDX #$08 ; Load Bit Count Cycles Xmit FFh 3 XM XM BCLR BCLR ROLA BCC BSET BSET DECX BNE BCLR 0, PORTB, PORTB XM, PORTB 0, PORTB XM 0, PORTB ; 0 Clock ; 0 Data ; ; ; Data ; Clock ; ; ; 0 Data Loop Transmit time is maximum for transmitting FFh = 66 cycles = 6.7 µs. Z86CXX Byte Cycles XMIT LD COUNT, #8 ; Load Bit Count /Words 3 Xmit 00h 0 AND P, #%FC ; 0 Data, Clock 3 6 Cycles Xmit FFh 0 6 XM XM RRC JR OR OR DJNZ AND XDATA ; NC, XM P, #0 P, #0 COUNT, XM P, #%FC ; ; Data ; Clock ; ; 0 Clock, Data Loop Transmit time is maximum for transmitting FFh = 4 cycles = µs. 805 Byte Cycles MXIT MOV ; R0 Points to Data Word /Words Xmit 00h MOV R, #08H ; Load Bit Count Cycles Xmit FFh XM ANL RRC JNC SETB PORT, #0FCH A XM PORT, 0 ; 0 Data, Clock ; Rotate Right A thru Carry ; ; Data 3 Loop XM SETB DJNZ PORT, R, XM ; Clock ; Decrement Count Transmit time is maximum for transmitting FFh = 74 cycles = 44.4 µs. DS0050D-page Microchip Technology Inc.

5 AN50 SOFTWARE TIMER Microcontrollers quite often need to implement time delays. Debouncing key input, pulse width modulation, and phase angle control are just a few examples. Implementing a 0 ms time delay loop subroutine will be considered in this section. PIC6C5X/XX Byte/Words Cycles DELAY MOVLW 4H ; 0 ms Delay Loop MOVWF COUNT ; CLRF COUNT ; LOOP INCFSZ GOTO DECFSZ GOTO RET COUNT LOOP COUNT LOOP ; This inner Loop will be ; Executed 56 Times ; ; ; 8 / / Execution time for the routine = 5 + (55 x 3 + 5) x 65 = 005 Tcyc = 0.0 ms. The PIC6C5X/XX can implement delay times very precisely (when necessary) because of its fine instruction cycle resolution. COP800 Byte/Words Cycles DELAY LD COUNT, #0BH ; 0 ms Delay Loop 3 LD B, #0EH ; LOOP DRSZ B ; JP DRSZ JP RET LOOP COUNT LOOP ; ; ; ; Execution time for the routine = (6N + 6) N + 9 cycles. Here N = 0Bh and N = 0Eh, which gives us: 999 Tcyc = 9.99 ms. 8 5 ST6 LOOP Byte/Words Cycles LDI A, #FF 4 LD LDI LD DEC JRNZ DEC JRNZ X, A A, #04 Y, A X LOOP Y LOOP ; LOOP Count ; LOOP Count ; 0 CLK ; ; 0 CLK Execution time for the subroutine = (6N + 6) N + 6 cycles, where N = FFh, N = 04h gives us 0.0 ms. 997 Microchip Technology Inc. DS0050D-page 5

6 AN50 SOFTWARE TIMER (Cont. d) MC68HC05 Byte/Words Cycles DELAY LDX $D ; 0 ms Delay Loop LDX $5C ; LOOP DECA BNE DECX BNE RTS LOOP LOOP Execution time for the subroutine = (5 x N + 5)N + 0, with N = Dh, N = 5Ch, time delay = 0.08 ms. ; ; ; ; ; Z86CXX Byte/Words Cycles DELAY LD COUNT, #%6 ; 0 ms Delay Loop 6 LD COUNT, #%33 ; 6 LOOP DJNZ COUNT, LOOP ; DJNZ COUNT, LOOP ; RET ; Total execution time = (N +0)N, with N = 6h, N = 33h, time delay = cycles = ms. 9 0/ 0/ Byte/Words Cycles DELAY MOV COUNT, #H ; 0 ms Delay Loop LOOP MOV COUNT, #FBH ; LOOP DJNZ DJNZ RET COUNT, LOOP COUNT, LOOP ; ; ; 3 3 Execution time for the subroutine = (N + 3)N + 3 cycles. Where N = FBh, N = h, which gives us: 6668 cycles = ms. DS0050D-page Microchip Technology Inc.

7 AN50 SUMMARY Table summarizes code sizes for different microcontrollers. The overall relative code size number is an average of the individual relative code sizes. Given that the program word size of the PIC6C5X/XX is - or 4-bit (compared to an 8-bit program memory of all the other microcontrollers), a compaction of.5 is expected. Clearly, the PIC6C5X/XX meets this compaction (except for the COP800) and exceeds the compaction ratio in most comparisons. Table summarizes relative execution speed. The overall speed is an average of relative speed numbers. For example, the COP800 will, on average, exhibit 7% of the code execution speed of a PIC6C5X/XX devices. In other words, a PIC6C5X/XX will be (/0.7) 3.7 times faster than a COP800 on average. TABLE : COMPARISON OF CODE EFFICIENCY* Device Packing BCD Loop Control Bit Test & Branch 8-Bit Sync Transmission 0 ms Software Timer Overall COP ST MC68HC Z86CXX PIC6C5X/XX 8.00 * In each box, the top number is the number of program memory locations required to code the application. The bottom number is relative code size compared to the PIC6C5X/XX: # program memory locations for other microcontroller # program memory locations for the PIC6C5X/XX 997 Microchip Technology Inc. DS0050D-page 7

8 AN50 FIGURE : CODE SIZE COMPARISON Relative Code Size Most Compact Code PIC6C5X/XX COP800 ST8 MC68HC05 Z86CXX 805 DS0050D-page Microchip Technology Inc.

9 AN50 TABLE : COMPARISON OF EXECUTION SPEED Device Packing BCD Loop Control Bit Test & Branch 8-Bit Sync Transmission 0 ms Software Timer Overall 0 MHz 5 µs µs µs µs MHz 45.5 µs µs µs µs MHz 0.05 µs µs µs µs MHz.33 µs µs µs µs MHz 0 MHz.4 µs µs µs µs µs 0.6/0.4 µs 0.6/0.4 µs 4.8 µs * In each box, the top number is the time required to execute the example code, while the bottom number is a measure of relative performance compared to the PIC6C5X/XX. time required to execute code by the PIC6C5X/XX time required to execute code by other microcontroller FIGURE : EXECUTION SPEED COMPARISON Fastest Relative Execution Speed MHz 0 MHz 8 MHz 4. MHz MHz 0 MHz 997 Microchip Technology Inc. DS0050D-page 9

10 PIC6F87X 8/40-Pin 8-Bit CMOS FLASH Microcontrollers Devices Included in this Data Sheet: PIC6F873 PIC6F874 PIC6F876 PIC6F877 Microcontroller Core Features: High performance RISC CPU Only 35 single word instructions to learn All single cycle instructions except for program branches which are two cycle Operating speed: DC - 0 MHz clock input DC - 00 ns instruction cycle Up to 8K x 4 words of FLASH Program Memory, Up to 368 x 8 bytes of Data Memory (RAM) Up to 56 x 8 bytes of EEPROM Data Memory Pinout compatible to the PIC6C73B/74B/76/77 Interrupt capability (up to 4 sources) Eight level deep hardware stack Direct, indirect and relative addressing modes Power-on Reset (POR) Power-up Timer (PWRT) and Oscillator Start-up Timer (OST) Watchdog Timer (WDT) with its own on-chip RC oscillator for reliable operation Programmable code protection Power saving SLEEP mode Selectable oscillator options Low power, high speed CMOS FLASH/EEPROM technology Fully static design In-Circuit Serial Programming (ICSP) via two pins Single 5V In-Circuit Serial Programming capability In-Circuit Debugging via two pins Processor read/write access to program memory Wide operating voltage range:.0v to 5.5V High Sink/Source Current: 5 ma Commercial, Industrial and Extended temperature ranges Low-power consumption: - < 0.6 ma 3V, 4 MHz - 0 µa 3V, 3 khz - < µa typical standby current Pin Diagram PDIP MCLR/VPP RA0/AN0 RA/AN RA/AN/VREF- RA3/AN3/VREF+ RA4/T0CKI RA5/AN4/SS RE0/RD/AN5 RE/WR/AN6 RE/CS/AN7 VDD VSS OSC/CLKIN OSC/CLKOUT RC0/TOSO/TCKI RC/TOSI/CCP RC/CCP RC3/SCK/SCL RD0/PSP0 RD/PSP Peripheral Features: PIC6F877/ RB7/PGD RB6/PGC RB5 RB4 RB3/PGM RB RB RB0/INT VDD VSS RD7/PSP7 RD6/PSP6 RD5/PSP5 RD4/PSP4 RC7/RX/DT RC6/TX/CK RC5/SDO RC4/SDI/SDA RD3/PSP3 RD/PSP Timer0: 8-bit timer/counter with 8-bit prescaler Timer: 6-bit timer/counter with prescaler, can be incremented during SLEEP via external crystal/clock Timer: 8-bit timer/counter with 8-bit period register, prescaler and postscaler Two Capture, Compare, PWM modules - Capture is 6-bit, max. resolution is.5 ns - Compare is 6-bit, max. resolution is 00 ns - PWM max. resolution is 0-bit 0-bit multi-channel Analog-to-Digital converter Synchronous Serial Port (SSP) with SPI (Master mode) and I C (Master/Slave) Universal Synchronous Asynchronous Receiver Transmitter (USART/SCI) with 9-bit address detection Parallel Slave Port (PSP) 8-bits wide, with external RD, WR and CS controls (40/44-pin only) Brown-out detection circuitry for Brown-out Reset (BOR) 00 Microchip Technology Inc. DS309C-page

11 PIC6F87X FIGURE -: PIC6F874 AND PIC6F877 BLOCK DIAGRAM Device Program FLASH Data Memory Data EEPROM PIC6F874 4K 9 Bytes 8 Bytes PIC6F877 8K 368 Bytes 56 Bytes FLASH Program Memory 3 Program Counter 8 Level Stack (3-bit) Data Bus RAM File Registers 8 PORTA RA0/AN0 RA/AN RA/AN/VREF- RA3/AN3/VREF+ RA4/T0CKI RA5/AN4/SS Program Bus OSC/CLKIN OSC/CLKOUT 4 Instruction reg Instruction Decode & Control Timing Generation 8 Direct Addr 7 Power-up Timer Oscillator Start-up Timer Power-on Reset Watchdog Timer Brown-out Reset In-Circuit Debugger Low-Voltage Programming RAM Addr () Addr MUX ALU W reg 8 FSR reg Indirect Addr STATUS reg MUX Parallel Slave Port PORTB PORTC PORTD RB0/INT RB RB RB3/PGM RB4 RB5 RB6/PGC RB7/PGD RC0/TOSO/TCKI RC/TOSI/CCP RC/CCP RC3/SCK/SCL RC4/SDI/SDA RC5/SDO RC6/TX/CK RC7/RX/DT RD0/PSP0 RD/PSP RD/PSP RD3/PSP3 RD4/PSP4 RD5/PSP5 RD6/PSP6 RD7/PSP7 PORTE MCLR VDD, VSS RE0/AN5/RD RE/AN6/WR Timer0 Timer Timer 0-bit A/D RE/AN7/CS Data EEPROM CCP, Synchronous Serial Port USART Note : Higher order bits are from the STATUS register. DS309C-page 6 00 Microchip Technology Inc.

12 PIC6F87X TABLE -: PIC6F874 AND PIC6F877 PINOUT DESCRIPTION Pin Name DIP Pin# PLCC Pin# QFP Pin# I/O/P Type Buffer Type Description OSC/CLKIN I ST/CMOS (4) Oscillator crystal input/external clock source input. OSC/CLKOUT O Oscillator crystal output. Connects to crystal or resonator in crystal oscillator mode. In RC mode, OSC pin outputs CLKOUT which has /4 the frequency of OSC, and denotes the instruction cycle rate. MCLR/VPP 8 I/P ST Master Clear (Reset) input or programming voltage input. This pin is an active low RESET to the device. PORTA is a bi-directional I/O port. RA0/AN0 3 9 I/O TTL RA0 can also be analog input0. RA/AN I/O TTL RA can also be analog input. RA/AN/VREF- 4 5 I/O TTL RA can also be analog input or negative analog reference voltage. RA3/AN3/VREF+ 5 6 I/O TTL RA3 can also be analog input3 or positive analog reference voltage. RA4/T0CKI I/O ST RA4 can also be the clock input to the Timer0 timer/ counter. Output is open drain type. RA5/SS/AN I/O TTL RA5 can also be analog input4 or the slave select for the synchronous serial port. PORTB is a bi-directional I/O port. PORTB can be software programmed for internal weak pull-up on all inputs. RB0/INT I/O TTL/ST () RB0 can also be the external interrupt pin. RB I/O TTL RB I/O TTL RB3/PGM I/O TTL RB3 can also be the low voltage programming input. RB I/O TTL Interrupt-on-change pin. RB I/O TTL Interrupt-on-change pin. RB6/PGC I/O TTL/ST () Interrupt-on-change pin or In-Circuit Debugger pin. Serial programming clock. RB7/PGD I/O TTL/ST () Interrupt-on-change pin or In-Circuit Debugger pin. Serial programming data. Legend: I = input O = output I/O = input/output P = power = Not used TTL = TTL input ST = Schmitt Trigger input Note : This buffer is a Schmitt Trigger input when configured as an external interrupt. : This buffer is a Schmitt Trigger input when used in Serial Programming mode. 3: This buffer is a Schmitt Trigger input when configured as general purpose I/O and a TTL input when used in the Parallel Slave Port mode (for interfacing to a microprocessor bus). 4: This buffer is a Schmitt Trigger input when configured in RC oscillator mode and a CMOS input otherwise. DS309C-page 8 00 Microchip Technology Inc.

13 PIC6F87X TABLE -: PIC6F874 AND PIC6F877 PINOUT DESCRIPTION (CONTINUED) Pin Name DIP Pin# PLCC Pin# QFP Pin# I/O/P Type Buffer Type Description PORTC is a bi-directional I/O port. RC0/TOSO/TCKI I/O ST RC0 can also be the Timer oscillator output or a Timer clock input. RC/TOSI/CCP I/O ST RC can also be the Timer oscillator input or Capture input/compare output/pwm output. RC/CCP I/O ST RC can also be the Capture input/compare output/pwm output. RC3/SCK/SCL I/O ST RC3 can also be the synchronous serial clock input/ output for both SPI and I C modes. RC4/SDI/SDA I/O ST RC4 can also be the SPI Data In (SPI mode) or data I/O (I C mode). RC5/SDO I/O ST RC5 can also be the SPI Data Out (SPI mode). RC6/TX/CK I/O ST RC6 can also be the USART Asynchronous Transmit or Synchronous Clock. RC7/RX/DT 6 9 I/O ST RC7 can also be the USART Asynchronous Receive or Synchronous Data. PORTD is a bi-directional I/O port or parallel slave port when interfacing to a microprocessor bus. RD0/PSP I/O ST/TTL (3) RD/PSP 0 39 I/O ST/TTL (3) RD/PSP 3 40 I/O ST/TTL (3) RD3/PSP3 4 4 I/O ST/TTL (3) RD4/PSP I/O ST/TTL (3) RD5/PSP I/O ST/TTL (3) RD6/PSP I/O ST/TTL (3) RD7/PSP I/O ST/TTL (3) PORTE is a bi-directional I/O port. RE0/RD/AN I/O ST/TTL (3) RE0 can also be read control for the parallel slave port, or analog input5. RE/WR/AN I/O ST/TTL (3) RE can also be write control for the parallel slave port, or analog input6. RE/CS/AN7 0 7 I/O ST/TTL (3) RE can also be select control for the parallel slave port, or analog input7. VSS,3 3,34 6,9 P Ground reference for logic and I/O pins. VDD,3,35 7,8 P Positive supply for logic and I/O pins. NC,7,8, 40,3, 33,34 These pins are not internally connected. These pins should be left unconnected. Legend: I = input O = output I/O = input/output P = power = Not used TTL = TTL input ST = Schmitt Trigger input Note : This buffer is a Schmitt Trigger input when configured as an external interrupt. : This buffer is a Schmitt Trigger input when used in Serial Programming mode. 3: This buffer is a Schmitt Trigger input when configured as general purpose I/O and a TTL input when used in the Parallel Slave Port mode (for interfacing to a microprocessor bus). 4: This buffer is a Schmitt Trigger input when configured in RC oscillator mode and a CMOS input otherwise. 00 Microchip Technology Inc. DS309C-page 9

14 PIC6F87X FIGURE -3: PIC6F877/876 REGISTER FILE MAP Indirect addr. (*) TMR0 PCL STATUS FSR PORTA PORTB PORTC 00h 0h 0h 03h 04h 05h 06h 07h OPTION_REG PCL STATUS FSR TRISA TRISB TRISC PORTD () 08h TRISD () PORTE () 09h TRISE () PCLATH INTCON PIR PIR TMRL TMRH TCON TMR TCON SSPBUF SSPCON CCPRL CCPRH CCPCON RCSTA TXREG RCREG CCPRL CCPRH CCPCON ADRESH ADCON0 File Address 0Ah 0Bh 0Ch 0Dh 0Eh 0Fh 0h h h 3h 4h 5h 6h 7h 8h 9h Ah Bh Ch Dh Eh Fh 0h File Address Indirect addr. (*) 80h Indirect addr. (*) 8h TMR0 8h PCL 83h STATUS 84h FSR 85h 86h PORTB 87h 88h 89h PCLATH INTCON PIE PIE 8Ah 8Bh 8Ch 8Dh PCLATH INTCON EEDATA EEADR PCON 8Eh 8Fh EEDATH EEADRH 90h SSPCON 9h PR SSPADD SSPSTAT 9h 93h 94h 95h 96h 97h General Purpose TXSTA 98h Register SPBRG 99h 9Ah 9Bh 9Ch 9Dh ADRESL 9Eh ADCON 9Fh A0h File Address 00h 0h 0h 03h 04h 05h 06h 07h 08h 09h 0Ah 0Bh 0Ch 0Dh 0Eh 0Fh 0h h h 3h 4h 5h 6h 7h 8h 9h Ah Bh Ch Dh Eh Fh 0h Indirect addr. (*) OPTION_REG PCL STATUS FSR TRISB PCLATH INTCON EECON EECON Reserved () Reserved () General Purpose Register 6 Bytes 6 Bytes File Address 80h 8h 8h 83h 84h 85h 86h 87h 88h 89h 8Ah 8Bh 8Ch 8Dh 8Eh 8Fh 90h 9h 9h 93h 94h 95h 96h 97h 98h 99h 9Ah 9Bh 9Ch 9Dh 9Eh 9Fh A0h General Purpose Register 96 Bytes General Purpose Register accesses 70h-7Fh 7Fh Bank 0 Bank FFh General Purpose Register General Purpose Register 80 Bytes EFh 80 Bytes 80 Bytes F0h 6Fh accesses 70h accesses 70h-7Fh 70h - 7Fh 7Fh Bank Bank 3 EFh F0h FFh Unimplemented data memory locations, read as 0. * Not a physical register. Note : These registers are not implemented on the PIC6F876. : These registers are reserved, maintain these registers clear. 00 Microchip Technology Inc. DS309C-page 3

15 PIC6F87X.. SPECIAL FUNCTION REGISTERS The Special Function Registers are registers used by the CPU and peripheral modules for controlling the desired operation of the device. These registers are implemented as static RAM. A list of these registers is given in Table -. The Special Function Registers can be classified into two sets: core (CPU) and peripheral. Those registers associated with the core functions are described in detail in this section. Those related to the operation of the peripheral features are described in detail in the peripheral features section. TABLE -: SPECIAL FUNCTION REGISTER SUMMARY Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 Value on: POR, BOR Bank 0 00h (3) INDF Addressing this location uses contents of FSR to address data memory (not a physical register) h TMR0 Timer0 Module Register xxxx xxxx 47 0h (3) PCL Program Counter (PC) Least Significant Byte h (3) STATUS IRP RP RP0 TO PD Z DC C 000 xxx 8 04h (3) FSR Indirect Data Memory Address Pointer xxxx xxxx 7 05h PORTA PORTA Data Latch when written: PORTA pins when read --0x h PORTB PORTB Data Latch when written: PORTB pins when read xxxx xxxx 3 07h PORTC PORTC Data Latch when written: PORTC pins when read xxxx xxxx 33 08h (4) PORTD PORTD Data Latch when written: PORTD pins when read xxxx xxxx 35 09h (4) PORTE RE RE RE xxx 36 0Ah (,3) PCLATH Write Buffer for the upper 5 bits of the Program Counter Bh (3) INTCON GIE PEIE T0IE INTE RBIE T0IF INTF RBIF x 0 0Ch PIR PSPIF (3) ADIF RCIF TXIF SSPIF CCPIF TMRIF TMRIF Dh PIR (5) EEIF BCLIF CCPIF -r Eh TMRL Holding register for the Least Significant Byte of the 6-bit TMR Register xxxx xxxx 5 0Fh TMRH Holding register for the Most Significant Byte of the 6-bit TMR Register xxxx xxxx 5 0h TCON TCKPS TCKPS0 TOSCEN TSYNC TMRCS TMRON h TMR Timer Module Register h TCON TOUTPS3 TOUTPS TOUTPS TOUTPS0 TMRON TCKPS TCKPS h SSPBUF Synchronous Serial Port Receive Buffer/Transmit Register xxxx xxxx 70, 73 4h SSPCON WCOL SSPOV SSPEN CKP SSPM3 SSPM SSPM SSPM h CCPRL Capture/Compare/PWM Register (LSB) xxxx xxxx 57 6h CCPRH Capture/Compare/PWM Register (MSB) xxxx xxxx 57 7h CCPCON CCPX CCPY CCPM3 CCPM CCPM CCPM h RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D x 96 9h TXREG USART Transmit Data Register Ah RCREG USART Receive Data Register Bh CCPRL Capture/Compare/PWM Register (LSB) xxxx xxxx 57 Ch CCPRH Capture/Compare/PWM Register (MSB) xxxx xxxx 57 Dh CCPCON CCPX CCPY CCPM3 CCPM CCPM CCPM Eh ADRESH A/D Result Register High Byte xxxx xxxx 6 Fh ADCON0 ADCS ADCS0 CHS CHS CHS0 GO/DONE ADON Legend: x = unknown, u = unchanged, q = value depends on condition, - = unimplemented, read as '0', r = reserved. Shaded locations are unimplemented, read as 0. Note : The upper byte of the program counter is not directly accessible. PCLATH is a holding register for the PC<:8> whose contents are transferred to the upper byte of the program counter. : Bits PSPIE and PSPIF are reserved on PIC6F873/876 devices; always maintain these bits clear. 3: These registers can be addressed from any bank. 4: PORTD, PORTE, TRISD, and TRISE are not physically implemented on PIC6F873/876 devices; read as 0. 5: PIR<6> and PIE<6> are reserved on these devices; always maintain these bits clear. Details on page: 00 Microchip Technology Inc. DS309C-page 5

16 PIC6F87X TABLE -: SPECIAL FUNCTION REGISTER SUMMARY (CONTINUED) Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 Value on: POR, BOR Bank 80h (3) INDF Addressing this location uses contents of FSR to address data memory (not a physical register) h OPTION_REG RBPU INTEDG T0CS T0SE PSA PS PS PS0 9 8h (3) PCL Program Counter (PC) Least Significant Byte h (3) STATUS IRP RP RP0 TO PD Z DC C 000 xxx 8 84h (3) FSR Indirect Data Memory Address Pointer xxxx xxxx 7 85h TRISA PORTA Data Direction Register h TRISB PORTB Data Direction Register 3 87h TRISC PORTC Data Direction Register 33 88h (4) TRISD PORTD Data Direction Register 35 89h (4) TRISE IBF OBF IBOV PSPMODE PORTE Data Direction Bits Ah (,3) PCLATH Write Buffer for the upper 5 bits of the Program Counter Bh (3) INTCON GIE PEIE T0IE INTE RBIE T0IF INTF RBIF x 0 8Ch PIE PSPIE () ADIE RCIE TXIE SSPIE CCPIE TMRIE TMRIE Dh PIE (5) EEIE BCLIE CCPIE -r Eh PCON POR BOR qq 5 8Fh Unimplemented 90h Unimplemented 9h SSPCON GCEN ACKSTAT ACKDT ACKEN RCEN PEN RSEN SEN h PR Timer Period Register 55 93h SSPADD Synchronous Serial Port (I C mode) Address Register , 74 94h SSPSTAT SMP CKE D/A P S R/W UA BF h Unimplemented 96h Unimplemented 97h Unimplemented 98h TXSTA CSRC TX9 TXEN SYNC BRGH TRMT TX9D h SPBRG Baud Rate Generator Register Ah Unimplemented 9Bh Unimplemented 9Ch Unimplemented 9Dh Unimplemented 9Eh ADRESL A/D Result Register Low Byte xxxx xxxx 6 9Fh ADCON ADFM PCFG3 PCFG PCFG PCFG Legend: x = unknown, u = unchanged, q = value depends on condition, - = unimplemented, read as '0', r = reserved. Shaded locations are unimplemented, read as 0. Note : The upper byte of the program counter is not directly accessible. PCLATH is a holding register for the PC<:8> whose contents are transferred to the upper byte of the program counter. : Bits PSPIE and PSPIF are reserved on PIC6F873/876 devices; always maintain these bits clear. 3: These registers can be addressed from any bank. 4: PORTD, PORTE, TRISD, and TRISE are not physically implemented on PIC6F873/876 devices; read as 0. 5: PIR<6> and PIE<6> are reserved on these devices; always maintain these bits clear. Details on page: DS309C-page 6 00 Microchip Technology Inc.

17 PIC6F87X TABLE -: SPECIAL FUNCTION REGISTER SUMMARY (CONTINUED) Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 Value on: POR, BOR Bank 00h (3) INDF Addressing this location uses contents of FSR to address data memory (not a physical register) h TMR0 Timer0 Module Register xxxx xxxx 47 0h (3) PCL Program Counter s (PC) Least Significant Byte h (3) STATUS IRP RP RP0 TO PD Z DC C 000 xxx 8 04h (3) FSR Indirect Data Memory Address Pointer xxxx xxxx 7 05h Unimplemented 06h PORTB PORTB Data Latch when written: PORTB pins when read xxxx xxxx 3 07h Unimplemented 08h Unimplemented 09h Unimplemented 0Ah (,3) PCLATH Write Buffer for the upper 5 bits of the Program Counter Bh (3) INTCON GIE PEIE T0IE INTE RBIE T0IF INTF RBIF x 0 0Ch EEDATA EEPROM Data Register Low Byte xxxx xxxx 4 0Dh EEADR EEPROM Address Register Low Byte xxxx xxxx 4 0Eh EEDATH EEPROM Data Register High Byte xxxx xxxx 4 0Fh EEADRH EEPROM Address Register High Byte xxxx xxxx 4 Bank 3 80h (3) INDF Addressing this location uses contents of FSR to address data memory (not a physical register) h OPTION_REG RBPU INTEDG T0CS T0SE PSA PS PS PS0 9 8h (3) PCL Program Counter (PC) Least Significant Byte h (3) STATUS IRP RP RP0 TO PD Z DC C 000 xxx 8 84h (3) FSR Indirect Data Memory Address Pointer xxxx xxxx 7 85h Unimplemented 86h TRISB PORTB Data Direction Register 3 87h Unimplemented 88h Unimplemented 89h Unimplemented 8Ah (,3) PCLATH Write Buffer for the upper 5 bits of the Program Counter Bh (3) INTCON GIE PEIE T0IE INTE RBIE T0IF INTF RBIF x 0 8Ch EECON EEPGD WRERR WREN WR RD x--- x000 4, 4 8Dh EECON EEPROM Control Register (not a physical register) Eh Reserved maintain clear Fh Reserved maintain clear Legend: x = unknown, u = unchanged, q = value depends on condition, - = unimplemented, read as '0', r = reserved. Shaded locations are unimplemented, read as 0. Note : The upper byte of the program counter is not directly accessible. PCLATH is a holding register for the PC<:8> whose contents are transferred to the upper byte of the program counter. : Bits PSPIE and PSPIF are reserved on PIC6F873/876 devices; always maintain these bits clear. 3: These registers can be addressed from any bank. 4: PORTD, PORTE, TRISD, and TRISE are not physically implemented on PIC6F873/876 devices; read as 0. 5: PIR<6> and PIE<6> are reserved on these devices; always maintain these bits clear. Details on page: 00 Microchip Technology Inc. DS309C-page 7

18 PIC6F87X 3.0 I/O PORTS Some pins for these I/O ports are multiplexed with an alternate function for the peripheral features on the device. In general, when a peripheral is enabled, that pin may not be used as a general purpose I/O pin. Additional information on I/O ports may be found in the PICmicro Mid-Range Reference Manual, (DS3303). 3. PORTA and the TRISA Register PORTA is a 6-bit wide, bi-directional port. The corresponding data direction register is TRISA. Setting a TRISA bit (= ) will make the corresponding PORTA pin an input (i.e., put the corresponding output driver in a Hi-Impedance mode). Clearing a TRISA bit (= 0) will make the corresponding PORTA pin an output (i.e., put the contents of the output latch on the selected pin). Reading the PORTA register reads the status of the pins, whereas writing to it will write to the port latch. All write operations are read-modify-write operations. Therefore, a write to a port implies that the port pins are read, the value is modified and then written to the port data latch. Pin RA4 is multiplexed with the Timer0 module clock input to become the RA4/T0CKI pin. The RA4/T0CKI pin is a Schmitt Trigger input and an open drain output. All other PORTA pins have TTL input levels and full CMOS output drivers. Other PORTA pins are multiplexed with analog inputs and analog VREF input. The operation of each pin is selected by clearing/setting the control bits in the ADCON register (A/D Control Register). Note: The TRISA register controls the direction of the RA pins, even when they are being used as analog inputs. The user must ensure the bits in the TRISA register are maintained set when using them as analog inputs. EXAMPLE 3-: On a Power-on Reset, these pins are configured as analog inputs and read as '0'. INITIALIZING PORTA BCF STATUS, RP0 ; BCF STATUS, RP ; Bank0 CLRF PORTA ; Initialize PORTA by ; clearing output ; data latches BSF STATUS, RP0 ; Select Bank MOVLW 0x06 ; Configure all pins MOVWF ADCON ; as digital inputs MOVLW 0xCF ; Value used to ; initialize data ; direction MOVWF TRISA ; Set RA<3:0> as inputs ; RA<5:4> as outputs ; TRISA<7:6>are always ; read as 0. FIGURE 3-: Data Bus WR Port WR TRIS RD TRIS RD Port D D CK CK To A/D Converter FIGURE 3-: Data Latch TRIS Latch Q Q Q Q BLOCK DIAGRAM OF RA3:RA0 AND RA5 PINS Q BLOCK DIAGRAM OF RA4/T0CKI PIN D EN VDD P N VSS Analog Input Mode I/O pin () TTL Input Buffer Note : I/O pins have protection diodes to VDD and VSS. Data Bus WR Port WR TRIS RD TRIS RD Port Data Latch D CK TRIS Latch D CK TMR0 Clock Input Q Q Q Q Q N VSS Schmitt Trigger Input Buffer D EN EN Note : I/O pin has protection diodes to VSS only. I/O pin () 00 Microchip Technology Inc. DS309C-page 9

19 PIC6F87X TABLE 3-: PORTA FUNCTIONS Name Bit# Buffer Function RA0/AN0 bit0 TTL Input/output or analog input. RA/AN bit TTL Input/output or analog input. RA/AN bit TTL Input/output or analog input. RA3/AN3/VREF bit3 TTL Input/output or analog input or VREF. RA4/T0CKI bit4 ST Input/output or external clock input for Timer0. Output is open drain type. RA5/SS/AN4 bit5 TTL Input/output or slave select input for synchronous serial port or analog input. Legend: TTL = TTL input, ST = Schmitt Trigger input TABLE 3-: SUMMARY OF REGISTERS ASSOCIATED WITH PORTA Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 Value on: POR, BOR Value on all other RESETS 05h PORTA RA5 RA4 RA3 RA RA RA0 --0x u h TRISA PORTA Data Direction Register Fh ADCON ADFM PCFG3 PCFG PCFG PCFG Legend: x = unknown, u = unchanged, - = unimplemented locations read as '0'. Shaded cells are not used by PORTA. Note: When using the SSP module in SPI Slave mode and SS enabled, the A/D converter must be set to one of the following modes, where PCFG3:PCFG0 = 000,00, 0x, 0, 0,. DS309C-page Microchip Technology Inc.

20 PIC6F87X 3. PORTB and the TRISB Register PORTB is an 8-bit wide, bi-directional port. The corresponding data direction register is TRISB. Setting a TRISB bit (= ) will make the corresponding PORTB pin an input (i.e., put the corresponding output driver in a Hi-Impedance mode). Clearing a TRISB bit (= 0) will make the corresponding PORTB pin an output (i.e., put the contents of the output latch on the selected pin). Three pins of PORTB are multiplexed with the Low Voltage Programming function: RB3/PGM, RB6/PGC and RB7/PGD. The alternate functions of these pins are described in the Special Features Section. Each of the PORTB pins has a weak internal pull-up. A single control bit can turn on all the pull-ups. This is performed by clearing bit RBPU (OPTION_REG<7>). The weak pull-up is automatically turned off when the port pin is configured as an output. The pull-ups are disabled on a Power-on Reset. FIGURE 3-3: RBPU () Data Bus WR Port WR TRIS RD TRIS RD Port RB0/INT RB3/PGM BLOCK DIAGRAM OF RB3:RB0 PINS Data Latch D Q CK TRIS Latch D Q CK VDD Weak P Pull-up Four of the PORTB pins, RB7:RB4, have an interrupton-change feature. Only pins configured as inputs can cause this interrupt to occur (i.e., any RB7:RB4 pin configured as an output is excluded from the interrupton-change comparison). The input pins (of RB7:RB4) are compared with the old value latched on the last read of PORTB. The mismatch outputs of RB7:RB4 are OR ed together to generate the RB Port Change Interrupt with flag bit RBIF (INTCON<0>). Q Schmitt Trigger Buffer TTL Input Buffer D EN I/O pin () RD Port Note : I/O pins have diode protection to VDD and VSS. : To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit (OPTION_REG<7>). This interrupt can wake the device from SLEEP. The user, in the Interrupt Service Routine, can clear the interrupt in the following manner: a) Any read or write of PORTB. This will end the mismatch condition. b) Clear flag bit RBIF. A mismatch condition will continue to set flag bit RBIF. Reading PORTB will end the mismatch condition and allow flag bit RBIF to be cleared. The interrupt-on-change feature is recommended for wake-up on key depression operation and operations where PORTB is only used for the interrupt-on-change feature. Polling of PORTB is not recommended while using the interrupt-on-change feature. This interrupt-on-mismatch feature, together with software configureable pull-ups on these four pins, allow easy interface to a keypad and make it possible for wake-up on key depression. Refer to the Embedded Control Handbook, Implementing Wake-up on Key Strokes (AN55). RB0/INT is an external interrupt input pin and is configured using the INTEDG bit (OPTION_REG<6>). RB0/INT is discussed in detail in Section.0.. FIGURE 3-4: RBPU () Data Bus WR Port WR TRIS RD TRIS RD Port Set RBIF From other RB7:RB4 pins Data Latch D Q CK TRIS Latch D Q CK RB7:RB6 In Serial Programming Mode BLOCK DIAGRAM OF RB7:RB4 PINS Latch Q D Q EN D EN TTL Input Buffer VDD P Weak Pull-up I/O pin () ST Buffer Q RD Port Note : I/O pins have diode protection to VDD and VSS. : To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit (OPTION_REG<7>). Q3 00 Microchip Technology Inc. DS309C-page 3

21 PIC6F87X TABLE 3-3: PORTB FUNCTIONS Name Bit# Buffer Function RB0/INT bit0 TTL/ST () Input/output pin or external interrupt input. Internal software programmable weak pull-up. RB bit TTL Input/output pin. Internal software programmable weak pull-up. RB bit TTL Input/output pin. Internal software programmable weak pull-up. RB3/PGM (3) bit3 TTL Input/output pin or programming pin in LVP mode. Internal software programmable weak pull-up. RB4 bit4 TTL Input/output pin (with interrupt-on-change). Internal software programmable weak pull-up. RB5 bit5 TTL Input/output pin (with interrupt-on-change). Internal software programmable weak pull-up. RB6/PGC bit6 TTL/ST () Input/output pin (with interrupt-on-change) or In-Circuit Debugger pin. Internal software programmable weak pull-up. Serial programming clock. RB7/PGD bit7 TTL/ST () Input/output pin (with interrupt-on-change) or In-Circuit Debugger pin. Internal software programmable weak pull-up. Serial programming data. Legend: TTL = TTL input, ST = Schmitt Trigger input Note : This buffer is a Schmitt Trigger input when configured as the external interrupt. : This buffer is a Schmitt Trigger input when used in Serial Programming mode. 3: Low Voltage ICSP Programming (LVP) is enabled by default, which disables the RB3 I/O function. LVP must be disabled to enable RB3 as an I/O pin and allow maximum compatibility to the other 8-pin and 40-pin mid-range devices. TABLE 3-4: SUMMARY OF REGISTERS ASSOCIATED WITH PORTB Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 Value on: POR, BOR Value on all other RESETS 06h, 06h PORTB RB7 RB6 RB5 RB4 RB3 RB RB RB0 xxxx xxxx uuuu uuuu 86h, 86h TRISB PORTB Data Direction Register 8h, 8h OPTION_REG RBPU INTEDG T0CS T0SE PSA PS PS PS0 Legend: x = unknown, u = unchanged. Shaded cells are not used by PORTB. DS309C-page 3 00 Microchip Technology Inc.

22 PIC6F87X 3.3 PORTC and the TRISC Register PORTC is an 8-bit wide, bi-directional port. The corresponding data direction register is TRISC. Setting a TRISC bit (= ) will make the corresponding PORTC pin an input (i.e., put the corresponding output driver in a Hi-Impedance mode). Clearing a TRISC bit (= 0) will make the corresponding PORTC pin an output (i.e., put the contents of the output latch on the selected pin). PORTC is multiplexed with several peripheral functions (Table 3-5). PORTC pins have Schmitt Trigger input buffers. When the I C module is enabled, the PORTC<4:3> pins can be configured with normal I C levels, or with SMBus levels by using the CKE bit (SSPSTAT<6>). When enabling peripheral functions, care should be taken in defining TRIS bits for each PORTC pin. Some peripherals override the TRIS bit to make a pin an output, while other peripherals override the TRIS bit to make a pin an input. Since the TRIS bit override is in effect while the peripheral is enabled, read-modifywrite instructions (BSF, BCF, XORWF) with TRISC as destination, should be avoided. The user should refer to the corresponding peripheral section for the correct TRIS bit settings. FIGURE 3-5: Port/Peripheral Select () PORTC BLOCK DIAGRAM (PERIPHERAL OUTPUT OVERRIDE) RC<:0>, RC<7:5> FIGURE 3-6: Port/Peripheral Select () Peripheral Data Out Data Bus WR Port WR TRIS RD TRIS Peripheral OE (3) RD Port SSPl Input D Data Latch D CK CK Q Q Q Q TRIS Latch PORTC BLOCK DIAGRAM (PERIPHERAL OUTPUT OVERRIDE) RC<4:3> 0 Q D EN Schmitt Trigger VDD P N Vss I/O pin () Note : I/O pins have diode protection to VDD and VSS. : Port/Peripheral select signal selects between port data and peripheral output. 3: Peripheral OE (output enable) is only activated if peripheral select is active. 0 CKE SSPSTAT<6> Schmitt Trigger with SMBus levels Peripheral Data Out Data Bus D WR Port CK Q Q 0 VDD P I/O pin () Data Latch WR TRIS D Q CK Q TRIS Latch N RD TRIS Peripheral OE (3) Q D Schmitt Trigger VSS RD Port EN Peripheral Input Note : I/O pins have diode protection to VDD and VSS. : Port/Peripheral select signal selects between port data and peripheral output. 3: Peripheral OE (output enable) is only activated if peripheral select is active. 00 Microchip Technology Inc. DS309C-page 33

23 PIC6F87X TABLE 3-5: PORTC FUNCTIONS Name Bit# Buffer Type Function RC0/TOSO/TCKI bit0 ST Input/output port pin or Timer oscillator output/timer clock input. RC/TOSI/CCP bit ST Input/output port pin or Timer oscillator input or Capture input/ Compare output/pwm output. RC/CCP bit ST Input/output port pin or Capture input/compare output/ PWM output. RC3/SCK/SCL bit3 ST RC3 can also be the synchronous serial clock for both SPI and I C modes. RC4/SDI/SDA bit4 ST RC4 can also be the SPI Data In (SPI mode) or data I/O (I C mode). RC5/SDO bit5 ST Input/output port pin or Synchronous Serial Port data output. RC6/TX/CK bit6 ST Input/output port pin or USART Asynchronous Transmit or Synchronous Clock. RC7/RX/DT bit7 ST Input/output port pin or USART Asynchronous Receive or Synchronous Data. Legend: ST = Schmitt Trigger input TABLE 3-6: SUMMARY OF REGISTERS ASSOCIATED WITH PORTC Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 Value on: POR, BOR Value on all other RESETS 07h PORTC RC7 RC6 RC5 RC4 RC3 RC RC RC0 xxxx xxxx uuuu uuuu 87h TRISC PORTC Data Direction Register Legend: x = unknown, u = unchanged DS309C-page Microchip Technology Inc.

24 PIC6F87X 3.4 PORTD and TRISD Registers PORTD and TRISD are not implemented on the PIC6F873 or PIC6F876. PORTD is an 8-bit port with Schmitt Trigger input buffers. Each pin is individually configureable as an input or output. PORTD can be configured as an 8-bit wide microprocessor port (parallel slave port) by setting control bit PSPMODE (TRISE<4>). In this mode, the input buffers are TTL. FIGURE 3-7: Data Bus WR Port WR TRIS Data Latch D Q CK TRIS Latch D CK Q PORTD BLOCK DIAGRAM (IN I/O PORT MODE) Schmitt Trigger Input Buffer I/O pin () RD TRIS Q D RD Port EN EN Note : I/O pins have protection diodes to VDD and VSS. TABLE 3-7: PORTD FUNCTIONS Name Bit# Buffer Type Function RD0/PSP0 bit0 ST/TTL () Input/output port pin or parallel slave port bit0. RD/PSP bit ST/TTL () Input/output port pin or parallel slave port bit. RD/PSP bit ST/TTL () Input/output port pin or parallel slave port bit. RD3/PSP3 bit3 ST/TTL () Input/output port pin or parallel slave port bit3. RD4/PSP4 bit4 ST/TTL () Input/output port pin or parallel slave port bit4. RD5/PSP5 bit5 ST/TTL () Input/output port pin or parallel slave port bit5. RD6/PSP6 bit6 ST/TTL () Input/output port pin or parallel slave port bit6. RD7/PSP7 bit7 ST/TTL () Input/output port pin or parallel slave port bit7. Legend: ST = Schmitt Trigger input, TTL = TTL input Note : Input buffers are Schmitt Triggers when in I/O mode and TTL buffers when in Parallel Slave Port mode. TABLE 3-8: SUMMARY OF REGISTERS ASSOCIATED WITH PORTD Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 Value on: POR, BOR Value on all other RESETS 08h PORTD RD7 RD6 RD5 RD4 RD3 RD RD RD0 xxxx xxxx uuuu uuuu 88h TRISD PORTD Data Direction Register 89h TRISE IBF OBF IBOV PSPMODE PORTE Data Direction Bits Legend: x = unknown, u = unchanged, - = unimplemented, read as '0'. Shaded cells are not used by PORTD. 00 Microchip Technology Inc. DS309C-page 35

25 PIC6F87X 3.5 PORTE and TRISE Register PORTE and TRISE are not implemented on the PIC6F873 or PIC6F876. PORTE has three pins (RE0/RD/AN5, RE/WR/AN6, and RE/CS/AN7) which are individually configureable as inputs or outputs. These pins have Schmitt Trigger input buffers. The PORTE pins become the I/O control inputs for the microprocessor port when bit PSPMODE (TRISE<4>) is set. In this mode, the user must make certain that the TRISE<:0> bits are set, and that the pins are configured as digital inputs. Also ensure that ADCON is configured for digital I/O. In this mode, the input buffers are TTL. Register 3- shows the TRISE register, which also controls the parallel slave port operation. PORTE pins are multiplexed with analog inputs. When selected for analog input, these pins will read as 0 s. TRISE controls the direction of the RE pins, even when they are being used as analog inputs. The user must make sure to keep the pins configured as inputs when using them as analog inputs. Note: On a Power-on Reset, these pins are configured as analog inputs, and read as 0. FIGURE 3-8: Data Bus WR Port WR TRIS RD TRIS RD Port Data Latch D Q CK TRIS Latch D CK Q PORTE BLOCK DIAGRAM (IN I/O PORT MODE) Q Schmitt Trigger Input Buffer D EN EN I/O pin () Note : I/O pins have protection diodes to VDD and VSS. TABLE 3-9: PORTE FUNCTIONS Name Bit# Buffer Type Function RE0/RD/AN5 bit0 ST/TTL () RE/WR/AN6 bit ST/TTL () I/O port pin or read control input in Parallel Slave Port mode or analog input: RD = Idle 0 = Read operation. Contents of PORTD register are output to PORTD I/O pins (if chip selected) I/O port pin or write control input in Parallel Slave Port mode or analog input: WR =Idle 0 = Write operation. Value of PORTD I/O pins is latched into PORTD register (if chip selected) RE/CS/AN7 bit ST/TTL () CS = Device is not selected I/O port pin or chip select control input in Parallel Slave Port mode or analog input: 0 = Device is selected Legend: ST = Schmitt Trigger input, TTL = TTL input Note : Input buffers are Schmitt Triggers when in I/O mode and TTL buffers when in Parallel Slave Port mode. TABLE 3-0: SUMMARY OF REGISTERS ASSOCIATED WITH PORTE Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 Value on: POR, BOR Value on all other RESETS 09h PORTE RE RE RE xxx uuu 89h TRISE IBF OBF IBOV PSPMODE PORTE Data Direction Bits Fh ADCON ADFM PCFG3 PCFG PCFG PCFG Legend: x = unknown, u = unchanged, - = unimplemented, read as 0. Shaded cells are not used by PORTE. DS309C-page Microchip Technology Inc.

26 PIC6F87X REGISTER 3-: TRISE REGISTER (ADDRESS 89h) R-0 R-0 R/W-0 R/W-0 U-0 R/W- R/W- R/W- IBF OBF IBOV PSPMODE Bit Bit Bit0 bit 7 bit 0 Parallel Slave Port Status/Control Bits: bit 7 IBF: Input Buffer Full Status bit = A word has been received and is waiting to be read by the CPU 0 = No word has been received bit 6 OBF: Output Buffer Full Status bit = The output buffer still holds a previously written word 0 = The output buffer has been read bit 5 IBOV: Input Buffer Overflow Detect bit (in Microprocessor mode) = A write occurred when a previously input word has not been read (must be cleared in software) 0 = No overflow occurred bit 4 bit 3 bit bit bit 0 PSPMODE: Parallel Slave Port Mode Select bit = PORTD functions in Parallel Slave Port mode 0 = PORTD functions in general purpose I/O mode Unimplemented: Read as '0' PORTE Data Direction Bits: Bit: Direction Control bit for pin RE/CS/AN7 = Input 0 = Output Bit: Direction Control bit for pin RE/WR/AN6 = Input 0 = Output Bit0: Direction Control bit for pin RE0/RD/AN5 = Input 0 = Output Legend: R = Readable bit W = Writable bit U = Unimplemented bit, read as 0 - n = Value at POR = Bit is set 0 = Bit is cleared x = Bit is unknown 00 Microchip Technology Inc. DS309C-page 37

27 PIC6F87X 3.6 Parallel Slave Port The Parallel Slave Port (PSP) is not implemented on the PIC6F873 or PIC6F876. PORTD operates as an 8-bit wide Parallel Slave Port or microprocessor port, when control bit PSPMODE (TRISE<4>) is set. In Slave mode, it is asynchronously readable and writable by the external world through RD control input pin RE0/RD and WR control input pin RE/WR. The PSP can directly interface to an 8-bit microprocessor data bus. The external microprocessor can read or write the PORTD latch as an 8-bit latch. Setting bit PSPMODE enables port pin RE0/RD to be the RD input, RE/WR to be the WR input and RE/CS to be the CS (chip select) input. For this functionality, the corresponding data direction bits of the TRISE register (TRISE<:0>) must be configured as inputs (set). The A/D port configuration bits PCFG3:PCFG0 (ADCON<3:0>) must be set to configure pins RE:RE0 as digital I/O. There are actually two 8-bit latches: one for data output, and one for data input. The user writes 8-bit data to the PORTD data latch and reads data from the port pin latch (note that they have the same address). In this mode, the TRISD register is ignored, since the external device is controlling the direction of data flow. A write to the PSP occurs when both the CS and WR lines are first detected low. When either the CS or WR lines become high (level triggered), the Input Buffer Full (IBF) status flag bit (TRISE<7>) is set on the Q4 clock cycle, following the next Q cycle, to signal the write is complete (Figure 3-0). The interrupt flag bit PSPIF (PIR<7>) is also set on the same Q4 clock cycle. IBF can only be cleared by reading the PORTD input latch. The Input Buffer Overflow (IBOV) status flag bit (TRISE<5>) is set if a second write to the PSP is attempted when the previous byte has not been read out of the buffer. A read from the PSP occurs when both the CS and RD lines are first detected low. The Output Buffer Full (OBF) status flag bit (TRISE<6>) is cleared immediately (Figure 3-), indicating that the PORTD latch is waiting to be read by the external bus. When either the CS or RD pin becomes high (level triggered), the interrupt flag bit PSPIF is set on the Q4 clock cycle, following the next Q cycle, indicating that the read is complete. OBF remains low until data is written to PORTD by the user firmware. When not in PSP mode, the IBF and OBF bits are held clear. However, if flag bit IBOV was previously set, it must be cleared in firmware. An interrupt is generated and latched into flag bit PSPIF when a read or write operation is completed. PSPIF must be cleared by the user in firmware and the interrupt can be disabled by clearing the interrupt enable bit PSPIE (PIE<7>). FIGURE 3-9: Data Bus WR Port RD Port D Q One bit of PORTD Set Interrupt Flag PSPIF(PIR<7>) CK Q EN EN PORTD AND PORTE BLOCK DIAGRAM (PARALLEL SLAVE PORT) D Read TTL Chip Select TTL Write TTL TTL Note : I/O pins have protection diodes to VDD and VSS. RDx pin RD CS WR DS309C-page Microchip Technology Inc.

28 PIC6F87X FIGURE 3-0: PARALLEL SLAVE PORT WRITE WAVEFORMS Q Q Q3 Q4 Q Q Q3 Q4 Q Q Q3 Q4 CS WR RD PORTD<7:0> IBF OBF PSPIF FIGURE 3-: PARALLEL SLAVE PORT READ WAVEFORMS Q Q Q3 Q4 Q Q Q3 Q4 Q Q Q3 Q4 CS WR RD PORTD<7:0> IBF OBF PSPIF TABLE 3-: REGISTERS ASSOCIATED WITH PARALLEL SLAVE PORT Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 Value on: POR, BOR Value on all other RESETS 08h PORTD Port Data Latch when written: Port pins when read xxxx xxxx uuuu uuuu 09h PORTE RE RE RE xxx uuu 89h TRISE IBF OBF IBOV PSPMODE PORTE Data Direction Bits Ch PIR PSPIF () ADIF RCIF TXIF SSPIF CCPIF TMRIF TMRIF Ch PIE PSPIE () ADIE RCIE TXIE SSPIE CCPIE TMRIE TMRIE Fh ADCON ADFM PCFG3 PCFG PCFG PCFG Legend: x = unknown, u = unchanged, - = unimplemented, read as '0'. Shaded cells are not used by the Parallel Slave Port. Note : Bits PSPIE and PSPIF are reserved on the PIC6F873/876; always maintain these bits clear. 00 Microchip Technology Inc. DS309C-page 39

29 PIC6F87X 4.0 DATA EEPROM AND FLASH PROGRAM MEMORY The Data EEPROM and FLASH Program Memory are readable and writable during normal operation over the entire VDD range. These operations take place on a single byte for Data EEPROM memory and a single word for Program memory. A write operation causes an erase-then-write operation to take place on the specified byte or word. A bulk erase operation may not be issued from user code (which includes removing code protection). Access to program memory allows for checksum calculation. The values written to program memory do not need to be valid instructions. Therefore, up to 4-bit numbers can be stored in memory for use as calibration parameters, serial numbers, packed 7-bit ASCII, etc. Executing a program memory location containing data that form an invalid instruction, results in the execution of a NOP instruction. The EEPROM Data memory is rated for high erase/ write cycles (specification D0). The FLASH program memory is rated much lower (specification D30), because EEPROM data memory can be used to store frequently updated values. An on-chip timer controls the write time and it will vary with voltage and temperature, as well as from chip to chip. Please refer to the specifications for exact limits (specifications D and D33). A byte or word write automatically erases the location and writes the new value (erase before write). Writing to EEPROM data memory does not impact the operation of the device. Writing to program memory will cease the execution of instructions until the write is complete. The program memory cannot be accessed during the write. During the write operation, the oscillator continues to run, the peripherals continue to function and interrupt events will be detected and essentially queued until the write is complete. When the write completes, the next instruction in the pipeline is executed and the branch to the interrupt vector will take place, if the interrupt is enabled and occurred during the write. Read and write access to both memories take place indirectly through a set of Special Function Registers (SFR). The six SFRs used are: EEDATA EEDATH EEADR EEADRH EECON EECON The EEPROM data memory allows byte read and write operations without interfering with the normal operation of the microcontroller. When interfacing to EEPROM data memory, the EEADR register holds the address to be accessed. Depending on the operation, the EEDATA register holds the data to be written, or the data read, at the address in EEADR. The PIC6F873/874 devices have 8 bytes of EEPROM data memory and therefore, require that the MSb of EEADR remain clear. The EEPROM data memory on these devices do not wrap around to 0, i.e., 0x80 in the EEADR does not map to 0x00. The PIC6F876/877 devices have 56 bytes of EEPROM data memory and therefore, uses all 8-bits of the EEADR. The FLASH program memory allows non-intrusive read access, but write operations cause the device to stop executing instructions, until the write completes. When interfacing to the program memory, the EEADRH:EEADR registers form a two-byte word, which holds the 3-bit address of the memory location being accessed. The register combination of EEDATH:EEDATA holds the 4-bit data for writes, or reflects the value of program memory after a read operation. Just as in EEPROM data memory accesses, the value of the EEADRH:EEADR registers must be within the valid range of program memory, depending on the device: 0000h to FFFh for the PIC6F873/874, or 0000h to 3FFFh for the PIC6F876/877. Addresses outside of this range do not wrap around to 0000h (i.e., 4000h does not map to 0000h on the PIC6F877). 4. EECON and EECON Registers The EECON register is the control register for configuring and initiating the access. The EECON register is not a physically implemented register, but is used exclusively in the memory write sequence to prevent inadvertent writes. There are many bits used to control the read and write operations to EEPROM data and FLASH program memory. The EEPGD bit determines if the access will be a program or data memory access. When clear, any subsequent operations will work on the EEPROM data memory. When set, all subsequent operations will operate in the program memory. Read operations only use one additional bit, RD, which initiates the read operation from the desired memory location. Once this bit is set, the value of the desired memory location will be available in the data registers. This bit cannot be cleared by firmware. It is automatically cleared at the end of the read operation. For EEPROM data memory reads, the data will be available in the EEDATA register in the very next instruction cycle after the RD bit is set. For program memory reads, the data will be loaded into the EEDATH:EEDATA registers, following the second instruction after the RD bit is set. 00 Microchip Technology Inc. DS309C-page 4

30 PIC6F87X Write operations have two control bits, WR and WREN, and two status bits, WRERR and EEIF. The WREN bit is used to enable or disable the write operation. When WREN is clear, the write operation will be disabled. Therefore, the WREN bit must be set before executing a write operation. The WR bit is used to initiate the write operation. It also is automatically cleared at the end of the write operation. The interrupt flag EEIF is used to determine when the memory write completes. This flag must be cleared in software before setting the WR bit. For EEPROM data memory, once the WREN bit and the WR bit have been set, the desired memory address in EEADR will be erased, followed by a write of the data in EEDATA. This operation takes place in parallel with the microcontroller continuing to execute normally. When the write is complete, the EEIF flag bit will be set. For program memory, once the WREN bit and the WR bit have been set, the microcontroller will cease to execute instructions. The desired memory location pointed to by EEADRH:EEADR will be erased. Then, the data value in EEDATH:EEDATA will be programmed. When complete, the EEIF flag bit will be set and the microcontroller will continue to execute code. The WRERR bit is used to indicate when the PIC6F87X device has been reset during a write operation. WRERR should be cleared after Power-on Reset. Thereafter, it should be checked on any other RESET. The WRERR bit is set when a write operation is interrupted by a MCLR Reset, or a WDT Time-out Reset, during normal operation. In these situations, following a RESET, the user should check the WRERR bit and rewrite the memory location, if set. The contents of the data registers, address registers and EEPGD bit are not affected by either MCLR Reset, or WDT Timeout Reset, during normal operation. REGISTER 4-: EECON REGISTER (ADDRESS 8Ch) R/W-x U-0 U-0 U-0 R/W-x R/W-0 R/S-0 R/S-0 EEPGD WRERR WREN WR RD bit 7 bit 0 bit 7 bit 6-4 bit 3 bit bit bit 0 EEPGD: Program/Data EEPROM Select bit = Accesses program memory 0 = Accesses data memory (This bit cannot be changed while a read or write operation is in progress) Unimplemented: Read as '0' WRERR: EEPROM Error Flag bit = A write operation is prematurely terminated (any MCLR Reset or any WDT Reset during normal operation) 0 = The write operation completed WREN: EEPROM Write Enable bit = Allows write cycles 0 = Inhibits write to the EEPROM WR: Write Control bit = Initiates a write cycle. (The bit is cleared by hardware once write is complete. The WR bit can only be set (not cleared) in software.) 0 = Write cycle to the EEPROM is complete RD: Read Control bit = Initiates an EEPROM read. (RD is cleared in hardware. The RD bit can only be set (not cleared) in software.) 0 = Does not initiate an EEPROM read Legend: R = Readable bit W = Writable bit U = Unimplemented bit, read as 0 - n = Value at POR = Bit is set 0 = Bit is cleared x = Bit is unknown DS309C-page 4 00 Microchip Technology Inc.

31 PIC6F87X 4. Reading the EEPROM Data Memory Reading EEPROM data memory only requires that the desired address to access be written to the EEADR register and clear the EEPGD bit. After the RD bit is set, data will be available in the EEDATA register on the very next instruction cycle. EEDATA will hold this value until another read operation is initiated or until it is written by firmware. The steps to reading the EEPROM data memory are:. Write the address to EEDATA. Make sure that the address is not larger than the memory size of the PIC6F87X device.. Clear the EEPGD bit to point to EEPROM data memory. 3. Set the RD bit to start the read operation. 4. Read the data from the EEDATA register. EXAMPLE 4-: EEPROM DATA READ BSF STATUS, RP ; BCF STATUS, RP0 ;Bank MOVF ADDR, W ;Write address MOVWF EEADR ;to read from BSF STATUS, RP0 ;Bank 3 BCF EECON, EEPGD ;Point to Data memory BSF EECON, RD ;Start read operation BCF STATUS, RP0 ;Bank MOVF EEDATA, W ;W = EEDATA 4.3 Writing to the EEPROM Data Memory There are many steps in writing to the EEPROM data memory. Both address and data values must be written to the SFRs. The EEPGD bit must be cleared, and the WREN bit must be set, to enable writes. The WREN bit should be kept clear at all times, except when writing to the EEPROM data. The WR bit can only be set if the WREN bit was set in a previous operation, i.e., they both cannot be set in the same operation. The WREN bit should then be cleared by firmware after the write. Clearing the WREN bit before the write actually completes will not terminate the write in progress. Writes to EEPROM data memory must also be prefaced with a special sequence of instructions, that prevent inadvertent write operations. This is a sequence of five instructions that must be executed without interruptions. The firmware should verify that a write is not in progress, before starting another cycle. The steps to write to EEPROM data memory are:. If step 0 is not implemented, check the WR bit to see if a write is in progress.. Write the address to EEADR. Make sure that the address is not larger than the memory size of the PIC6F87X device. 3. Write the 8-bit data value to be programmed in the EEDATA register. 4. Clear the EEPGD bit to point to EEPROM data memory. 5. Set the WREN bit to enable program operations. 6. Disable interrupts (if enabled). 7. Execute the special five instruction sequence: Write 55h to EECON in two steps (first to W, then to EECON) Write AAh to EECON in two steps (first to W, then to EECON) Set the WR bit 8. Enable interrupts (if using interrupts). 9. Clear the WREN bit to disable program operations. 0. At the completion of the write cycle, the WR bit is cleared and the EEIF interrupt flag bit is set. (EEIF must be cleared by firmware.) If step is not implemented, then firmware should check for EEIF to be set, or WR to clear, to indicate the end of the program cycle. EXAMPLE 4-: EEPROM DATA WRITE BSF STATUS, RP ; BSF STATUS, RP0 ;Bank 3 BTFSC EECON, WR ;Wait for GOTO $- ;write to finish BCF STATUS, RP0 ;Bank MOVF ADDR, W ;Address to MOVWF EEADR ;write to MOVF VALUE, W ;Data to MOVWF EEDATA ;write BSF STATUS, RP0 ;Bank 3 BCF EECON, EEPGD ;Point to Data memory BSF EECON, WREN ;Enable writes ;Only disable interrupts BCF INTCON, GIE ;if already enabled, ;otherwise discard MOVLW 0x55 ;Write 55h to MOVWF EECON ;EECON MOVLW 0xAA ;Write AAh to MOVWF EECON ;EECON BSF EECON, WR ;Start write operation ;Only enable interrupts BSF INTCON, GIE ;if using interrupts, ;otherwise discard BCF EECON, WREN ;Disable writes 00 Microchip Technology Inc. DS309C-page 43

32 PIC6F87X 4.4 Reading the FLASH Program Memory Reading FLASH program memory is much like that of EEPROM data memory, only two NOP instructions must be inserted after the RD bit is set. These two instruction cycles that the NOP instructions execute, will be used by the microcontroller to read the data out of program memory and insert the value into the EEDATH:EEDATA registers. Data will be available following the second NOP instruction. EEDATH and EEDATA will hold their value until another read operation is initiated, or until they are written by firmware. The steps to reading the FLASH program memory are:. Write the address to EEADRH:EEADR. Make sure that the address is not larger than the memory size of the PIC6F87X device.. Set the EEPGD bit to point to FLASH program memory. 3. Set the RD bit to start the read operation. 4. Execute two NOP instructions to allow the microcontroller to read out of program memory. 5. Read the data from the EEDATH:EEDATA registers. EXAMPLE 4-3: FLASH PROGRAM READ BSF STATUS, RP ; BCF STATUS, RP0 ;Bank MOVF ADDRL, W ;Write the MOVWF EEADR ;address bytes MOVF ADDRH,W ;for the desired MOVWF EEADRH ;address to read BSF STATUS, RP0 ;Bank 3 BSF EECON, EEPGD ;Point to Program memory BSF EECON, RD ;Start read operation NOP ;Required two NOPs NOP ; BCF STATUS, RP0 ;Bank MOVF EEDATA, W ;DATAL = EEDATA MOVWF DATAL ; MOVF EEDATH,W ;DATAH = EEDATH MOVWF DATAH ; 4.5 Writing to the FLASH Program Memory Writing to FLASH program memory is unique, in that the microcontroller does not execute instructions while programming is taking place. The oscillator continues to run and all peripherals continue to operate and queue interrupts, if enabled. Once the write operation completes (specification D33), the processor begins executing code from where it left off. The other important difference when writing to FLASH program memory, is that the WRT configuration bit, when clear, prevents any writes to program memory (see Table 4-). Just like EEPROM data memory, there are many steps in writing to the FLASH program memory. Both address and data values must be written to the SFRs. The EEPGD bit must be set, and the WREN bit must be set to enable writes. The WREN bit should be kept clear at all times, except when writing to the FLASH Program memory. The WR bit can only be set if the WREN bit was set in a previous operation, i.e., they both cannot be set in the same operation. The WREN bit should then be cleared by firmware after the write. Clearing the WREN bit before the write actually completes will not terminate the write in progress. Writes to program memory must also be prefaced with a special sequence of instructions that prevent inadvertent write operations. This is a sequence of five instructions that must be executed without interruption for each byte written. These instructions must then be followed by two NOP instructions to allow the microcontroller to setup for the write operation. Once the write is complete, the execution of instructions starts with the instruction after the second NOP. The steps to write to program memory are:. Write the address to EEADRH:EEADR. Make sure that the address is not larger than the memory size of the PIC6F87X device.. Write the 4-bit data value to be programmed in the EEDATH:EEDATA registers. 3. Set the EEPGD bit to point to FLASH program memory. 4. Set the WREN bit to enable program operations. 5. Disable interrupts (if enabled). 6. Execute the special five instruction sequence: Write 55h to EECON in two steps (first to W, then to EECON) Write AAh to EECON in two steps (first to W, then to EECON) Set the WR bit 7. Execute two NOP instructions to allow the microcontroller to setup for write operation. 8. Enable interrupts (if using interrupts). 9. Clear the WREN bit to disable program operations. DS309C-page Microchip Technology Inc.

33 PIC6F87X At the completion of the write cycle, the WR bit is cleared and the EEIF interrupt flag bit is set. (EEIF must be cleared by firmware.) Since the microcontroller does not execute instructions during the write cycle, the firmware does not necessarily have to check either EEIF, or WR, to determine if the write had finished. EXAMPLE 4-4: 4.6 Write Verify FLASH PROGRAM WRITE BSF STATUS, RP ; BCF STATUS, RP0 ;Bank MOVF ADDRL, W ;Write address MOVWF EEADR ;of desired MOVF ADDRH, W ;program memory MOVWF EEADRH ;location MOVF VALUEL, W ;Write value to MOVWF EEDATA ;program at MOVF VALUEH, W ;desired memory MOVWF EEDATH ;location BSF STATUS, RP0 ;Bank 3 BSF EECON, EEPGD ;Point to Program memory BSF EECON, WREN ;Enable writes ;Only disable interrupts BCF INTCON, GIE ;if already enabled, ;otherwise discard MOVLW 0x55 ;Write 55h to MOVWF EECON ;EECON MOVLW 0xAA ;Write AAh to MOVWF EECON ;EECON BSF EECON, WR ;Start write operation NOP ;Two NOPs to allow micro NOP ;to setup for write ;Only enable interrupts BSF INTCON, GIE ;if using interrupts, ;otherwise discard BCF EECON, WREN ;Disable writes The PIC6F87X devices do not automatically verify the value written during a write operation. Depending on the application, good programming practice may dictate that the value written to memory be verified against the original value. This should be used in applications where excessive writes can stress bits near the specified endurance limits. 4.7 Protection Against Spurious Writes There are conditions when the device may not want to write to the EEPROM data memory or FLASH program memory. To protect against these spurious write conditions, various mechanisms have been built into the PIC6F87X devices. On power-up, the WREN bit is cleared and the Power-up Timer (if enabled) prevents writes. The write initiate sequence, and the WREN bit together, help prevent any accidental writes during brown-out, power glitches, or firmware malfunction. 4.8 Operation While Code Protected The PIC6F87X devices have two code protect mechanisms, one bit for EEPROM data memory and two bits for FLASH program memory. Data can be read and written to the EEPROM data memory, regardless of the state of the code protection bit, CPD. When code protection is enabled and CPD cleared, external access via ICSP is disabled, regardless of the state of the program memory code protect bits. This prevents the contents of EEPROM data memory from being read out of the device. The state of the program memory code protect bits, CP0 and CP, do not affect the execution of instructions out of program memory. The PIC6F87X devices can always read the values in program memory, regardless of the state of the code protect bits. However, the state of the code protect bits and the WRT bit will have different effects on writing to program memory. Table 4- shows the effect of the code protect bits and the WRT bit on program memory. Once code protection has been enabled for either EEPROM data memory or FLASH program memory, only a full erase of the entire device will disable code protection. 00 Microchip Technology Inc. DS309C-page 45

34 PIC6F87X 4.9 FLASH Program Memory Write Protection The configuration word contains a bit that write protects the FLASH program memory, called WRT. This bit can only be accessed when programming the PIC6F87X device via ICSP. Once write protection is enabled, only an erase of the entire device will disable it. When enabled, write protection prevents any writes to FLASH program memory. Write protection does not affect program memory reads. TABLE 4-: READ/WRITE STATE OF INTERNAL FLASH PROGRAM MEMORY Configuration Bits CP CP0 WRT Memory Location Internal Read Internal Write ICSP Read ICSP Write 0 0 x All program memory Yes No No No 0 0 Unprotected areas Yes No Yes No 0 0 Protected areas Yes No No No 0 Unprotected areas Yes Yes Yes No 0 Protected areas Yes No No No 0 0 Unprotected areas Yes No Yes No 0 0 Protected areas Yes No No No 0 Unprotected areas Yes Yes Yes No 0 Protected areas Yes No No No 0 All program memory Yes No Yes Yes All program memory Yes Yes Yes Yes TABLE 4-: REGISTERS ASSOCIATED WITH DATA EEPROM/PROGRAM FLASH Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 0Bh, 8Bh, 0Bh, 8Bh Value on: POR, BOR Value on all other RESETS INTCON GIE PEIE T0IE INTE RBIE T0IF INTF RBIF x u 0Dh EEADR EEPROM Address Register, Low Byte xxxx xxxx uuuu uuuu 0Fh EEADRH EEPROM Address, High Byte xxxx xxxx uuuu uuuu 0Ch EEDATA EEPROM Data Register, Low Byte xxxx xxxx uuuu uuuu 0Eh EEDATH EEPROM Data Register, High Byte xxxx xxxx uuuu uuuu 8Ch EECON EEPGD WRERR WREN WR RD x--- x000 x--- u000 8Dh EECON EEPROM Control Register (not a physical register) 8Dh PIE () EEIE BCLIE CCPIE -r r Dh PIR () EEIF BCLIF CCPIF -r r Legend: x = unknown, u = unchanged, r = reserved, - = unimplemented, read as '0'. Shaded cells are not used during FLASH/EEPROM access. Note : These bits are reserved; always maintain these bits clear. DS309C-page Microchip Technology Inc.

35 PIC6F87X 5.0 TIMER0 MODULE The Timer0 module timer/counter has the following features: 8-bit timer/counter Readable and writable 8-bit software programmable prescaler Internal or external clock select Interrupt on overflow from FFh to 00h Edge select for external clock Figure 5- is a block diagram of the Timer0 module and the prescaler shared with the WDT. Additional information on the Timer0 module is available in the PICmicro Mid-Range MCU Family Reference Manual (DS3303). Timer mode is selected by clearing bit T0CS (OPTION_REG<5>). In Timer mode, the Timer0 module will increment every instruction cycle (without prescaler). If the TMR0 register is written, the increment is inhibited for the following two instruction cycles. The user can work around this by writing an adjusted value to the TMR0 register. Counter mode is selected by setting bit T0CS (OPTION_REG<5>). In Counter mode, Timer0 will increment either on every rising, or falling edge of pin RA4/T0CKI. The incrementing edge is determined by the Timer0 Source Edge Select bit, T0SE (OPTION_REG<4>). Clearing bit T0SE selects the rising edge. Restrictions on the external clock input are discussed in detail in Section 5.. The prescaler is mutually exclusively shared between the Timer0 module and the Watchdog Timer. The prescaler is not readable or writable. Section 5.3 details the operation of the prescaler. 5. Timer0 Interrupt The TMR0 interrupt is generated when the TMR0 register overflows from FFh to 00h. This overflow sets bit T0IF (INTCON<>). The interrupt can be masked by clearing bit T0IE (INTCON<5>). Bit T0IF must be cleared in software by the Timer0 module Interrupt Service Routine before re-enabling this interrupt. The TMR0 interrupt cannot awaken the processor from SLEEP, since the timer is shut-off during SLEEP. FIGURE 5-: BLOCK DIAGRAM OF THE TIMER0/WDT PRESCALER CLKOUT (= FOSC/4) Data Bus RA4/T0CKI pin 0 M U X 0 M U X SYNC Cycles 8 TMR0 Reg T0SE T0CS PSA Set Flag Bit T0IF on Overflow PRESCALER Watchdog Timer 0 M U X 8-bit Prescaler 8 PSA 8 - to - MUX PS:PS0 WDT Enable bit 0 M U X PSA WDT Time-out Note: T0CS, T0SE, PSA, PS:PS0 are (OPTION_REG<5:0>). 00 Microchip Technology Inc. DS309C-page 47

36 PIC6F87X 5. Using Timer0 with an External Clock When no prescaler is used, the external clock input is the same as the prescaler output. The synchronization of T0CKI with the internal phase clocks is accomplished by sampling the prescaler output on the Q and Q4 cycles of the internal phase clocks. Therefore, it is necessary for T0CKI to be high for at least Tosc (and a small RC delay of 0 ns) and low for at least Tosc (and a small RC delay of 0 ns). Refer to the electrical specification of the desired device. 5.3 Prescaler There is only one prescaler available, which is mutually exclusively shared between the Timer0 module and the Watchdog Timer. A prescaler assignment for the Timer0 module means that there is no prescaler for the Watchdog Timer, and vice-versa. This prescaler is not readable or writable (see Figure 5-). The PSA and PS:PS0 bits (OPTION_REG<3:0>) determine the prescaler assignment and prescale ratio. When assigned to the Timer0 module, all instructions writing to the TMR0 register (e.g. CLRF, MOVWF, BSF,x...etc.) will clear the prescaler. When assigned to WDT, a CLRWDT instruction will clear the prescaler along with the Watchdog Timer. The prescaler is not readable or writable. Note: Writing to TMR0, when the prescaler is assigned to Timer0, will clear the prescaler count, but will not change the prescaler assignment. REGISTER 5-: OPTION_REG REGISTER R/W- R/W- R/W- R/W- R/W- R/W- R/W- R/W- RBPU INTEDG T0CS T0SE PSA PS PS PS0 bit 7 bit 0 bit 7 bit 6 bit 5 bit 4 bit 3 bit -0 RBPU INTEDG T0CS: TMR0 Clock Source Select bit = Transition on T0CKI pin 0 = Internal instruction cycle clock (CLKOUT) T0SE: TMR0 Source Edge Select bit = Increment on high-to-low transition on T0CKI pin 0 = Increment on low-to-high transition on T0CKI pin PSA: Prescaler Assignment bit = Prescaler is assigned to the WDT 0 = Prescaler is assigned to the Timer0 module PS:PS0: Prescaler Rate Select bits Bit Value TMR0 Rate WDT Rate : : 4 : 8 : 6 : 3 : 64 : 8 : 56 : : : 4 : 8 : 6 : 3 : 64 : 8 Legend: R = Readable bit W = Writable bit U = Unimplemented bit, read as 0 - n = Value at POR = Bit is set 0 = Bit is cleared x = Bit is unknown Note: To avoid an unintended device RESET, the instruction sequence shown in the PICmicro Mid-Range MCU Family Reference Manual (DS3303) must be executed when changing the prescaler assignment from Timer0 to the WDT. This sequence must be followed even if the WDT is disabled. DS309C-page Microchip Technology Inc.

37 PIC6F87X TABLE 5-: REGISTERS ASSOCIATED WITH TIMER0 Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 Value on: POR, BOR Value on all other RESETS 0h,0h TMR0 Timer0 Module s Register xxxx xxxx uuuu uuuu 0Bh,8Bh, 0Bh,8Bh INTCON GIE PEIE T0IE INTE RBIE T0IF INTF RBIF x u 8h,8h OPTION_REG RBPU INTEDG T0CS T0SE PSA PS PS PS0 Legend: x = unknown, u = unchanged, - = unimplemented locations read as '0'. Shaded cells are not used by Timer0. 00 Microchip Technology Inc. DS309C-page 49

38 PIC6F87X 6.0 TIMER MODULE The Timer module is a 6-bit timer/counter consisting of two 8-bit registers (TMRH and TMRL), which are readable and writable. The TMR Register pair (TMRH:TMRL) increments from 0000h to FFFFh and rolls over to 0000h. The TMR Interrupt, if enabled, is generated on overflow, which is latched in interrupt flag bit TMRIF (PIR<0>). This interrupt can be enabled/disabled by setting/clearing TMR interrupt enable bit TMRIE (PIE<0>). Timer can operate in one of two modes: As a timer As a counter The operating mode is determined by the clock select bit, TMRCS (TCON<>). In Timer mode, Timer increments every instruction cycle. In Counter mode, it increments on every rising edge of the external clock input. Timer can be enabled/disabled by setting/clearing control bit TMRON (TCON<0>). Timer also has an internal RESET input. This RESET can be generated by either of the two CCP modules (Section 8.0). Register 6- shows the Timer control register. When the Timer oscillator is enabled (TOSCEN is set), the RC/TOSI/CCP and RC0/TOSO/TCKI pins become inputs. That is, the TRISC<:0> value is ignored, and these pins read as 0. Additional information on timer modules is available in the PICmicro Mid-Range MCU Family Reference Manual (DS3303). REGISTER 6-: TCON: TIMER CONTROL REGISTER (ADDRESS 0h) U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 TCKPS TCKPS0 TOSCEN TSYNC TMRCS TMRON bit 7 bit 0 bit 7-6 bit 5-4 bit 3 bit bit bit 0 Unimplemented: Read as '0' TCKPS:TCKPS0: Timer Input Clock Prescale Select bits = :8 Prescale value 0 = :4 Prescale value 0 = : Prescale value 00 = : Prescale value TOSCEN: Timer Oscillator Enable Control bit = Oscillator is enabled 0 = Oscillator is shut-off (the oscillator inverter is turned off to eliminate power drain) TSYNC: Timer External Clock Input Synchronization Control bit When TMRCS = : = Do not synchronize external clock input 0 = Synchronize external clock input When TMRCS = 0: This bit is ignored. Timer uses the internal clock when TMRCS = 0. TMRCS: Timer Clock Source Select bit = External clock from pin RC0/TOSO/TCKI (on the rising edge) 0 = Internal clock (FOSC/4) TMRON: Timer On bit = Enables Timer 0 = Stops Timer Legend: R = Readable bit W = Writable bit U = Unimplemented bit, read as 0 - n = Value at POR = Bit is set 0 = Bit is cleared x = Bit is unknown 00 Microchip Technology Inc. DS309C-page 5

39 PIC6F87X 6. Timer Operation in Timer Mode Timer mode is selected by clearing the TMRCS (TCON<>) bit. In this mode, the input clock to the timer is FOSC/4. The synchronize control bit TSYNC (TCON<>) has no effect, since the internal clock is always in sync. 6. Timer Counter Operation Timer may operate in either a Synchronous, or an Asynchronous mode, depending on the setting of the TMRCS bit. When Timer is being incremented via an external source, increments occur on a rising edge. After Timer is enabled in Counter mode, the module must first have a falling edge before the counter begins to increment. FIGURE 6-: TIMER INCREMENTING EDGE TCKI (Default High) TCKI (Default Low) Note: Arrows indicate counter increments. 6.3 Timer Operation in Synchronized Counter Mode Counter mode is selected by setting bit TMRCS. In this mode, the timer increments on every rising edge of clock input on pin RC/TOSI/CCP, when bit TOSCEN is set, or on pin RC0/TOSO/TCKI, when bit TOSCEN is cleared. If TSYNC is cleared, then the external clock input is synchronized with internal phase clocks. The synchronization is done after the prescaler stage. The prescaler stage is an asynchronous ripple-counter. In this configuration, during SLEEP mode, Timer will not increment even if the external clock is present, since the synchronization circuit is shut-off. The prescaler, however, will continue to increment. FIGURE 6-: TIMER BLOCK DIAGRAM Set Flag bit TMRIF on Overflow RC0/TOSO/TCKI RC/TOSI/CCP () TMRH TOSC TMR TMRL TOSCEN Enable Oscillator () FOSC/4 Internal Clock TMRON On/Off 0 TMRCS 0 TSYNC Prescaler,, 4, 8 TCKPS:TCKPS0 Synchronized Clock Input Synchronize det Q Clock Note : When the TOSCEN bit is cleared, the inverter is turned off. This eliminates power drain. DS309C-page 5 00 Microchip Technology Inc.

40 PIC6F87X 6.4 Timer Operation in Asynchronous Counter Mode TABLE 6-: CAPACITOR SELECTION FOR THE TIMER OSCILLATOR If control bit TSYNC (TCON<>) is set, the external clock input is not synchronized. The timer continues to increment asynchronous to the internal phase clocks. The timer will continue to run during SLEEP and can generate an interrupt-on-overflow, which will wake-up the processor. However, special precautions in software are needed to read/write the timer (Section 6.4.). In Asynchronous Counter mode, Timer cannot be used as a time-base for capture or compare operations READING AND WRITING TIMER IN ASYNCHRONOUS COUNTER MODE Reading TMRH or TMRL while the timer is running from an external asynchronous clock, will guarantee a valid read (taken care of in hardware). However, the user should keep in mind that reading the 6-bit timer in two 8-bit values itself, poses certain problems, since the timer may overflow between the reads. For writes, it is recommended that the user simply stop the timer and write the desired values. A write contention may occur by writing to the timer registers, while the register is incrementing. This may produce an unpredictable value in the timer register. Reading the 6-bit value requires some care. Examples - and -3 in the PICmicro Mid-Range MCU Family Reference Manual (DS3303) show how to read and write Timer when it is running in Asynchronous mode. 6.5 Timer Oscillator A crystal oscillator circuit is built-in between pins TOSI (input) and TOSO (amplifier output). It is enabled by setting control bit TOSCEN (TCON<3>). The oscillator is a low power oscillator, rated up to 00 khz. It will continue to run during SLEEP. It is primarily intended for use with a 3 khz crystal. Table 6- shows the capacitor selection for the Timer oscillator. The Timer oscillator is identical to the LP oscillator. The user must provide a software time delay to ensure proper oscillator start-up. Osc Type Freq. C C LP 3 khz 33 pf 33 pf 00 khz 5 pf 5 pf 00 khz 5 pf 5 pf These values are for design guidance only. Crystals Tested: khz Epson C-00R3.768K-A ± 0 PPM 00 khz Epson C KC-P ± 0 PPM 00 khz STD XTL khz ± 0 PPM Note : Higher capacitance increases the stability of oscillator, but also increases the start-up time. : Since each resonator/crystal has its own characteristics, the user should consult the resonator/crystal manufacturer for appropriate values of external components. 6.6 Resetting Timer using a CCP Trigger Output If the CCP or CCP module is configured in Compare mode to generate a special event trigger (CCPM3:CCPM0 = 0), this signal will reset Timer. Note: The special event triggers from the CCP and CCP modules will not set interrupt flag bit TMRIF (PIR<0>). Timer must be configured for either Timer or Synchronized Counter mode to take advantage of this feature. If Timer is running in Asynchronous Counter mode, this RESET operation may not work. In the event that a write to Timer coincides with a special event trigger from CCP or CCP, the write will take precedence. In this mode of operation, the CCPRxH:CCPRxL register pair effectively becomes the period register for Timer. 00 Microchip Technology Inc. DS309C-page 53

41 PIC6F87X 6.7 Resetting of Timer Register Pair (TMRH, TMRL) TMRH and TMRL registers are not reset to 00h on a POR, or any other RESET, except by the CCP and CCP special event triggers. TCON register is reset to 00h on a Power-on Reset, or a Brown-out Reset, which shuts off the timer and leaves a : prescale. In all other RESETS, the register is unaffected. 6.8 Timer Prescaler The prescaler counter is cleared on writes to the TMRH or TMRL registers. TABLE 6-: REGISTERS ASSOCIATED WITH TIMER AS A TIMER/COUNTER Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 0Bh,8Bh, 0Bh, 8Bh Value on: POR, BOR Value on all other RESETS INTCON GIE PEIE T0IE INTE RBIE T0IF INTF RBIF x u 0Ch PIR PSPIF () ADIF RCIF TXIF SSPIF CCPIF TMRIF TMRIF Ch PIE PSPIE () ADIE RCIE TXIE SSPIE CCPIE TMRIE TMRIE Eh TMRL Holding Register for the Least Significant Byte of the 6-bit TMR Register xxxx xxxx uuuu uuuu 0Fh TMRH Holding Register for the Most Significant Byte of the 6-bit TMR Register xxxx xxxx uuuu uuuu 0h TCON TCKPS TCKPS0 TOSCEN TSYNC TMRCS TMRON uu uuuu Legend: x = unknown, u = unchanged, - = unimplemented, read as '0'. Shaded cells are not used by the Timer module. Note : Bits PSPIE and PSPIF are reserved on the PIC6F873/876; always maintain these bits clear. DS309C-page Microchip Technology Inc.

42 PIC6F87X 7.0 TIMER MODULE Timer is an 8-bit timer with a prescaler and a postscaler. It can be used as the PWM time-base for the PWM mode of the CCP module(s). The TMR register is readable and writable, and is cleared on any device RESET. The input clock (FOSC/4) has a prescale option of :, :4, or :6, selected by control bits TCKPS:TCKPS0 (TCON<:0>). The Timer module has an 8-bit period register, PR. Timer increments from 00h until it matches PR and then resets to 00h on the next increment cycle. PR is a readable and writable register. The PR register is initialized to FFh upon RESET. The match output of TMR goes through a 4-bit postscaler (which gives a : to :6 scaling inclusive) to generate a TMR interrupt (latched in flag bit TMRIF, (PIR<>)). Timer can be shut-off by clearing control bit TMRON (TCON<>), to minimize power consumption. Register 7- shows the Timer control register. Additional information on timer modules is available in the PICmicro Mid-Range MCU Family Reference Manual (DS3303). FIGURE 7-: Sets Flag bit TMRIF Postscaler : to :6 4 TOUTPS3: TOUTPS0 TMR Output () RESET EQ TIMER BLOCK DIAGRAM TMR Reg Comparator PR Reg Prescaler :, :4, :6 TCKPS: TCKPS0 FOSC/4 Note : TMR register output can be software selected by the SSP module as a baud clock. REGISTER 7-: TCON: TIMER CONTROL REGISTER (ADDRESS h) U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 TOUTPS3 TOUTPS TOUTPS TOUTPS0 TMRON TCKPS TCKPS0 bit 7 bit 0 bit 7 bit 6-3 bit bit -0 Unimplemented: Read as '0' TOUTPS3:TOUTPS0: Timer Output Postscale Select bits 0000 = : Postscale 000 = : Postscale 000 = :3 Postscale = :6 Postscale TMRON: Timer On bit = Timer is on 0 = Timer is off TCKPS:TCKPS0: Timer Clock Prescale Select bits 00 = Prescaler is 0 = Prescaler is 4 x = Prescaler is 6 Legend: R = Readable bit W = Writable bit U = Unimplemented bit, read as 0 - n = Value at POR = Bit is set 0 = Bit is cleared x = Bit is unknown 00 Microchip Technology Inc. DS309C-page 55

43 PIC6F87X 7. Timer Prescaler and Postscaler The prescaler and postscaler counters are cleared when any of the following occurs: a write to the TMR register a write to the TCON register any device RESET (POR, MCLR Reset, WDT Reset, or BOR) TMR is not cleared when TCON is written. 7. Output of TMR The output of TMR (before the postscaler) is fed to the SSP module, which optionally uses it to generate shift clock. TABLE 7-: REGISTERS ASSOCIATED WITH TIMER AS A TIMER/COUNTER Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 0Bh,8Bh, 0Bh,8Bh Value on: POR, BOR Value on all other RESETS INTCON GIE PEIE T0IE INTE RBIE T0IF INTF RBIF x u 0Ch PIR PSPIF () ADIF RCIF TXIF SSPIF CCPIF TMRIF TMRIF Ch PIE PSPIE () ADIE RCIE TXIE SSPIE CCPIE TMRIE TMRIE h TMR Timer Module s Register h TCON TOUTPS3 TOUTPS TOUTPS TOUTPS0 TMRON TCKPS TCKPS h PR Timer Period Register Legend: x = unknown, u = unchanged, - = unimplemented, read as '0'. Shaded cells are not used by the Timer module. Note : Bits PSPIE and PSPIF are reserved on the PIC6F873/876; always maintain these bits clear. DS309C-page Microchip Technology Inc.

44 PIC6F87X 8.0 CAPTURE/COMPARE/PWM MODULES Each Capture/Compare/PWM (CCP) module contains a 6-bit register which can operate as a: 6-bit Capture register 6-bit Compare register PWM Master/Slave Duty Cycle register Both the CCP and CCP modules are identical in operation, with the exception being the operation of the special event trigger. Table 8- and Table 8- show the resources and interactions of the CCP module(s). In the following sections, the operation of a CCP module is described with respect to CCP. CCP operates the same as CCP, except where noted. CCP Module: Capture/Compare/PWM Register (CCPR) is comprised of two 8-bit registers: CCPRL (low byte) and CCPRH (high byte). The CCPCON register controls the operation of CCP. The special event trigger is generated by a compare match and will reset Timer. CCP Module: Capture/Compare/PWM Register (CCPR) is comprised of two 8-bit registers: CCPRL (low byte) and CCPRH (high byte). The CCPCON register controls the operation of CCP. The special event trigger is generated by a compare match and will reset Timer and start an A/D conversion (if the A/D module is enabled). Additional information on CCP modules is available in the PICmicro Mid-Range MCU Family Reference Manual (DS3303) and in application note AN594, Using the CCP Modules (DS00594). TABLE 8-: CCP Mode Capture Compare PWM CCP MODE - TIMER RESOURCES REQUIRED Timer Resource Timer Timer Timer TABLE 8-: INTERACTION OF TWO CCP MODULES CCPx Mode CCPy Mode Interaction Capture Capture Same TMR time-base Capture Compare The compare should be configured for the special event trigger, which clears TMR Compare Compare The compare(s) should be configured for the special event trigger, which clears TMR PWM PWM The PWMs will have the same frequency and update rate (TMR interrupt) PWM Capture None PWM Compare None 00 Microchip Technology Inc. DS309C-page 57

45 PIC6F87X REGISTER 8-: CCPCON REGISTER/CCPCON REGISTER (ADDRESS: 7h/Dh) U-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 CCPxX CCPxY CCPxM3 CCPxM CCPxM CCPxM0 bit 7 bit 0 bit 7-6 bit 5-4 bit 3-0 Unimplemented: Read as '0' CCPxX:CCPxY: PWM Least Significant bits Capture mode: Unused Compare mode: Unused PWM mode: These bits are the two LSbs of the PWM duty cycle. The eight MSbs are found in CCPRxL. CCPxM3:CCPxM0: CCPx Mode Select bits 0000 = Capture/Compare/PWM disabled (resets CCPx module) 000 = Capture mode, every falling edge 00 = Capture mode, every rising edge 00 = Capture mode, every 4th rising edge 0 = Capture mode, every 6th rising edge 000 = Compare mode, set output on match (CCPxIF bit is set) 00 = Compare mode, clear output on match (CCPxIF bit is set) 00 = Compare mode, generate software interrupt on match (CCPxIF bit is set, CCPx pin is unaffected) 0 = Compare mode, trigger special event (CCPxIF bit is set, CCPx pin is unaffected); CCP resets TMR; CCP resets TMR and starts an A/D conversion (if A/D module is enabled) xx =PWM mode Legend: R = Readable bit W = Writable bit U = Unimplemented bit, read as 0 - n = Value at POR = Bit is set 0 = Bit is cleared x = Bit is unknown DS309C-page Microchip Technology Inc.

46 PIC6F87X 8. Capture Mode In Capture mode, CCPRH:CCPRL captures the 6-bit value of the TMR register when an event occurs on pin RC/CCP. An event is defined as one of the following: Every falling edge Every rising edge Every 4th rising edge Every 6th rising edge The type of event is configured by control bits CCPM3:CCPM0 (CCPxCON<3:0>). When a capture is made, the interrupt request flag bit CCPIF (PIR<>) is set. The interrupt flag must be cleared in software. If another capture occurs before the value in register CCPR is read, the old captured value is overwritten by the new value. 8.. CCP PIN CONFIGURATION In Capture mode, the RC/CCP pin should be configured as an input by setting the TRISC<> bit. Note: FIGURE 8-: If the RC/CCP pin is configured as an output, a write to the port can cause a capture condition. Qs CAPTURE MODE OPERATION BLOCK DIAGRAM CCPCON<3:0> Capture Enable CCPRH TMRH CCPRL TMRL 8.. TIMER MODE SELECTION Timer must be running in Timer mode, or Synchronized Counter mode, for the CCP module to use the capture feature. In Asynchronous Counter mode, the capture operation may not work SOFTWARE INTERRUPT When the Capture mode is changed, a false capture interrupt may be generated. The user should keep bit CCPIE (PIE<>) clear to avoid false interrupts and should clear the flag bit CCPIF, following any such change in operating mode CCP PRESCALER There are four prescaler settings, specified by bits CCPM3:CCPM0. Whenever the CCP module is turned off, or the CCP module is not in Capture mode, the prescaler counter is cleared. Any RESET will clear the prescaler counter. Switching from one capture prescaler to another may generate an interrupt. Also, the prescaler counter will not be cleared, therefore, the first capture may be from a non-zero prescaler. Example 8- shows the recommended method for switching between capture prescalers. This example also clears the prescaler counter and will not generate the false interrupt. EXAMPLE 8-: CHANGING BETWEEN CAPTURE PRESCALERS RC/CCP Set Flag bit CCPIF pin Prescaler (PIR<>) CLRF CCPCON ; Turn CCP module off, 4, 6 and edge detect MOVLW NEW_CAPT_PS ; Load the W reg with ; the new prescaler ; move value and CCP ON MOVWF CCPCON ; Load CCPCON with this ; value 00 Microchip Technology Inc. DS309C-page 59

47 PIC6F87X 8. Compare Mode In Compare mode, the 6-bit CCPR register value is constantly compared against the TMR register pair value. When a match occurs, the RC/CCP pin is: Driven high Driven low Remains unchanged The action on the pin is based on the value of control bits CCPM3:CCPM0 (CCPCON<3:0>). At the same time, interrupt flag bit CCPIF is set. FIGURE 8-: COMPARE MODE OPERATION BLOCK DIAGRAM Special event trigger will: reset Timer, but not set interrupt flag bit TMRIF (PIR<0>), and set bit GO/DONE (ADCON0<>). RC/CCP pin Q TRISC<> Output Enable Special Event Trigger S R Output Logic CCPCON<3:0> Mode Select Set Flag bit CCPIF (PIR<>) CCPRH CCPRL Match Comparator TMRH TMRL 8.. TIMER MODE SELECTION Timer must be running in Timer mode, or Synchronized Counter mode, if the CCP module is using the compare feature. In Asynchronous Counter mode, the compare operation may not work SOFTWARE INTERRUPT MODE When Generate Software Interrupt mode is chosen, the CCP pin is not affected. The CCPIF bit is set, causing a CCP interrupt (if enabled) SPECIAL EVENT TRIGGER In this mode, an internal hardware trigger is generated, which may be used to initiate an action. The special event trigger output of CCP resets the TMR register pair. This allows the CCPR register to effectively be a 6-bit programmable period register for Timer. The special event trigger output of CCP resets the TMR register pair and starts an A/D conversion (if the A/D module is enabled). Note: The special event trigger from the CCPand CCP modules will not set interrupt flag bit TMRIF (PIR<0>). 8.. CCP PIN CONFIGURATION The user must configure the RC/CCP pin as an output by clearing the TRISC<> bit. Note: Clearing the CCPCON register will force the RC/CCP compare output latch to the default low level. This is not the PORTC I/O data latch. DS309C-page Microchip Technology Inc.

48 PIC6F87X 8.3 PWM Mode (PWM) In Pulse Width Modulation mode, the CCPx pin produces up to a 0-bit resolution PWM output. Since the CCP pin is multiplexed with the PORTC data latch, the TRISC<> bit must be cleared to make the CCP pin an output. Note: Figure 8-3 shows a simplified block diagram of the CCP module in PWM mode. For a step-by-step procedure on how to set up the CCP module for PWM operation, see Section FIGURE 8-3: Clearing the CCPCON register will force the CCP PWM output latch to the default low level. This is not the PORTC I/O data latch. Duty Cycle Registers CCPRL SIMPLIFIED PWM BLOCK DIAGRAM CCPCON<5:4> 8.3. PWM PERIOD The PWM period is specified by writing to the PR register. The PWM period can be calculated using the following formula: PWM period = [(PR) + ] 4 TOSC (TMR prescale value) PWM frequency is defined as / [PWM period]. When TMR is equal to PR, the following three events occur on the next increment cycle: TMR is cleared The CCP pin is set (exception: if PWM duty cycle = 0%, the CCP pin will not be set) The PWM duty cycle is latched from CCPRL into CCPRH Note: The Timer postscaler (see Section 7.) is not used in the determination of the PWM frequency. The postscaler could be used to have a servo update rate at a different frequency than the PWM output PWM DUTY CYCLE CCPRH (Slave) Comparator TMR Comparator PR A PWM output (Figure 8-4) has a time-base (period) and a time that the output stays high (duty cycle). The frequency of the PWM is the inverse of the period (/period). FIGURE 8-4: (Note ) R S Clear Timer, CCP pin and latch D.C. Q PWM OUTPUT TRISC<> RC/CCP Note : The 8-bit timer is concatenated with -bit internal Q clock, or bits of the prescaler, to create 0-bit timebase. Period Duty Cycle TMR = PR TMR = PR TMR = Duty Cycle The PWM duty cycle is specified by writing to the CCPRL register and to the CCPCON<5:4> bits. Up to 0-bit resolution is available. The CCPRL contains the eight MSbs and the CCPCON<5:4> contains the two LSbs. This 0-bit value is represented by CCPRL:CCPCON<5:4>. The following equation is used to calculate the PWM duty cycle in time: PWM duty cycle =(CCPRL:CCPCON<5:4>) TOSC (TMR prescale value) CCPRL and CCPCON<5:4> can be written to at any time, but the duty cycle value is not latched into CCPRH until after a match between PR and TMR occurs (i.e., the period is complete). In PWM mode, CCPRH is a read-only register. The CCPRH register and a -bit internal latch are used to double buffer the PWM duty cycle. This double buffering is essential for glitch-free PWM operation. When the CCPRH and -bit latch match TMR, concatenated with an internal -bit Q clock, or bits of the TMR prescaler, the CCP pin is cleared. The maximum PWM resolution (bits) for a given PWM frequency is given by the formula: FOSC log( FPWM ) Resolution = bits log() Note: If the PWM duty cycle value is longer than the PWM period, the CCP pin will not be cleared. 00 Microchip Technology Inc. DS309C-page 6

49 PIC6F87X SETUP FOR PWM OPERATION The following steps should be taken when configuring the CCP module for PWM operation:. Set the PWM period by writing to the PR register.. Set the PWM duty cycle by writing to the CCPRL register and CCPCON<5:4> bits. 3. Make the CCP pin an output by clearing the TRISC<> bit. 4. Set the TMR prescale value and enable Timer by writing to TCON. 5. Configure the CCP module for PWM operation. TABLE 8-3: EXAMPLE PWM FREQUENCIES AND RESOLUTIONS AT 0 MHz PWM Frequency. khz 4.88 khz 9.53 khz 78.kHz 56.3 khz 08.3 khz Timer Prescaler (, 4, 6) 6 4 PR Value 0xFFh 0xFFh 0xFFh 0x3Fh 0xFh 0x7h Maximum Resolution (bits) TABLE 8-4: REGISTERS ASSOCIATED WITH CAPTURE, COMPARE, AND TIMER Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 Value on: POR, BOR Value on all other RESETS 0Bh,8Bh, 0Bh, 8Bh INTCON GIE PEIE T0IE INTE RBIE T0IF INTF RBIF x u 0Ch PIR PSPIF () ADIF RCIF TXIF SSPIF CCPIF TMRIF TMRIF Dh PIR CCPIF Ch PIE PSPIE () ADIE RCIE TXIE SSPIE CCPIE TMRIE TMRIE Dh PIE CCPIE h TRISC PORTC Data Direction Register 0Eh TMRL Holding Register for the Least Significant Byte of the 6-bit TMR Register xxxx xxxx uuuu uuuu 0Fh TMRH Holding Register for the Most Significant Byte of the 6-bit TMR Register xxxx xxxx uuuu uuuu 0h TCON TCKPS TCKPS0 TOSCEN TSYNC TMRCS TMRON uu uuuu 5h CCPRL Capture/Compare/PWM Register (LSB) xxxx xxxx uuuu uuuu 6h CCPRH Capture/Compare/PWM Register (MSB) xxxx xxxx uuuu uuuu 7h CCPCON CCPX CCPY CCPM3 CCPM CCPM CCPM Bh CCPRL Capture/Compare/PWM Register (LSB) xxxx xxxx uuuu uuuu Ch CCPRH Capture/Compare/PWM Register (MSB) xxxx xxxx uuuu uuuu Dh CCPCON CCPX CCPY CCPM3 CCPM CCPM CCPM Legend: x = unknown, u = unchanged, - = unimplemented, read as '0'. Shaded cells are not used by Capture and Timer. Note : The PSP is not implemented on the PIC6F873/876; always maintain these bits clear. DS309C-page 6 00 Microchip Technology Inc.

50 PIC6F87X TABLE 8-5: REGISTERS ASSOCIATED WITH PWM AND TIMER Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 Value on: POR, BOR Value on all other RESETS 0Bh,8Bh, INTCON GIE PEIE T0IE INTE RBIE T0IF INTF RBIF x u 0Bh, 8Bh 0Ch PIR PSPIF () ADIF RCIF TXIF SSPIF CCPIF TMRIF TMRIF Dh PIR CCPIF Ch PIE PSPIE () ADIE RCIE TXIE SSPIE CCPIE TMRIE TMRIE Dh PIE CCPIE h TRISC PORTC Data Direction Register h TMR Timer Module s Register h PR Timer Module s Period Register h TCON TOUTPS3 TOUTPS TOUTPS TOUTPS0 TMRON TCKPS TCKPS h CCPRL Capture/Compare/PWM Register (LSB) xxxx xxxx uuuu uuuu 6h CCPRH Capture/Compare/PWM Register (MSB) xxxx xxxx uuuu uuuu 7h CCPCON CCPX CCPY CCPM3 CCPM CCPM CCPM Bh CCPRL Capture/Compare/PWM Register (LSB) xxxx xxxx uuuu uuuu Ch CCPRH Capture/Compare/PWM Register (MSB) xxxx xxxx uuuu uuuu Dh CCPCON CCPX CCPY CCPM3 CCPM CCPM CCPM Legend: x = unknown, u = unchanged, - = unimplemented, read as '0'. Shaded cells are not used by PWM and Timer. Note : Bits PSPIE and PSPIF are reserved on the PIC6F873/876; always maintain these bits clear. 00 Microchip Technology Inc. DS309C-page 63

51 PIC6F87X 0.0 ADDRESSABLE UNIVERSAL SYNCHRONOUS ASYNCHRONOUS RECEIVER TRANSMITTER (USART) The Universal Synchronous Asynchronous Receiver Transmitter (USART) module is one of the two serial I/O modules. (USART is also known as a Serial Communications Interface or SCI.) The USART can be configured as a full duplex asynchronous system that can communicate with peripheral devices such as CRT terminals and personal computers, or it can be configured as a half duplex synchronous system that can communicate with peripheral devices such as A/D or D/A integrated circuits, serial EEPROMs etc. The USART can be configured in the following modes: Asynchronous (full duplex) Synchronous - Master (half duplex) Synchronous - Slave (half duplex) Bit SPEN (RCSTA<7>) and bits TRISC<7:6> have to be set in order to configure pins RC6/TX/CK and RC7/RX/DT as the Universal Synchronous Asynchronous Receiver Transmitter. The USART module also has a multi-processor communication capability using 9-bit address detection. REGISTER 0-: TXSTA: TRANSMIT STATUS AND CONTROL REGISTER (ADDRESS 98h) R/W-0 R/W-0 R/W-0 R/W-0 U-0 R/W-0 R- R/W-0 CSRC TX9 TXEN SYNC BRGH TRMT TX9D bit 7 bit 0 bit 7 CSRC: Clock Source Select bit Asynchronous mode: Don t care Synchronous mode: = Master mode (clock generated internally from BRG) 0 = Slave mode (clock from external source) bit 6 TX9: 9-bit Transmit Enable bit = Selects 9-bit transmission 0 = Selects 8-bit transmission bit 5 TXEN: Transmit Enable bit = Transmit enabled 0 = Transmit disabled Note: SREN/CREN overrides TXEN in SYNC mode. bit 4 SYNC: USART Mode Select bit = Synchronous mode 0 = Asynchronous mode bit 3 Unimplemented: Read as '0' bit BRGH: High Baud Rate Select bit Asynchronous mode: = High speed 0 = Low speed Synchronous mode: Unused in this mode bit TRMT: Transmit Shift Register Status bit = TSR empty 0 = TSR full bit 0 TX9D: 9th bit of Transmit Data, can be parity bit Legend: R = Readable bit W = Writable bit U = Unimplemented bit, read as 0 - n = Value at POR = Bit is set 0 = Bit is cleared x = Bit is unknown 00 Microchip Technology Inc. DS309C-page 95

52 PIC6F87X REGISTER 0-: RCSTA: RECEIVE STATUS AND CONTROL REGISTER (ADDRESS 8h) R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R-0 R-0 R-x SPEN RX9 SREN CREN ADDEN FERR OERR RX9D bit 7 bit 0 bit 7 bit 6 bit 5 bit 4 bit 3 SPEN: Serial Port Enable bit = Serial port enabled (configures RC7/RX/DT and RC6/TX/CK pins as serial port pins) 0 = Serial port disabled RX9: 9-bit Receive Enable bit = Selects 9-bit reception 0 = Selects 8-bit reception SREN: Single Receive Enable bit Asynchronous mode: Don t care Synchronous mode - master: = Enables single receive 0 = Disables single receive This bit is cleared after reception is complete. Synchronous mode - slave: Don t care CREN: Continuous Receive Enable bit Asynchronous mode: = Enables continuous receive 0 = Disables continuous receive Synchronous mode: = Enables continuous receive until enable bit CREN is cleared (CREN overrides SREN) 0 = Disables continuous receive ADDEN: Address Detect Enable bit Asynchronous mode 9-bit (RX9 = ): = Enables address detection, enables interrupt and load of the receive buffer when RSR<8> is set 0 = Disables address detection, all bytes are received, and ninth bit can be used as parity bit bit FERR: Framing Error bit = Framing error (can be updated by reading RCREG register and receive next valid byte) 0 = No framing error bit OERR: Overrun Error bit = Overrun error (can be cleared by clearing bit CREN) 0 = No overrun error bit 0 RX9D: 9th bit of Received Data (can be parity bit, but must be calculated by user firmware) Legend: R = Readable bit W = Writable bit U = Unimplemented bit, read as 0 - n = Value at POR = Bit is set 0 = Bit is cleared x = Bit is unknown DS309C-page Microchip Technology Inc.

53 PIC6F87X 0. USART Baud Rate Generator (BRG) The BRG supports both the Asynchronous and Synchronous modes of the USART. It is a dedicated 8-bit baud rate generator. The SPBRG register controls the period of a free running 8-bit timer. In Asynchronous mode, bit BRGH (TXSTA<>) also controls the baud rate. In Synchronous mode, bit BRGH is ignored. Table 0- shows the formula for computation of the baud rate for different USART modes which only apply in Master mode (internal clock). Given the desired baud rate and FOSC, the nearest integer value for the SPBRG register can be calculated using the formula in Table 0-. From this, the error in baud rate can be determined. It may be advantageous to use the high baud rate (BRGH = ), even for slower baud clocks. This is because the FOSC/(6(X + )) equation can reduce the baud rate error in some cases. Writing a new value to the SPBRG register causes the BRG timer to be reset (or cleared). This ensures the BRG does not wait for a timer overflow before outputting the new baud rate. 0.. SAMPLING The data on the RC7/RX/DT pin is sampled three times by a majority detect circuit to determine if a high or a low level is present at the RX pin. TABLE 0-: BAUD RATE FORMULA SYNC BRGH = 0 (Low Speed) BRGH = (High Speed) 0 X = value in SPBRG (0 to 55) (Asynchronous) Baud Rate = FOSC/(64(X+)) (Synchronous) Baud Rate = FOSC/(4(X+)) Baud Rate = FOSC/(6(X+)) N/A TABLE 0-: REGISTERS ASSOCIATED WITH BAUD RATE GENERATOR Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 Value on: POR, BOR Value on all other RESETS 98h TXSTA CSRC TX9 TXEN SYNC BRGH TRMT TX9D h RCSTA SPEN RX9 SREN CREN ADDEN FERR OERR RX9D x x 99h SPBRG Baud Rate Generator Register Legend: x = unknown, - = unimplemented, read as '0'. Shaded cells are not used by the BRG. 00 Microchip Technology Inc. DS309C-page 97

54 PIC6F87X TABLE 0-3: BAUD RATES FOR ASYNCHRONOUS MODE (BRGH = 0) BAUD RATE (K) KBAUD FOSC = 0 MHz FOSC = 6 MHz FOSC = 0 MHz % ERROR SPBRG value (decimal) KBAUD % ERROR SPBRG value (decimal) KBAUD % ERROR SPBRG value (decimal) HIGH LOW FOSC = 4 MHz FOSC = MHz BAUD RATE SPBRG SPBRG % % (K) value value ERROR ERROR KBAUD (decimal) KBAUD (decimal) HIGH LOW TABLE 0-4: BAUD RATES FOR ASYNCHRONOUS MODE (BRGH = ) BAUD RATE (K) KBAUD FOSC = 0 MHz FOSC = 6 MHz FOSC = 0 MHz % ERROR SPBRG value (decimal) KBAUD % ERROR SPBRG value (decimal) KBAUD % ERROR SPBRG value (decimal) HIGH LOW FOSC = 4 MHz FOSC = MHz BAUD RATE SPBRG SPBRG % % (K) value value ERROR ERROR KBAUD (decimal) KBAUD (decimal) HIGH LOW DS309C-page Microchip Technology Inc.

55 PIC6F87X 0. USART Asynchronous Mode In this mode, the USART uses standard non-return-tozero (NRZ) format (one START bit, eight or nine data bits, and one STOP bit). The most common data format is 8-bits. An on-chip, dedicated, 8-bit baud rate generator can be used to derive standard baud rate frequencies from the oscillator. The USART transmits and receives the LSb first. The transmitter and receiver are functionally independent, but use the same data format and baud rate. The baud rate generator produces a clock, either x6 or x64 of the bit shift rate, depending on bit BRGH (TXSTA<>). Parity is not supported by the hardware, but can be implemented in software (and stored as the ninth data bit). Asynchronous mode is stopped during SLEEP. Asynchronous mode is selected by clearing bit SYNC (TXSTA<4>). The USART Asynchronous module consists of the following important elements: Baud Rate Generator Sampling Circuit Asynchronous Transmitter Asynchronous Receiver 0.. USART ASYNCHRONOUS TRANSMITTER The USART transmitter block diagram is shown in Figure 0-. The heart of the transmitter is the transmit (serial) shift register (TSR). The shift register obtains its data from the read/write transmit buffer, TXREG. The TXREG register is loaded with data in software. The TSR register is not loaded until the STOP bit has been transmitted from the previous load. As soon as the STOP bit is transmitted, the TSR is loaded with new data from the TXREG register (if available). Once the TXREG register transfers the data to the TSR register (occurs in one TCY), the TXREG register is empty and flag bit TXIF (PIR<4>) is set. This interrupt can be enabled/disabled by setting/clearing enable bit TXIE ( PIE<4>). Flag bit TXIF will be set, regardless of the state of enable bit TXIE and cannot be cleared in software. It will reset only when new data is loaded into the TXREG register. While flag bit TXIF indicates the status of the TXREG register, another bit TRMT (TXSTA<>) shows the status of the TSR register. Status bit TRMT is a read only bit, which is set when the TSR register is empty. No interrupt logic is tied to this bit, so the user has to poll this bit in order to determine if the TSR register is empty. Note : The TSR register is not mapped in data memory, so it is not available to the user. : Flag bit TXIF is set when enable bit TXEN is set. TXIF is cleared by loading TXREG. Transmission is enabled by setting enable bit TXEN (TXSTA<5>). The actual transmission will not occur until the TXREG register has been loaded with data and the baud rate generator (BRG) has produced a shift clock (Figure 0-). The transmission can also be started by first loading the TXREG register and then setting enable bit TXEN. Normally, when transmission is first started, the TSR register is empty. At that point, transfer to the TXREG register will result in an immediate transfer to TSR, resulting in an empty TXREG. A back-to-back transfer is thus possible (Figure 0-3). Clearing enable bit TXEN during a transmission will cause the transmission to be aborted and will reset the transmitter. As a result, the RC6/TX/CK pin will revert to hi-impedance. In order to select 9-bit transmission, transmit bit TX9 (TXSTA<6>) should be set and the ninth bit should be written to TX9D (TXSTA<0>). The ninth bit must be written before writing the 8-bit data to the TXREG register. This is because a data write to the TXREG register can result in an immediate transfer of the data to the TSR register (if the TSR is empty). In such a case, an incorrect ninth data bit may be loaded in the TSR register. FIGURE 0-: USART TRANSMIT BLOCK DIAGRAM Data Bus TXIE Interrupt TXIF TXREG Register 8 MSb LSb (8) 0 TSR Register Pin Buffer and Control RC6/TX/CK pin TXEN Baud Rate CLK TRMT SPEN SPBRG Baud Rate Generator TX9D TX9 00 Microchip Technology Inc. DS309C-page 99

56 PIC6F87X When setting up an Asynchronous Transmission, follow these steps:. Initialize the SPBRG register for the appropriate baud rate. If a high speed baud rate is desired, set bit BRGH (Section 0.).. Enable the asynchronous serial port by clearing bit SYNC and setting bit SPEN. 3. If interrupts are desired, then set enable bit TXIE. 4. If 9-bit transmission is desired, then set transmit bit TX9. 5. Enable the transmission by setting bit TXEN, which will also set bit TXIF. 6. If 9-bit transmission is selected, the ninth bit should be loaded in bit TX9D. 7. Load data to the TXREG register (starts transmission). 8. If using interrupts, ensure that GIE and PEIE (bits 7 and 6) of the INTCON register are set. FIGURE 0-: ASYNCHRONOUS MASTER TRANSMISSION Write to TXREG BRG Output (Shift Clock) RC6/TX/CK (pin) TXIF bit (Transmit Buffer Reg. Empty Flag) Word START Bit Bit 0 Bit Bit 7/8 Word STOP Bit TRMT bit (Transmit Shift Reg. Empty Flag) Word Transmit Shift Reg FIGURE 0-3: Write to TXREG BRG Output (Shift Clock) RC6/TX/CK (pin) TXIF bit (Interrupt Reg. Flag) TRMT bit (Transmit Shift Reg. Empty Flag) ASYNCHRONOUS MASTER TRANSMISSION (BACK TO BACK) Word Word START Bit Bit 0 Bit Bit 7/8 STOP Bit START Bit Bit 0 Word Word Word Word Transmit Shift Reg. Transmit Shift Reg. Note: This timing diagram shows two consecutive transmissions. TABLE 0-5: REGISTERS ASSOCIATED WITH ASYNCHRONOUS TRANSMISSION Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 0Bh, 8Bh, 0Bh,8Bh Value on: POR, BOR Value on all other RESETS INTCON GIE PEIE T0IE INTE RBIE T0IF INTF R0IF x u 0Ch PIR PSPIF () ADIF RCIF TXIF SSPIF CCPIF TMRIF TMRIF h RCSTA SPEN RX9 SREN CREN FERR OERR RX9D x x 9h TXREG USART Transmit Register Ch PIE PSPIE () ADIE RCIE TXIE SSPIE CCPIE TMRIE TMRIE h TXSTA CSRC TX9 TXEN SYNC BRGH TRMT TX9D h SPBRG Baud Rate Generator Register Legend: x = unknown, - = unimplemented locations read as '0'. Shaded cells are not used for asynchronous transmission. Note : Bits PSPIE and PSPIF are reserved on the PIC6F873/876; always maintain these bits clear. DS309C-page Microchip Technology Inc.

57 PIC6F87X 0.. USART ASYNCHRONOUS RECEIVER The receiver block diagram is shown in Figure 0-4. The data is received on the RC7/RX/DT pin and drives the data recovery block. The data recovery block is actually a high speed shifter, operating at x6 times the baud rate; whereas, the main receive serial shifter operates at the bit rate or at FOSC. Once Asynchronous mode is selected, reception is enabled by setting bit CREN (RCSTA<4>). The heart of the receiver is the receive (serial) shift register (RSR). After sampling the STOP bit, the received data in the RSR is transferred to the RCREG register (if it is empty). If the transfer is complete, flag bit RCIF (PIR<5>) is set. The actual interrupt can be enabled/ disabled by setting/clearing enable bit RCIE (PIE<5>). Flag bit RCIF is a read only bit, which is cleared by the hardware. It is cleared when the RCREG register has been read and is empty. The RCREG is a double buffered register (i.e., it is a two deep FIFO). It is possible for two bytes of data to be received and transferred to the RCREG FIFO and a third byte to begin shifting to the RSR register. On the detection of the STOP bit of the third byte, if the RCREG register is still full, the overrun error bit OERR (RCSTA<>) will be set. The word in the RSR will be lost. The RCREG register can be read twice to retrieve the two bytes in the FIFO. Overrun bit OERR has to be cleared in software. This is done by resetting the receive logic (CREN is cleared and then set). If bit OERR is set, transfers from the RSR register to the RCREG register are inhibited, and no further data will be received. It is therefore, essential to clear error bit OERR if it is set. Framing error bit FERR (RCSTA<>) is set if a STOP bit is detected as clear. Bit FERR and the 9th receive bit are buffered the same way as the receive data. Reading the RCREG will load bits RX9D and FERR with new values, therefore, it is essential for the user to read the RCSTA register before reading the RCREG register in order not to lose the old FERR and RX9D information. FIGURE 0-4: USART RECEIVE BLOCK DIAGRAM FOSC x64 Baud Rate CLK SPBRG Baud Rate Generator 64 or 6 CREN MSb STOP OERR FERR RSR Register LSb (8) 7 0 START RC7/RX/DT Pin Buffer and Control Data Recovery RX9 SPEN RX9D RCREG Register FIFO Interrupt RCIF RCIE 8 Data Bus 00 Microchip Technology Inc. DS309C-page 0

58 PIC6F87X FIGURE 0-5: ASYNCHRONOUS RECEPTION RX (pin) Rcv Shift Reg Rcv Buffer Reg Read Rcv Buffer Reg RCREG START bit START bit0 bit bit7/8 STOP bit bit0 bit Word RCREG bit7/8 Word RCREG STOP bit START bit bit7/8 STOP bit RCIF (Interrupt Flag) OERR bit CREN Note: This timing diagram shows three words appearing on the RX input. The RCREG (receive buffer) is read after the third word, causing the OERR (overrun) bit to be set. When setting up an Asynchronous Reception, follow these steps:. Initialize the SPBRG register for the appropriate baud rate. If a high speed baud rate is desired, set bit BRGH (Section 0.).. Enable the asynchronous serial port by clearing bit SYNC and setting bit SPEN. 3. If interrupts are desired, then set enable bit RCIE. 4. If 9-bit reception is desired, then set bit RX9. 5. Enable the reception by setting bit CREN. 6. Flag bit RCIF will be set when reception is complete and an interrupt will be generated if enable bit RCIE is set. 7. Read the RCSTA register to get the ninth bit (if enabled) and determine if any error occurred during reception. 8. Read the 8-bit received data by reading the RCREG register. 9. If any error occurred, clear the error by clearing enable bit CREN. 0. If using interrupts, ensure that GIE and PEIE (bits 7 and 6) of the INTCON register are set. TABLE 0-6: REGISTERS ASSOCIATED WITH ASYNCHRONOUS RECEPTION Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 Value on: POR, BOR Value on all other RESETS 0Bh, 8Bh, INTCON GIE PEIE T0IE INTE RBIE T0IF INTF R0IF x u 0Bh,8Bh 0Ch PIR PSPIF () ADIF RCIF TXIF SSPIF CCPIF TMRIF TMRIF h RCSTA SPEN RX9 SREN CREN FERR OERR RX9D x x Ah RCREG USART Receive Register Ch PIE PSPIE () ADIE RCIE TXIE SSPIE CCPIE TMRIE TMRIE h TXSTA CSRC TX9 TXEN SYNC BRGH TRMT TX9D h SPBRG Baud Rate Generator Register Legend: x = unknown, - = unimplemented locations read as '0'. Shaded cells are not used for asynchronous reception. Note : Bits PSPIE and PSPIF are reserved on PIC6F873/876 devices; always maintain these bits clear. DS309C-page 0 00 Microchip Technology Inc.

59 PIC6F87X.0 ANALOG-TO-DIGITAL CONVERTER (A/D) MODULE The Analog-to-Digital (A/D) Converter module has five inputs for the 8-pin devices and eight for the other devices. The analog input charges a sample and hold capacitor. The output of the sample and hold capacitor is the input into the converter. The converter then generates a digital result of this analog level via successive approximation. The A/D conversion of the analog input signal results in a corresponding 0-bit digital number. The A/D module has high and low voltage reference input that is software selectable to some combination of VDD, VSS, RA, or RA3. The A/D converter has a unique feature of being able to operate while the device is in SLEEP mode. To operate in SLEEP, the A/D clock must be derived from the A/D s internal RC oscillator. The A/D module has four registers. These registers are: A/D Result High Register (ADRESH) A/D Result Low Register (ADRESL) A/D Control Register0 (ADCON0) A/D Control Register (ADCON) The ADCON0 register, shown in Register -, controls the operation of the A/D module. The ADCON register, shown in Register -, configures the functions of the port pins. The port pins can be configured as analog inputs (RA3 can also be the voltage reference), or as digital I/O. Additional information on using the A/D module can be found in the PICmicro Mid-Range MCU Family Reference Manual (DS3303). REGISTER -: ADCON0 REGISTER (ADDRESS: Fh) R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 R/W-0 U-0 R/W-0 ADCS ADCS0 CHS CHS CHS0 GO/DONE ADON bit 7 bit 0 bit 7-6 bit 5-3 bit bit bit 0 ADCS:ADCS0: A/D Conversion Clock Select bits 00 = FOSC/ 0 = FOSC/8 0 = FOSC/3 = FRC (clock derived from the internal A/D module RC oscillator) CHS:CHS0: Analog Channel Select bits 000 = channel 0, (RA0/AN0) 00 = channel, (RA/AN) 00 = channel, (RA/AN) 0 = channel 3, (RA3/AN3) 00 = channel 4, (RA5/AN4) 0 = channel 5, (RE0/AN5) () 0 = channel 6, (RE/AN6) () = channel 7, (RE/AN7) () GO/DONE: A/D Conversion Status bit If ADON = : = A/D conversion in progress (setting this bit starts the A/D conversion) 0 = A/D conversion not in progress (this bit is automatically cleared by hardware when the A/D conversion is complete) Unimplemented: Read as '0' ADON: A/D On bit = A/D converter module is operating 0 = A/D converter module is shut-off and consumes no operating current Note : These channels are not available on PIC6F873/876 devices. Legend: R = Readable bit W = Writable bit U = Unimplemented bit, read as 0 - n = Value at POR = Bit is set 0 = Bit is cleared x = Bit is unknown 00 Microchip Technology Inc. DS309C-page

60 PIC6F87X REGISTER -: ADCON REGISTER (ADDRESS 9Fh) U-0 U-0 R/W-0 U-0 R/W-0 R/W-0 R/W-0 R/W-0 ADFM PCFG3 PCFG PCFG PCFG0 bit 7 bit 0 bit 7 bit 6-4 bit 3-0 ADFM: A/D Result Format Select bit = Right justified. 6 Most Significant bits of ADRESH are read as 0. 0 = Left justified. 6 Least Significant bits of ADRESL are read as 0. Unimplemented: Read as '0' PCFG3:PCFG0: A/D Port Configuration Control bits: PCFG3: PCFG0 AN7 () RE A = Analog input AN6 () RE AN5 () RE0 D = Digital I/O AN4 RA5 AN3 RA3 AN RA AN RA AN0 RA0 VREF+ VREF- CHAN/ Refs () 0000 A A A A A A A A VDD VSS 8/0 000 A A A A VREF+ A A A RA3 VSS 7/ 000 D D D A A A A A VDD VSS 5/0 00 D D D A VREF+ A A A RA3 VSS 4/ 000 D D D D A D A A VDD VSS 3/0 00 D D D D VREF+ D A A RA3 VSS / 0x D D D D D D D D VDD VSS 0/0 000 A A A A VREF+ VREF- A A RA3 RA 6/ 00 D D A A A A A A VDD VSS 6/0 00 D D A A VREF+ A A A RA3 VSS 5/ 0 D D A A VREF+ VREF- A A RA3 RA 4/ 00 D D D A VREF+ VREF- A A RA3 RA 3/ 0 D D D D VREF+ VREF- A A RA3 RA / 0 D D D D D D D A VDD VSS /0 D D D D VREF+ VREF- D A RA3 RA / Note : These channels are not available on PIC6F873/876 devices. : This column indicates the number of analog channels available as A/D inputs and the number of analog channels used as voltage reference inputs. Legend: R = Readable bit W = Writable bit U = Unimplemented bit, read as 0 - n = Value at POR = Bit is set 0 = Bit is cleared x = Bit is unknown The ADRESH:ADRESL registers contain the 0-bit result of the A/D conversion. When the A/D conversion is complete, the result is loaded into this A/D result register pair, the GO/DONE bit (ADCON0<>) is cleared and the A/D interrupt flag bit ADIF is set. The block diagram of the A/D module is shown in Figure -. After the A/D module has been configured as desired, the selected channel must be acquired before the conversion is started. The analog input channels must have their corresponding TRIS bits selected as inputs. To determine sample time, see Section.. After this acquisition time has elapsed, the A/D conversion can be started. DS309C-page 00 Microchip Technology Inc.

61 PIC6F87X These steps should be followed for doing an A/D Conversion:. Configure the A/D module: Configure analog pins/voltage reference and digital I/O (ADCON) Select A/D input channel (ADCON0) Select A/D conversion clock (ADCON0) Turn on A/D module (ADCON0). Configure A/D interrupt (if desired): Clear ADIF bit Set ADIE bit Set PEIE bit Set GIE bit 3. Wait the required acquisition time. 4. Start conversion: Set GO/DONE bit (ADCON0) 5. Wait for A/D conversion to complete, by either: Polling for the GO/DONE bit to be cleared (with interrupts enabled); OR Waiting for the A/D interrupt 6. Read A/D result register pair (ADRESH:ADRESL), clear bit ADIF if required. 7. For the next conversion, go to step or step, as required. The A/D conversion time per bit is defined as TAD. A minimum wait of TAD is required before the next acquisition starts. FIGURE -: A/D BLOCK DIAGRAM CHS:CHS0 VAIN (Input Voltage) RE/AN7 () RE/AN6 () RE0/AN5 () RA5/AN4 RA3/AN3/VREF+ A/D Converter RA/AN VDD 000 RA0/AN0 VREF+ (Reference Voltage) PCFG3:PCFG0 RA/AN/VREF- VREF- (Reference Voltage) VSS PCFG3:PCFG0 Note : Not available on PIC6F873/876 devices. 00 Microchip Technology Inc. DS309C-page 3

62 PIC6F87X. A/D Acquisition Requirements For the A/D converter to meet its specified accuracy, the charge holding capacitor (CHOLD) must be allowed to fully charge to the input channel voltage level. The analog input model is shown in Figure -. The source impedance (RS) and the internal sampling switch (RSS) impedance directly affect the time required to charge the capacitor CHOLD. The sampling switch (RSS) impedance varies over the device voltage (VDD), see Figure -. The maximum recommended impedance for analog sources is 0 kω. As the impedance is decreased, the acquisition time may be decreased. After the analog input channel is selected (changed), this acquisition must be done before the conversion can be started. To calculate the minimum acquisition time, Equation - may be used. This equation assumes that / LSb error is used (04 steps for the A/D). The / LSb error is the maximum error allowed for the A/D to meet its specified resolution. To calculate the minimum acquisition time, TACQ, see the PICmicro Mid-Range Reference Manual (DS3303). EQUATION -: ACQUISITION TIME TACQ = Amplifier Settling Time + Hold Capacitor Charging Time + Temperature Coefficient TC TACQ = = = = = = = TAMP + TC + TCOFF µs + TC + [(Temperature -5 C)(0.05µs/ C)] CHOLD (RIC + RSS + RS) In(/047) - 0pF (kω + 7kΩ + 0kΩ) In( ) 6.47µs µs µs + [(50 C -5 C)(0.05µs/ C) 9.7µs Note : The reference voltage (VREF) has no effect on the equation, since it cancels itself out. : The charge holding capacitor (CHOLD) is not discharged after each conversion. 3: The maximum recommended impedance for analog sources is 0 kω. This is required to meet the pin leakage specification. 4: After a conversion has completed, a.0tad delay must complete before acquisition can begin again. During this time, the holding capacitor is not connected to the selected A/D input channel. FIGURE -: ANALOG INPUT MODEL RS ANx VDD VT = 0.6V RIC k Sampling Switch SS RSS VA CPIN 5 pf VT = 0.6V I LEAKAGE ± 500 na CHOLD = DAC capacitance = 0 pf VSS Legend CPIN VT I LEAKAGE RIC SS CHOLD = input capacitance = threshold voltage = leakage current at the pin due to various junctions = interconnect resistance = sampling switch = sample/hold capacitance (from DAC) 6V 5V VDD 4V 3V V Sampling Switch (kω) DS309C-page 4 00 Microchip Technology Inc.

63 PIC6F87X. Selecting the A/D Conversion Clock The A/D conversion time per bit is defined as TAD. The A/D conversion requires a minimum TAD per 0-bit conversion. The source of the A/D conversion clock is software selected. The four possible options for TAD are: For correct A/D conversions, the A/D conversion clock (TAD) must be selected to ensure a minimum TAD time of.6 µs. Table - shows the resultant TAD times derived from the device operating frequencies and the A/D clock source selected. TOSC 8TOSC 3TOSC Internal A/D module RC oscillator (-6 µs) TABLE -: TAD vs. MAXIMUM DEVICE OPERATING FREQUENCIES (STANDARD DEVICES (C)) AD Clock Source (TAD) Maximum Device Frequency Operation ADCS:ADCS0 Max. TOSC 00.5 MHz 8TOSC 0 5 MHz 3TOSC 0 0 MHz RC (,, 3) (Note ) Note : The RC source has a typical TAD time of 4 µs, but can vary between -6 µs. : When the device frequencies are greater than MHz, the RC A/D conversion clock source is only recommended for SLEEP operation. 3: For extended voltage devices (LC), please refer to the Electrical Characteristics (Sections 5. and 5.)..3 Configuring Analog Port Pins The ADCON and TRIS registers control the operation of the A/D port pins. The port pins that are desired as analog inputs must have their corresponding TRIS bits set (input). If the TRIS bit is cleared (output), the digital output level (VOH or VOL) will be converted. The A/D operation is independent of the state of the CHS:CHS0 bits and the TRIS bits. Note : When reading the port register, any pin configured as an analog input channel will read as cleared (a low level). Pins configured as digital inputs will convert an analog input. Analog levels on a digitally configured input will not affect the conversion accuracy. : Analog levels on any pin that is defined as a digital input (including the AN7:AN0 pins), may cause the input buffer to consume current that is out of the device specifications. 00 Microchip Technology Inc. DS309C-page 5

64 PIC6F87X.4 A/D Conversions Clearing the GO/DONE bit during a conversion will abort the current conversion. The A/D result register pair will NOT be updated with the partially completed A/D conversion sample. That is, the ADRESH:ADRESL registers will continue to contain the value of the last completed conversion (or the last value written to the ADRESH:ADRESL registers). After the A/D conversion is aborted, a TAD wait is required before the next acquisition is started. After this TAD wait, acquisition on the selected channel is automatically started. The GO/DONE bit can then be set to start the conversion. In Figure -3, after the GO bit is set, the first time segment has a minimum of TCY and a maximum of TAD. Note: The GO/DONE bit should NOT be set in the same instruction that turns on the A/D. FIGURE -3: TCY to TAD A/D CONVERSION TAD CYCLES TAD TAD TAD3 TAD4 TAD5 TAD6 TAD7 TAD8 TAD9 b9 b8 b7 b6 b5 b4 b3 b TAD0 TAD b b0 Conversion starts Holding capacitor is disconnected from analog input (typically 00 ns) Set GO bit ADRES is loaded GO bit is cleared ADIF bit is set Holding capacitor is connected to analog input.4. A/D RESULT REGISTERS The ADRESH:ADRESL register pair is the location where the 0-bit A/D result is loaded at the completion of the A/D conversion. This register pair is 6-bits wide. The A/D module gives the flexibility to left or right justify the 0-bit result in the 6-bit result register. The A/D Format Select bit (ADFM) controls this justification. Figure -4 shows the operation of the A/D result justification. The extra bits are loaded with 0 s. When an A/D result will not overwrite these locations (A/D disable), these registers may be used as two general purpose 8-bit registers. FIGURE -4: A/D RESULT JUSTIFICATION 0-bit Result ADFM = ADFM = ADRESH ADRESL ADRESH ADRESL 0-bit Result 0-bit Result Right Justified Left Justified DS309C-page 6 00 Microchip Technology Inc.

65 PIC6F87X.5 A/D Operation During SLEEP The A/D module can operate during SLEEP mode. This requires that the A/D clock source be set to RC (ADCS:ADCS0 = ). When the RC clock source is selected, the A/D module waits one instruction cycle before starting the conversion. This allows the SLEEP instruction to be executed, which eliminates all digital switching noise from the conversion. When the conversion is completed, the GO/DONE bit will be cleared and the result loaded into the ADRES register. If the A/D interrupt is enabled, the device will wake-up from SLEEP. If the A/D interrupt is not enabled, the A/D module will then be turned off, although the ADON bit will remain set. When the A/D clock source is another clock option (not RC), a SLEEP instruction will cause the present conversion to be aborted and the A/D module to be turned off, though the ADON bit will remain set. Turning off the A/D places the A/D module in its lowest current consumption state. Note: For the A/D module to operate in SLEEP, the A/D clock source must be set to RC (ADCS:ADCS0 = ). To allow the conversion to occur during SLEEP, ensure the SLEEP instruction immediately follows the instruction that sets the GO/DONE bit..6 Effects of a RESET A device RESET forces all registers to their RESET state. This forces the A/D module to be turned off, and any conversion is aborted. All A/D input pins are configured as analog inputs. The value that is in the ADRESH:ADRESL registers is not modified for a Power-on Reset. The ADRESH:ADRESL registers will contain unknown data after a Power-on Reset. TABLE -: REGISTERS/BITS ASSOCIATED WITH A/D Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 0Bh,8Bh, 0Bh,8Bh Value on POR, BOR Value on MCLR, WDT INTCON GIE PEIE T0IE INTE RBIE T0IF INTF RBIF x u 0Ch PIR PSPIF () ADIF RCIF TXIF SSPIF CCPIF TMRIF TMRIF Ch PIE PSPIE () ADIE RCIE TXIE SSPIE CCPIE TMRIE TMRIE Eh ADRESH A/D Result Register High Byte xxxx xxxx uuuu uuuu 9Eh ADRESL A/D Result Register Low Byte xxxx xxxx uuuu uuuu Fh ADCON0 ADCS ADCS0 CHS CHS CHS0 GO/DONE ADON Fh ADCON ADFM PCFG3 PCFG PCFG PCFG h TRISA PORTA Data Direction Register h PORTA PORTA Data Latch when written: PORTA pins when read --0x u h () TRISE IBF OBF IBOV PSPMODE PORTE Data Direction bits h () PORTE RE RE RE xxx uuu Legend: x = unknown, u = unchanged, - = unimplemented, read as '0'. Shaded cells are not used for A/D conversion. Note : These registers/bits are not available on the 8-pin devices. 00 Microchip Technology Inc. DS309C-page 7

66 PIC6F87X.0 Interrupts The PIC6F87X family has up to 4 sources of interrupt. The interrupt control register (INTCON) records individual interrupt requests in flag bits. It also has individual and global interrupt enable bits. Note: Individual interrupt flag bits are set, regardless of the status of their corresponding mask bit, or the GIE bit. A global interrupt enable bit, GIE (INTCON<7>) enables (if set) all unmasked interrupts, or disables (if cleared) all interrupts. When bit GIE is enabled, and an interrupt s flag bit and mask bit are set, the interrupt will vector immediately. Individual interrupts can be disabled through their corresponding enable bits in various registers. Individual interrupt bits are set, regardless of the status of the GIE bit. The GIE bit is cleared on RESET. The return from interrupt instruction, RETFIE, exits the interrupt routine, as well as sets the GIE bit, which re-enables interrupts. The RB0/INT pin interrupt, the RB port change interrupt, and the TMR0 overflow interrupt flags are contained in the INTCON register. The peripheral interrupt flags are contained in the special function registers, PIR and PIR. The corresponding interrupt enable bits are contained in special function registers, PIE and PIE, and the peripheral interrupt enable bit is contained in special function register INTCON. When an interrupt is responded to, the GIE bit is cleared to disable any further interrupt, the return address is pushed onto the stack and the PC is loaded with 0004h. Once in the Interrupt Service Routine, the source(s) of the interrupt can be determined by polling the interrupt flag bits. The interrupt flag bit(s) must be cleared in software before re-enabling interrupts to avoid recursive interrupts. For external interrupt events, such as the INT pin or PORTB change interrupt, the interrupt latency will be three or four instruction cycles. The exact latency depends when the interrupt event occurs. The latency is the same for one or two-cycle instructions. Individual interrupt flag bits are set, regardless of the status of their corresponding mask bit, PEIE bit, or GIE bit. FIGURE -9: INTERRUPT LOGIC EEIF EEIE PSPIF PSPIE ADIF ADIE T0IF T0IE Wake-up (If in SLEEP mode) CCPIF CCPIE BCLIF BCLIE RCIF RCIE TXIF TXIE SSPIF SSPIE CCPIF CCPIE TMRIF TMRIE TMRIF TMRIE INTF INTE RBIF RBIE PEIE GIE Interrupt to CPU The following table shows which devices have which interrupts. Device T0IF INTF RBIF PSPIF ADIF RCIF TXIF SSPIF CCPIF TMRIF TMRIF EEIF BCLIF CCPIF PIC6F876/873 Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes PIC6F877/874 Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes 00 Microchip Technology Inc. DS309C-page 9

67 PIC6F87X.0. INT INTERRUPT External interrupt on the RB0/INT pin is edge triggered, either rising, if bit INTEDG (OPTION_REG<6>) is set, or falling, if the INTEDG bit is clear. When a valid edge appears on the RB0/INT pin, flag bit INTF (INTCON<>) is set. This interrupt can be disabled by clearing enable bit INTE (INTCON<4>). Flag bit INTF must be cleared in software in the Interrupt Service Routine before re-enabling this interrupt. The INT interrupt can wake-up the processor from SLEEP, if bit INTE was set prior to going into SLEEP. The status of global interrupt enable bit, GIE, decides whether or not the processor branches to the interrupt vector following wake-up. See Section.3 for details on SLEEP mode..0. TMR0 INTERRUPT An overflow (FFh 00h) in the TMR0 register will set flag bit T0IF (INTCON<>). The interrupt can be enabled/disabled by setting/clearing enable bit T0IE (INTCON<5>) (Section 5.0).. Context Saving During Interrupts During an interrupt, only the return PC value is saved on the stack. Typically, users may wish to save key registers during an interrupt, (i.e., W register and STATUS register). This will have to be implemented in software. For the PIC6F873/874 devices, the register W_TEMP must be defined in both banks 0 and and must be defined at the same offset from the bank base address (i.e., If W_TEMP is defined at 0x0 in bank 0, it must also be defined at 0xA0 in bank ). The registers, PCLATH_TEMP and STATUS_TEMP, are only defined in bank 0. Since the upper 6 bytes of each bank are common in the PIC6F876/877 devices, temporary holding registers W_TEMP, STATUS_TEMP, and PCLATH_TEMP should be placed in here. These 6 locations don t require banking and therefore, make it easier for context save and restore. The same code shown in Example - can be used..0.3 PORTB INTCON CHANGE An input change on PORTB<7:4> sets flag bit RBIF (INTCON<0>). The interrupt can be enabled/disabled by setting/clearing enable bit RBIE (INTCON<4>) (Section 3.). EXAMPLE -: SAVING STATUS, W, AND PCLATH REGISTERS IN RAM MOVWF W_TEMP ;Copy W to TEMP register SWAPF STATUS,W ;Swap status to be saved into W CLRF STATUS ;bank 0, regardless of current bank, Clears IRP,RP,RP0 MOVWF STATUS_TEMP ;Save status to bank zero STATUS_TEMP register MOVF PCLATH, W ;Only required if using pages, and/or 3 MOVWF PCLATH_TEMP ;Save PCLATH into W CLRF PCLATH ;Page zero, regardless of current page : :(ISR) ;(Insert user code here) : MOVF PCLATH_TEMP, W ;Restore PCLATH MOVWF PCLATH ;Move W into PCLATH SWAPF STATUS_TEMP,W ;Swap STATUS_TEMP register into W ;(sets bank to original state) MOVWF STATUS ;Move W into STATUS register SWAPF W_TEMP,F ;Swap W_TEMP SWAPF W_TEMP,W ;Swap W_TEMP into W DS309C-page Microchip Technology Inc.

68 PIC6F87X. Watchdog Timer (WDT) The Watchdog Timer is a free running on-chip RC oscillator which does not require any external components. This RC oscillator is separate from the RC oscillator of the OSC/CLKIN pin. That means that the WDT will run, even if the clock on the OSC/CLKIN and OSC/ CLKOUT pins of the device has been stopped, for example, by execution of a SLEEP instruction. During normal operation, a WDT time-out generates a device RESET (Watchdog Timer Reset). If the device is in SLEEP mode, a WDT time-out causes the device to wake-up and continue with normal operation (Watchdog Timer Wake-up). The TO bit in the STATUS register will be cleared upon a Watchdog Timer time-out. The WDT can be permanently disabled by clearing configuration bit WDTE (Section.). WDT time-out period values may be found in the Electrical Specifications section under parameter #3. Values for the WDT prescaler (actually a postscaler, but shared with the Timer0 prescaler) may be assigned using the OPTION_REG register. Note : The CLRWDT and SLEEP instructions clear the WDT and the postscaler, if assigned to the WDT, and prevent it from timing out and generating a device RESET condition. : When a CLRWDT instruction is executed and the prescaler is assigned to the WDT, the prescaler count will be cleared, but the prescaler assignment is not changed. FIGURE -0: WATCHDOG TIMER BLOCK DIAGRAM From TMR0 Clock Source (Figure 5-) WDT Timer 0 M U X Postscaler to - MUX PS:PS0 WDT Enable Bit PSA To TMR0 (Figure 5-) 0 MUX PSA WDT Time-out Note: PSA and PS:PS0 are bits in the OPTION_REG register. TABLE -7: SUMMARY OF WATCHDOG TIMER REGISTERS Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit Bit Bit 0 007h Config. bits () BODEN () CP CP0 PWRTE () WDTE FOSC FOSC0 8h,8h OPTION_REG RBPU INTEDG T0CS T0SE PSA PS PS PS0 Legend: Shaded cells are not used by the Watchdog Timer. Note : See Register - for operation of these bits. 00 Microchip Technology Inc. DS309C-page 3

69 PIC6F87X.3 Power-down Mode (SLEEP) Power-down mode is entered by executing a SLEEP instruction. If enabled, the Watchdog Timer will be cleared but keeps running, the PD bit (STATUS<3>) is cleared, the TO (STATUS<4>) bit is set, and the oscillator driver is turned off. The I/O ports maintain the status they had before the SLEEP instruction was executed (driving high, low, or hi-impedance). For lowest current consumption in this mode, place all I/O pins at either VDD or VSS, ensure no external circuitry is drawing current from the I/O pin, power-down the A/D and disable external clocks. Pull all I/O pins that are hi-impedance inputs, high or low externally, to avoid switching currents caused by floating inputs. The T0CKI input should also be at VDD or VSS for lowest current consumption. The contribution from on-chip pull-ups on PORTB should also be considered. The MCLR pin must be at a logic high level (VIHMC)..3. WAKE-UP FROM SLEEP The device can wake-up from SLEEP through one of the following events:. External RESET input on MCLR pin.. Watchdog Timer Wake-up (if WDT was enabled). 3. Interrupt from INT pin, RB port change or peripheral interrupt. External MCLR Reset will cause a device RESET. All other events are considered a continuation of program execution and cause a wake-up. The TO and PD bits in the STATUS register can be used to determine the cause of device RESET. The PD bit, which is set on power-up, is cleared when SLEEP is invoked. The TO bit is cleared if a WDT time-out occurred and caused wake-up. The following peripheral interrupts can wake the device from SLEEP:. PSP read or write (PIC6F874/877 only).. TMR interrupt. Timer must be operating as an asynchronous counter. 3. CCP Capture mode interrupt. 4. Special event trigger (Timer in Asynchronous mode using an external clock). 5. SSP (START/STOP) bit detect interrupt. 6. SSP transmit or receive in Slave mode (SPI/I C). 7. USART RX or TX (Synchronous Slave mode). 8. A/D conversion (when A/D clock source is RC). 9. EEPROM write operation completion Other peripherals cannot generate interrupts since during SLEEP, no on-chip clocks are present. When the SLEEP instruction is being executed, the next instruction (PC + ) is pre-fetched. For the device to wake-up through an interrupt event, the corresponding interrupt enable bit must be set (enabled). Wake-up is regardless of the state of the GIE bit. If the GIE bit is clear (disabled), the device continues execution at the instruction after the SLEEP instruction. If the GIE bit is set (enabled), the device executes the instruction after the SLEEP instruction and then branches to the interrupt address (0004h). In cases where the execution of the instruction following SLEEP is not desirable, the user should have a NOP after the SLEEP instruction..3. WAKE-UP USING INTERRUPTS When global interrupts are disabled (GIE cleared) and any interrupt source has both its interrupt enable bit and interrupt flag bit set, one of the following will occur: If the interrupt occurs before the execution of a SLEEP instruction, the SLEEP instruction will complete as a NOP. Therefore, the WDT and WDT postscaler will not be cleared, the TO bit will not be set and PD bits will not be cleared. If the interrupt occurs during or after the execution of a SLEEP instruction, the device will immediately wake-up from SLEEP. The SLEEP instruction will be completely executed before the wake-up. Therefore, the WDT and WDT postscaler will be cleared, the TO bit will be set and the PD bit will be cleared. Even if the flag bits were checked before executing a SLEEP instruction, it may be possible for flag bits to become set before the SLEEP instruction completes. To determine whether a SLEEP instruction executed, test the PD bit. If the PD bit is set, the SLEEP instruction was executed as a NOP. To ensure that the WDT is cleared, a CLRWDT instruction should be executed before a SLEEP instruction. DS309C-page 3 00 Microchip Technology Inc.

70 PIC6F87X FIGURE -: WAKE-UP FROM SLEEP THROUGH INTERRUPT Q Q Q3 Q4 Q Q Q3 Q4 Q Q Q Q3 Q4 Q Q Q3 Q4 Q Q Q3 Q4 Q Q Q3 Q4 OSC CLKOUT (4) TOST () INT pin INTF Flag (INTCON<>) Interrupt Latency () GIE bit (INTCON<7>) Processor in SLEEP INSTRUCTION FLOW PC PC PC+ PC+ Instruction Fetched Instruction Executed Inst(PC) = SLEEP Inst(PC - ) Inst(PC + ) SLEEP PC+ Inst(PC + ) Inst(PC + ) PC h 0005h Inst(0004h) Inst(0005h) Dummy cycle Dummy cycle Inst(0004h) Note : XT, HS or LP oscillator mode assumed. : TOST = 04TOSC (drawing not to scale) This delay will not be there for RC osc mode. 3: GIE = assumed. In this case, after wake- up, the processor jumps to the interrupt routine. If GIE = 0, execution will continue in-line. 4: CLKOUT is not available in these osc modes, but shown here for timing reference..4 In-Circuit Debugger When the DEBUG bit in the configuration word is programmed to a 0, the In-Circuit Debugger functionality is enabled. This function allows simple debugging functions when used with MPLAB ICD. When the microcontroller has this feature enabled, some of the resources are not available for general use. Table -8 shows which features are consumed by the background debugger. TABLE -8: I/O pins Stack Program Memory Data Memory DEBUGGER RESOURCES RB6, RB7 level Address 0000h must be NOP Last 00h words 0x070 (0x0F0, 0x70, 0xF0) 0xEB - 0xEF.5 Program Verification/Code Protection If the code protection bit(s) have not been programmed, the on-chip program memory can be read out for verification purposes..6 ID Locations Four memory locations (000h - 003h) are designated as ID locations, where the user can store checksum or other code identification numbers. These locations are not accessible during normal execution, but are readable and writable during program/verify. It is recommended that only the 4 Least Significant bits of the ID location are used. To use the In-Circuit Debugger function of the microcontroller, the design must implement In-Circuit Serial Programming connections to MCLR/VPP, VDD, GND, RB7 and RB6. This will interface to the In-Circuit Debugger module available from Microchip, or one of the third party development tool companies. 00 Microchip Technology Inc. DS309C-page 33

71 PIC6F87X 3.0 INSTRUCTION SET SUMMARY Each PIC6F87X instruction is a 4-bit word, divided into an OPCODE which specifies the instruction type and one or more operands which further specify the operation of the instruction. The PIC6F87X instruction set summary in Table 3- lists byte-oriented, bit-oriented, and literal and control operations. Table 3- shows the opcode field descriptions. For byte-oriented instructions, f represents a file register designator and d represents a destination designator. The file register designator specifies which file register is to be used by the instruction. The destination designator specifies where the result of the operation is to be placed. If d is zero, the result is placed in the W register. If d is one, the result is placed in the file register specified in the instruction. For bit-oriented instructions, b represents a bit field designator which selects the number of the bit affected by the operation, while f represents the address of the file in which the bit is located. For literal and control operations, k represents an eight or eleven bit constant or literal value. TABLE 3-: Field f W b k OPCODE FIELD DESCRIPTIONS Description Register file address (0x00 to 0x7F) Working register (accumulator) Bit address within an 8-bit file register Literal field, constant data or label x Don't care location (= 0 or ). The assembler will generate code with x = 0. It is the recommended form of use for compatibility with all Microchip software tools. d Destination select; d = 0: store result in W, d = : store result in file register f. Default is d =. PC TO PD Program Counter Time-out bit Power-down bit The instruction set is highly orthogonal and is grouped into three basic categories: Byte-oriented operations Bit-oriented operations Literal and control operations All instructions are executed within one single instruction cycle, unless a conditional test is true or the program counter is changed as a result of an instruction. In this case, the execution takes two instruction cycles with the second cycle executed as a NOP. One instruction cycle consists of four oscillator periods. Thus, for an oscillator frequency of 4 MHz, the normal instruction execution time is µs. If a conditional test is true, or the program counter is changed as a result of an instruction, the instruction execution time is µs. Table 3- lists the instructions recognized by the MPASM TM assembler. Figure 3- shows the general formats that the instructions can have. Note: All examples use the following format to represent a hexadecimal number: 0xhh where h signifies a hexadecimal digit. FIGURE 3-: To maintain upward compatibility with future PIC6F87X products, do not use the OPTION and TRIS instructions. GENERAL FORMAT FOR INSTRUCTIONS Byte-oriented file register operations OPCODE d f (FILE #) d = 0 for destination W d = for destination f f = 7-bit file register address Bit-oriented file register operations OPCODE b (BIT #) f (FILE #) b = 3-bit bit address f = 7-bit file register address Literal and control operations General OPCODE k (literal) k = 8-bit immediate value CALL and GOTO instructions only OPCODE k (literal) k = -bit immediate value A description of each instruction is available in the PICmicro Mid-Range Reference Manual, (DS3303). 00 Microchip Technology Inc. DS309C-page 35

72 PIC6F87X TABLE 3-: PIC6F87X INSTRUCTION SET Mnemonic, Operands Description Cycles MSb 4-Bit Opcode LSb Status Affected Notes ADDWF ANDWF CLRF CLRW COMF DECF DECFSZ INCF INCFSZ IORWF MOVF MOVWF NOP RLF RRF SUBWF SWAPF XORWF BCF BSF BTFSC BTFSS ADDLW ANDLW CALL CLRWDT GOTO IORLW MOVLW RETFIE RETLW RETURN SLEEP SUBLW XORLW f, d f, d f - f, d f, d f, d f, d f, d f, d f, d f - f, d f, d f, d f, d f, d f, b f, b f, b f, b k k k - k k k - k - - k k Add W and f AND W with f Clear f Clear W Complement f Decrement f Decrement f, Skip if 0 Increment f Increment f, Skip if 0 Inclusive OR W with f Move f Move W to f No Operation Rotate Left f through Carry Rotate Right f through Carry Subtract W from f Swap nibbles in f Exclusive OR W with f Bit Clear f Bit Set f Bit Test f, Skip if Clear Bit Test f, Skip if Set Add literal and W AND literal with W Call subroutine Clear Watchdog Timer Go to address Inclusive OR literal with W Move literal to W Return from interrupt Return with literal in W Return from Subroutine Go into standby mode Subtract W from literal Exclusive OR literal with W BYTE-ORIENTED FILE REGISTER OPERATIONS () () BIT-ORIENTED FILE REGISTER OPERATIONS () () LITERAL AND CONTROL OPERATIONS bb 0bb 0bb bb x 00 0kkk 0000 kkk xx xx x 00 dfff dfff lfff 0xxx dfff dfff dfff dfff dfff dfff dfff lfff 0xx0 dfff dfff dfff dfff dfff bfff bfff bfff bfff kkkk kkkk kkkk 00 kkkk kkkk kkkk 0000 kkkk kkkk kkkk ffff ffff ffff xxxx ffff ffff ffff ffff ffff ffff ffff ffff 0000 ffff ffff ffff ffff ffff ffff ffff ffff ffff kkkk kkkk kkkk 000 kkkk kkkk kkkk 00 kkkk kkkk kkkk C,DC,Z Z Z Z Z Z Z Z Z C C C,DC,Z Z C,DC,Z Z TO,PD Z TO,PD C,DC,Z Z Note : When an I/O register is modified as a function of itself ( e.g., MOVF PORTB, ), the value used will be that value present on the pins themselves. For example, if the data latch is for a pin configured as input and is driven low by an external device, the data will be written back with a 0. : If this instruction is executed on the TMR0 register (and, where applicable, d = ), the prescaler will be cleared if assigned to the Timer0 module. 3: If Program Counter (PC) is modified, or a conditional test is true, the instruction requires two cycles. The second cycle is executed as a NOP.,,,,,,3,,,3,,,,,,,,, 3 3 Note: Additional information on the mid-range instruction set is available in the PICmicro Mid-Range MCU Family Reference Manual (DS3303). DS309C-page Microchip Technology Inc.

73 PIC6F87X 3. Instruction Descriptions ADDLW Add Literal and W Syntax: [label] ADDLW k Operands: 0 k 55 Operation: (W) + k (W) Status Affected: C, DC, Z Description: The contents of the W register are added to the eight bit literal k and the result is placed in the W register. BCF Bit Clear f Syntax: [label] BCF f,b Operands: 0 f 7 0 b 7 Operation: 0 (f<b>) Status Affected: None Description: Bit 'b' in register 'f' is cleared. ADDWF Add W and f Syntax: [label] ADDWF f,d Operands: 0 f 7 d [0,] Operation: (W) + (f) (destination) Status Affected: C, DC, Z Description: Add the contents of the W register with register f. If d is 0, the result is stored in the W register. If d is, the result is stored back in register f. BSF Bit Set f Syntax: [label] BSF f,b Operands: 0 f 7 0 b 7 Operation: (f<b>) Status Affected: None Description: Bit 'b' in register 'f' is set. ANDLW AND Literal with W Syntax: [label] ANDLW k Operands: 0 k 55 Operation: (W).AND. (k) (W) Status Affected: Z Description: The contents of W register are AND ed with the eight bit literal 'k'. The result is placed in the W register. BTFSS Bit Test f, Skip if Set Syntax: [label] BTFSS f,b Operands: 0 f 7 0 b < 7 Operation: skip if (f<b>) = Status Affected: None Description: If bit 'b' in register 'f' is '0', the next instruction is executed. If bit 'b' is '', then the next instruction is discarded and a NOP is executed instead, making this a TCY instruction. ANDWF AND W with f Syntax: [label] ANDWF f,d Operands: 0 f 7 d [0,] Operation: (W).AND. (f) (destination) Status Affected: Z Description: AND the W register with register 'f'. If 'd' is 0, the result is stored in the W register. If 'd' is, the result is stored back in register 'f'. BTFSC Bit Test, Skip if Clear Syntax: [label] BTFSC f,b Operands: 0 f 7 0 b 7 Operation: skip if (f<b>) = 0 Status Affected: None Description: If bit 'b' in register 'f' is '', the next instruction is executed. If bit 'b', in register 'f', is '0', the next instruction is discarded, and a NOP is executed instead, making this a TCY instruction. 00 Microchip Technology Inc. DS309C-page 37

74 PIC6F87X CALL Call Subroutine Syntax: [ label ] CALL k Operands: 0 k 047 Operation: (PC)+ TOS, k PC<0:0>, (PCLATH<4:3>) PC<:> Status Affected: None Description: Call Subroutine. First, return address (PC+) is pushed onto the stack. The eleven-bit immediate address is loaded into PC bits <0:0>. The upper bits of the PC are loaded from PCLATH. CALL is a two-cycle instruction. CLRWDT Syntax: Operands: Operation: Status Affected: Description: Clear Watchdog Timer [ label ] CLRWDT None 00h WDT 0 WDT prescaler, TO PD TO, PD CLRWDT instruction resets the Watchdog Timer. It also resets the prescaler of the WDT. Status bits TO and PD are set. CLRF Clear f Syntax: [label] CLRF f Operands: 0 f 7 Operation: 00h (f) Z Status Affected: Z Description: The contents of register f are cleared and the Z bit is set. COMF Complement f Syntax: [ label ] COMF f,d Operands: 0 f 7 d [0,] Operation: (f) (destination) Status Affected: Z Description: The contents of register f are complemented. If d is 0, the result is stored in W. If d is, the result is stored back in register f. CLRW Syntax: Operands: Operation: Status Affected: Description: Clear W [ label ] CLRW None 00h (W) Z Z W register is cleared. Zero bit (Z) is set. DECF Decrement f Syntax: [label] DECF f,d Operands: 0 f 7 d [0,] Operation: (f) - (destination) Status Affected: Z Description: Decrement register f. If d is 0, the result is stored in the W register. If d is, the result is stored back in register f. DS309C-page Microchip Technology Inc.

75 PIC6F87X DECFSZ Decrement f, Skip if 0 Syntax: [ label ] DECFSZ f,d Operands: 0 f 7 d [0,] Operation: (f) - (destination); skip if result = 0 Status Affected: None Description: The contents of register f are decremented. If d is 0, the result is placed in the W register. If d is, the result is placed back in register f. If the result is, the next instruction is executed. If the result is 0, then a NOP is executed instead making it a TCY instruction. INCFSZ Increment f, Skip if 0 Syntax: [ label ] INCFSZ f,d Operands: 0 f 7 d [0,] Operation: (f) + (destination), skip if result = 0 Status Affected: None Description: The contents of register f are incremented. If d is 0, the result is placed in the W register. If d is, the result is placed back in register f. If the result is, the next instruction is executed. If the result is 0, a NOP is executed instead, making it a TCY instruction. GOTO Unconditional Branch Syntax: [ label ] GOTO k Operands: 0 k 047 Operation: k PC<0:0> PCLATH<4:3> PC<:> Status Affected: None Description: GOTO is an unconditional branch. The eleven-bit immediate value is loaded into PC bits <0:0>. The upper bits of PC are loaded from PCLATH<4:3>. GOTO is a twocycle instruction. IORLW Inclusive OR Literal with W Syntax: [ label ] IORLW k Operands: 0 k 55 Operation: (W).OR. k (W) Status Affected: Z Description: The contents of the W register are OR ed with the eight bit literal 'k'. The result is placed in the W register. INCF Increment f Syntax: [ label ] INCF f,d Operands: 0 f 7 d [0,] Operation: (f) + (destination) Status Affected: Z Description: The contents of register f are incremented. If d is 0, the result is placed in the W register. If d is, the result is placed back in register f. IORWF Inclusive OR W with f Syntax: [ label ] IORWF f,d Operands: 0 f 7 d [0,] Operation: (W).OR. (f) (destination) Status Affected: Z Description: Inclusive OR the W register with register 'f'. If 'd' is 0 the result is placed in the W register. If 'd' is the result is placed back in register 'f'. 00 Microchip Technology Inc. DS309C-page 39

76 PIC6F87X MOVF Move f Syntax: [ label ] MOVF f,d Operands: 0 f 7 d [0,] Operation: (f) (destination) Status Affected: Z Description: The contents of register f are moved to a destination dependant upon the status of d. If d = 0, destination is W register. If d =, the destination is file register f itself. d = is useful to test a file register, since status flag Z is affected. NOP No Operation Syntax: [ label ] NOP Operands: None Operation: No operation Status Affected: None Description: No operation. MOVLW Move Literal to W Syntax: [ label ] MOVLW k Operands: 0 k 55 Operation: k (W) Status Affected: None Description: The eight bit literal k is loaded into W register. The don t cares will assemble as 0 s. RETFIE Return from Interrupt Syntax: [ label ] RETFIE Operands: None Operation: TOS PC, GIE Status Affected: None MOVWF Move W to f Syntax: [ label ] MOVWF f Operands: 0 f 7 Operation: (W) (f) Status Affected: None Description: Move data from W register to register 'f'. RETLW Return with Literal in W Syntax: [ label ] RETLW k Operands: 0 k 55 Operation: k (W); TOS PC Status Affected: None Description: The W register is loaded with the eight bit literal 'k'. The program counter is loaded from the top of the stack (the return address). This is a two-cycle instruction. DS309C-page Microchip Technology Inc.

77 PIC6F87X RLF Rotate Left f through Carry Syntax: [ label ] RLF f,d Operands: 0 f 7 d [0,] Operation: See description below Status Affected: C Description: The contents of register f are rotated one bit to the left through the Carry Flag. If d is 0, the result is placed in the W register. If d is, the result is stored back in register f. C Register f SLEEP Syntax: Operands: Operation: Status Affected: Description: [ label ] SLEEP None 00h WDT, 0 WDT prescaler, TO, 0 PD TO, PD The power-down status bit, PD is cleared. Time-out status bit, TO is set. Watchdog Timer and its prescaler are cleared. The processor is put into SLEEP mode with the oscillator stopped. RETURN Return from Subroutine Syntax: [ label ] RETURN Operands: None Operation: TOS PC Status Affected: None Description: Return from subroutine. The stack is POPed and the top of the stack (TOS) is loaded into the program counter. This is a two-cycle instruction. SUBLW Subtract W from Literal Syntax: [ label ] SUBLW k Operands: 0 k 55 Operation: k - (W) (W) Status Affected: C, DC, Z Description: The W register is subtracted ( s complement method) from the eight-bit literal 'k'. The result is placed in the W register. RRF Rotate Right f through Carry Syntax: [ label ] RRF f,d Operands: 0 f 7 d [0,] Operation: See description below Status Affected: C Description: The contents of register f are rotated one bit to the right through the Carry Flag. If d is 0, the result is placed in the W register. If d is, the result is placed back in register f. C Register f SUBWF Subtract W from f Syntax: [ label ] SUBWF f,d Operands: 0 f 7 d [0,] Operation: (f) - (W) (destination) Status C, DC, Z Affected: Description: Subtract ( s complement method) W register from register 'f'. If 'd' is 0, the result is stored in the W register. If 'd' is, the result is stored back in register 'f'. 00 Microchip Technology Inc. DS309C-page 4

78 PIC6F87X SWAPF Swap Nibbles in f Syntax: [ label ] SWAPF f,d Operands: 0 f 7 d [0,] Operation: (f<3:0>) (destination<7:4>), (f<7:4>) (destination<3:0>) Status Affected: None Description: The upper and lower nibbles of register f are exchanged. If d is 0, the result is placed in the W register. If d is, the result is placed in register f. XORWF Exclusive OR W with f Syntax: [label] XORWF f,d Operands: 0 f 7 d [0,] Operation: (W).XOR. (f) (destination) Status Affected: Z Description: Exclusive OR the contents of the W register with register 'f'. If 'd' is 0, the result is stored in the W register. If 'd' is, the result is stored back in register 'f'. XORLW Exclusive OR Literal with W Syntax: [label] XORLW k Operands: 0 k 55 Operation: (W).XOR. k (W) Status Affected: Z Description: The contents of the W register are XOR ed with the eight-bit literal 'k'. The result is placed in the W register. DS309C-page 4 00 Microchip Technology Inc.

79 PIC6F87X 5.0 ELECTRICAL CHARACTERISTICS Absolute Maximum Ratings Ambient temperature under bias to +5 C Storage temperature C to +50 C Voltage on any pin with respect to VSS (except VDD, MCLR. and RA4) V to (VDD V) Voltage on VDD with respect to VSS to +7.5 V Voltage on MCLR with respect to VSS (Note )...0 to +4 V Voltage on RA4 with respect to Vss...0 to +8.5 V Total power dissipation (Note )...0 W Maximum current out of VSS pin ma Maximum current into VDD pin...50 ma Input clamp current, IIK (VI < 0 or VI > VDD)... ± 0 ma Output clamp current, IOK (VO < 0 or VO > VDD)... ± 0 ma Maximum output current sunk by any I/O pin...5 ma Maximum output current sourced by any I/O pin...5 ma Maximum current sunk by PORTA, PORTB, and PORTE (combined) (Note 3)...00 ma Maximum current sourced by PORTA, PORTB, and PORTE (combined) (Note 3)...00 ma Maximum current sunk by PORTC and PORTD (combined) (Note 3)...00 ma Maximum current sourced by PORTC and PORTD (combined) (Note 3)...00 ma Note : Power dissipation is calculated as follows: Pdis = VDD x {IDD - IOH} + {(VDD - VOH) x IOH} + (VOl x IOL) : Voltage spikes below VSS at the MCLR pin, inducing currents greater than 80 ma, may cause latch-up. Thus, a series resistor of 50-00Ω should be used when applying a low level to the MCLR pin, rather than pulling this pin directly to VSS. 3: PORTD and PORTE are not implemented on PIC6F873/876 devices. NOTICE: Stresses above those listed under Absolute Maximum Ratings may cause permanent damage to the device. This is a stress rating only and functional operation of the device at those or any other conditions above those indicated in the operation listings of this specification is not implied. Exposure to maximum rating conditions for extended periods may affect device reliability. 00 Microchip Technology Inc. DS309C-page 49

80 PIC6F87X 5.5 Timing Parameter Symbology The timing parameter symbols have been created following one of the following formats:. TppSppS 3. TCC:ST (I C specifications only). TppS 4. Ts (I C specifications only) T F Frequency T Time Lowercase letters (pp) and their meanings: pp cc CCP osc OSC ck CLKOUT rd RD cs CS rw RD or WR di SDI sc SCK do SDO ss SS dt Data in t0 T0CKI io I/O port t TCKI mc MCLR wr WR Uppercase letters and their meanings: S F Fall P Period H High R Rise I Invalid (Hi-impedance) V Valid L Low Z Hi-impedance I C only AA output access High High BUF Bus free Low Low TCC:ST (I C specifications only) CC HD Hold SU Setup ST DAT DATA input hold STO STOP condition STA START condition FIGURE 5-5: LOAD CONDITIONS Load Condition Load Condition VDD/ RL Pin CL Pin CL VSS VSS RL = 464 Ω CL = 50 pf for all pins except OSC, but including PORTD and PORTE outputs as ports, 5 pf for OSC output Note: PORTD and PORTE are not implemented on PIC6F873/876 devices. 00 Microchip Technology Inc. DS309C-page 6

81 PIC6F87X FIGURE 5-6: EXTERNAL CLOCK TIMING Q4 Q Q Q3 Q4 Q OSC CLKOUT TABLE 5-: Parameter No. EXTERNAL CLOCK TIMING REQUIREMENTS Sym Characteristic Min Typ Max Units Conditions FOSC External CLKIN Frequency (Note ) Oscillator Frequency (Note ) TOSC External CLKIN Period (Note ) Oscillator Period (Note ) TCY Instruction Cycle Time (Note ) 3 TosL, TosH 4 TosR, TosF External Clock in (OSC) High or Low Time External Clock in (OSC) Rise or Fall Time DC 4 MHz XT and RC osc mode DC 4 MHz HS osc mode (-04) DC 0 MHz HS osc mode (-0) DC 0 MHz HS osc mode (-0) DC 00 khz LP osc mode DC 4 MHz RC osc mode 0. 4 MHz XT osc mode 4 0 MHz HS osc mode (-0) MHz khz HS osc mode (-0) LP osc mode 50 ns XT and RC osc mode 50 ns HS osc mode (-04) 00 ns HS osc mode (-0) 50 ns HS osc mode (-0) 5 µs LP osc mode 50 ns RC osc mode 50 0,000 ns XT osc mode 50 ns HS osc mode (-04) ns HS osc mode (-0) ns HS osc mode (-0) 5 µs LP osc mode 00 TCY DC ns TCY = 4/FOSC 00 ns XT oscillator.5 µs LP oscillator 5 ns HS oscillator 5 ns XT oscillator 50 ns LP oscillator 5 ns HS oscillator Data in "Typ" column is at 5V, 5 C unless otherwise stated. These parameters are for design guidance only and are not tested. Note : Instruction cycle period (TCY) equals four times the input oscillator time-base period. All specified values are based on characterization data for that particular oscillator type under standard operating conditions, with the device executing code. Exceeding these specified limits may result in an unstable oscillator operation and/or higher than expected current consumption. All devices are tested to operate at "min." values with an external clock applied to the OSC/CLKIN pin. When an external clock input is used, the "max." cycle time limit is "DC" (no clock) for all devices. DS309C-page 6 00 Microchip Technology Inc.

82 PIC6F87X FIGURE 5-7: CLKOUT AND I/O TIMING Q4 Q Q Q3 OSC 0 CLKOUT I/O Pin (Input) 7 5 I/O Pin (Output) Old Value New Value Note: Refer to Figure 5-5 for load conditions. 0, TABLE 5-: CLKOUT AND I/O TIMING REQUIREMENTS Param No. Symbol Characteristic Min Typ Max Units Conditions 0* TosHckL OSC to CLKOUT ns (Note ) * TosHck OSC to CLKOUT ns (Note ) H * TckR CLKOUT rise time ns (Note ) 3* TckF CLKOUT fall time ns (Note ) 4* TckLioV CLKOUT to Port out valid 0.5TCY + 0 ns (Note ) 5* TioVckH Port in valid before CLKOUT TOSC + 00 ns (Note ) 6* TckHioI Port in hold after CLKOUT 0 ns (Note ) 7* TosHioV OSC (Q cycle) to Port out valid ns 8* TosHioI OSC (Q cycle) to Standard (F) 00 ns Port input invalid (I/O in hold time) Extended (LF) 00 ns 9* TioVosH Port input valid to OSC (I/O in setup time) 0 ns 0* TioR Port output rise time Standard (F) 0 40 ns Extended (LF) 45 ns * TioF Port output fall time Standard (F) 0 40 ns Extended (LF) 45 ns * Tinp INT pin high or low time TCY ns 3 * Trbp RB7:RB4 change INT high or low time TCY ns * These parameters are characterized but not tested. Data in "Typ" column is at 5V, 5 C unless otherwise stated. These parameters are for design guidance only and are not tested. These parameters are asynchronous events not related to any internal clock edges. Note : Measurements are taken in RC mode where CLKOUT output is 4 x TOSC. 00 Microchip Technology Inc. DS309C-page 63

83 PIC6F87X FIGURE 5-0: TIMER0 AND TIMER EXTERNAL CLOCK TIMINGS RA4/T0CKI RC0/TOSO/TCKI TMR0 or TMR Note: Refer to Figure 5-5 for load conditions. TABLE 5-4: TIMER0 AND TIMER EXTERNAL CLOCK REQUIREMENTS Param No. Symbol Characteristic Min Typ Max Units Conditions 40* Tt0H T0CKI High Pulse Width No Prescaler 0.5TCY + 0 ns Must also meet With Prescaler 0 ns parameter 4 4* Tt0L T0CKI Low Pulse Width No Prescaler 0.5TCY + 0 ns Must also meet With Prescaler 0 ns parameter 4 4* Tt0P T0CKI Period No Prescaler TCY + 40 ns With Prescaler Greater of: 0 or TCY + 40 N ns N = prescale value (, 4,..., 56) 45* TtH TCKI High Time Synchronous, Prescaler = 0.5TCY + 0 ns Must also meet Synchronous, Standard(F) 5 ns parameter 47 Prescaler =,4,8 Extended(LF) 5 ns Asynchronous Standard(F) 30 ns Extended(LF) 50 ns 46* TtL TCKI Low Time Synchronous, Prescaler = 0.5TCY + 0 ns Must also meet Synchronous, Standard(F) 5 ns parameter 47 Prescaler =,4,8 Extended(LF) 5 ns Asynchronous Standard(F) 30 ns Extended(LF) 50 ns 47* TtP TCKI input period Synchronous Standard(F) Greater of: 30 OR TCY + 40 N Extended(LF) Greater of: 50 OR TCY + 40 N ns N = prescale value (,, 4, 8) N = prescale value (,, 4, 8) Asynchronous Standard(F) 60 ns Extended(LF) 00 ns Ft Timer oscillator input frequency range (oscillator enabled by setting bit TOSCEN) DC 00 khz 48 TCKEZtmr Delay from external clock edge to timer increment TOSC 7TOSC * These parameters are characterized but not tested. Data in "Typ" column is at 5V, 5 C unless otherwise stated. These parameters are for design guidance only and are not tested. 00 Microchip Technology Inc. DS309C-page 65

84 PIC6F87X FIGURE 5-: CAPTURE/COMPARE/PWM TIMINGS (CCP AND CCP) RC/TOSI/CCP and RC/CCP (Capture Mode) RC/TOSI/CCP and RC/CCP (Compare or PWM Mode) Note: Refer to Figure 5-5 for load conditions TABLE 5-5: CAPTURE/COMPARE/PWM REQUIREMENTS (CCP AND CCP) Param No. Sym Characteristic Min Typ Max Units Conditions 50* TccL CCP and CCP input low time 5* TccH CCP and CCP input high time No Prescaler 0.5TCY + 0 ns With Prescaler Standard(F) 0 ns Extended(LF) 0 ns No Prescaler 0.5TCY + 0 ns With Prescaler Standard(F) 0 ns Extended(LF) 0 ns 5* TccP CCP and CCP input period 3TCY + 40 N ns N = prescale value (, 4 or 6) 53* TccR CCP and CCP output rise time Standard(F) 0 5 ns Extended(LF) 5 50 ns 54* TccF CCP and CCP output fall time Standard(F) 0 5 ns Extended(LF) 5 45 ns * These parameters are characterized but not tested. Data in "Typ" column is at 5V, 5 C unless otherwise stated. These parameters are for design guidance only and are not tested. DS309C-page Microchip Technology Inc.

85 PIC6F87X FIGURE 5-: PARALLEL SLAVE PORT TIMING (PIC6F874/877 ONLY) RE/CS RE0/RD RE/WR 65 RD7:RD Note: Refer to Figure 5-5 for load conditions. 63 TABLE 5-6: Parameter No. PARALLEL SLAVE PORT REQUIREMENTS (PIC6F874/877 ONLY) Symbol Characteristic Min Typ Max Units Conditions 6 TdtVwrH Data in valid before WR or CS (setup time) * TwrHdtI WR or CS to data in invalid (hold time) Standard(F) 0 ns Extended(LF) 35 ns 64 TrdLdtV RD and CS to data out valid ns ns ns ns Extended Range Only Extended Range Only 65 TrdHdtI RD or CS to data out invalid 0 30 ns * These parameters are characterized but not tested. Data in "Typ" column is at 5V, 5 C unless otherwise stated. These parameters are for design guidance only and are not tested. 00 Microchip Technology Inc. DS309C-page 67

86 PIC6F87X FIGURE 5-9: USART SYNCHRONOUS TRANSMISSION (MASTER/SLAVE) TIMING RC6/TX/CK Pin RC7/RX/DT Pin 0 Note: Refer to Figure 5-5 for load conditions. TABLE 5-0: USART SYNCHRONOUS TRANSMISSION REQUIREMENTS Param No. Sym Characteristic Min Typ Max Units Conditions 0 TckHdtV SYNC XMIT (MASTER & SLAVE) Clock high to data out valid Standard(F) 80 ns Extended(LF) 00 ns Tckrf Clock out rise time and fall time Standard(F) 45 ns (Master mode) Extended(LF) 50 ns Tdtrf Data out rise time and fall time Standard(F) 45 ns Extended(LF) 50 ns Data in Typ column is at 5V, 5 C unless otherwise stated. These parameters are for design guidance only and are not tested. FIGURE 5-0: USART SYNCHRONOUS RECEIVE (MASTER/SLAVE) TIMING RC6/TX/CK pin RC7/RX/DT pin 5 6 Note: Refer to Figure 5-5 for load conditions. TABLE 5-: Parameter No. USART SYNCHRONOUS RECEIVE REQUIREMENTS Sym Characteristic Min Typ Max Units Conditions 5 TdtVckL SYNC RCV (MASTER & SLAVE) Data setup before CK (DT setup 5 ns time) 6 TckLdtl Data hold after CK (DT hold time) 5 ns Data in Typ column is at 5V, 5 C unless otherwise stated. These parameters are for design guidance only and are not tested. 00 Microchip Technology Inc. DS309C-page 73

87 PIC6F87X FIGURE 5-: A/D CONVERSION TIMING BSF ADCON0, GO Q4 (TOSC/) () 3 30 TCY A/D CLK 3 A/D DATA ADRES OLD_DATA NEW_DATA ADIF GO DONE SAMPLE SAMPLING STOPPED Note: If the A/D clock source is selected as RC, a time of TCY is added before the A/D clock starts. This allows the SLEEP instruction to be executed. TABLE 5-3: A/D CONVERSION REQUIREMENTS Param No. Sym Characteristic Min Typ Max Units Conditions 30 TAD A/D clock period Standard(F).6 µs TOSC based, VREF 3.0V Extended(LF) 3.0 µs TOSC based, VREF.0V Standard(F) µs A/D RC mode Extended(LF) µs A/D RC mode 3 TCNV Conversion time (not including S/H time) (Note ) TAD 3 TACQ Acquisition time (Note ) 0* µs The minimum time is the amplifier settling time. This may be used if the "new" input voltage has not changed by more than LSb (i.e., V) from the last sampled voltage (as stated on CHOLD). 34 TGO Q4 to A/D clock start TOSC/ If the A/D clock source is selected as RC, a time of TCY is added before the A/D clock starts. This allows the SLEEP instruction to be executed. * These parameters are characterized but not tested. Data in "Typ" column is at 5V, 5 C unless otherwise stated. These parameters are for design guidance only and are not tested. This specification ensured by design. Note : ADRES register may be read on the following TCY cycle. : See Section. for minimum conditions. 40 µs 00 Microchip Technology Inc. DS309C-page 75

88 6 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING CONTENTS AT A GLANCE Estimating Application Power Requirements Reset Interfacing to External Devices DIGITAL LOGIC DIFFERENT LOGIC LEVELS WITH ECL AND LEVEL SHIFTING LEDs Switch Bounce Matrix Keypads LCDs Analog I/O POTENTIOMETERS PULSE-WIDTH MODULATION (PWM) I/O AUDIO OUTPUT Relays and Solenoids DC and Stepper Motors R/C Servo Control Serial Interfaces SYNCHRONOUS ASYNCHRONOUS (NRZ) SERIAL DALLAS SEMICONDUCTOR -WIRE INTERFACE After reading the previous two chapters and Introduction to Electronics on the CD- ROM, you must feel like there is nothing left to understand about designing PICmicro MCU applications. In these chapters on the CD-ROM I have provided background on how microcontroller interfacing is carried out and some of the theories and pitfalls that you should be aware of. This chapter covers some specifics about how the PICmicro MCU works when wired to different interfaces. 53

89 54 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING I am not trying to say that the PICmicro MCU is a difficult microcontroller to interface to. Actually, it is one of the easiest eight-bit microcontrollers to develop interface applications for. In different versions, with built-in oscillators and reset circuits, interfaces can be unbelievably easy to implement. Despite this, you should be aware of a few things that will help you make your applications more efficient and keep you from having difficult to debug problems. Estimating Application Power Requirements Accurate power estimating for your applications is important because the expected power consumption affects how much heat is produced by the circuit and what kind of power supply is required by it. Although the PICmicro MCU power can usually only be estimated to an order of a magnitude, this is usually good enough to ensure that the circuit won t overheat, the power supply won t burn out or the batteries will not be exhausted before the required execution time has passed. For the PICmicro MCU itself, the intrinsic current, what I call the current consumed by the microcontroller with nothing connected to it, is available from Microchip in the data sheets. For the PIC6F87x, rated at 4 MHz, Table 6- lists the IDD (the supply current or intrinsic current), according to the oscillator type. The current rating for the oscillator type selected in the configuration fuses should be the basis for your estimate. Notice that as the clock frequency changes, the intrinsic current consumption will go up at a rate of about one ma per MHz. For estimating purposes, I recommend that you use the worst case for the oscillator selected. Next, select the current requirements for the devices that connect directly to the PICmicro MCU. Depending on their operation, the current requirements can change drastically. For example, an LED that is off consumes just no current, and one that is on can consume from five to 0 ma. Again, for these devices, the worst cases should be used with the estimate. Also, note that different devices will respond differently, depending on how they are used. A very good example of this is a LCD display. Many modern LCDs have built-in pull-ups to make interfacing easier for electronic devices that have open collector outputs (such as the 805). Typically, these devices current requirements will be quoted with the TABLE 6 PICmicro MCU Oscillator Current Consumption Comparison OSCILLATOR IDD FREQUENCY LP 5.5 A 3 khz RC 5 ma 4 MHz XT 5 ma 4 MHz HS 3.5 ma 4 MHz

90 RESET 55 minimum value, rather than the maximum. To ensure you have an accurate estimate, you will have to check the current drain with the LCD connected and operating with the PICmicro MCU. Lastly, the power consumption of other devices connected to the circuit (but not the PICmicro MCU) will have to be determined through the device s data sheets. Again, the worst-case situation should be taken into account. Once these three current values have been found, they can be summed together to get the total application power and then multiplied by the voltage applied to get the power consumed by the application. Once I have this value, I normally multiply it by a 5- to 50- percent derater to ensure that I have the absolute worst case. In the applications in this book where I have specified the current, I have continually sought out the worst case and then derated the power to make it seem even worse. This is to ensure that you will not have any problems with your application power supply. Power can really make or break an application. Incorrectly specifying a supply can lead to problems with the application not powering up properly, failing intermittently, or not running as long on batteries as expected. Marginal power supply problems can be extremely difficult to find as well. By going with a derated worst case for my application power requirements, I have eliminated one possible point in the application from going bad. Reset Reset in many new PICmicro MCU part numbers can be simply implemented, eliminating the need for a separate circuit or having a built-in brown-out reset sensor. Even putting your own reset circuit into an application is simple; only a couple of rules must be followed. Adding external reset circuit to the PICmicro MCU consists of a pull-up connected to the _MCLR pin of the PICmicro MCU. As shown in Fig. 6-, a switch pulling _MCLR to ground (to reset the device) can be implemented with a momentary on switch. A resistor of to 0 K is probably appropriate; the input is CMOS and does not draw any current through the resistor. The resistor is primarily used as a current-limiting device for the momentary-on switch. In the configuration registers of the mid-range parts there is a bit known as PWRTE. This bit will insert a 7-ms delay during PICmicro MCU power up before the first instruction is fetched and executed. The purpose of this function is to allow the PICmicro Figure 6-

91 56 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Figure 6- PICmicro MCU reset with brown out protection MCU s clock to stabilize before the application starts. In the low-end and high-end PICmicro MCU s, this function is not always available. PWRTE does not have to be enabled if a stable clock is being input to the PICmicro MCU, such as in the case where a canned oscillator is used as the PICmicro MCU s clock source instead of a crystal, ceramic resonator, or RC network. When the _MCLR pin is made active (pulled low), the oscillator stops until the pin is brought back high. As well, the oscillator is also stopped during sleep mode to minimize power consumption. The PWRTE 7 ms delay is required in these cases, as well to ensure the clock is stable before the application s code starts executing. If the PICmicro MCU is run at low voltage (less than 4.0 volts), do not enable the built-in Brown-Out Reset (BOR), unless it is available with a low-voltage selector option. Once power drops below 4.0 volts, then circuit will become active and will hold the PICmicro MCU reset even though it is receiving a valid voltage for the application. The low-voltage option usually means that the brown-out reset will reset the PICmicro MCU when the input voltage is below 4.0 volts or.8 volts. If you are going to use low voltage and want a brown-out detect function, this can be added with a Zener diode and a comparator as is shown in Fig. 6-. In this circuit, voltage is reduced by the Zener diode voltage regulator to 3 volts. If V cc goes below three volts, this circuit will put the PICmicro MCU into reset. The voltagedivider values can be changed for different ratios and R can be quite high (00 K ) to minimize current drain in a battery-driven application. The PICC5xx and 6C505 PICmicro MCU s can provide an internal reset function, which uses V dd as the _MCLR pin input. This frees the _MCLR pin for use as an input. The freed _MCLR pins generally cannot be used as an output. A common use for this pin is RS-3 input using a resistor as a current limiter and providing bit-banging software to read the incoming values. If you use the _MCLR/I/O pin in this fashion, be sure that you clamp the pin shown in Fig If the incoming negative voltage is not clamped within the PICmicro MCU, the negative voltage could cause the PICmicro MCU to be forced into reset mode. If the positive voltage is not clamped, then the PICmicro MCU could go into the programming mode. The general-purpose pins are designed with clamping diodes built in and will not allow inputs to be driven outside V dd or ground. Not clamping the input pins can cause some confusing problems when you first work with the PICmicro MCU in this type of application. The use of clamping diodes for RS-3 interfacing is shown in the Serial LCD Interface in Chapter 6.

92 INTERFACING TO EXTERNAL DEVICES 57 Figure 6-3 Internal reset allowing _MCLR pin to be used for RS- 3 input Interfacing to External Devices The previous chapters have provided a lot of information about the peripheral hardware built into the PICmicro MCU that will help making applications easier. Coupled with the information contained in the appendices, you would have thought I had it all covered. The following sections cover some of the hints and tips I ve learned over the years for interfacing PICmicro MCUs to other devices. With this information, I have also included source code for the different interface hardware. This code is available on the CD- ROM as snippets that can be cut and pasted into your applications, as well as into macros that can be added to the applications. Much of this information and code is used later in the book when I go through the experiments and projects. Some of the interfaces will seem very complex or difficult to create, but I have tried to work through many of the difficulties and provide you with sample circuits that are simple and cheap to implement. DIGITAL LOGIC It should not be surprising that the PICmicro MCU can interface directly to TTL and CMOS digital logic devices. The PICmicro MCU s parallel I/O pins provide digital output levels that can be detected properly by both logic technologies and inputs that can detect logic levels output from these logic families. If you check the PICmicro MCU data sheets, you will see that the output characteristics are: V ol (output low voltage) 0.6 V (max.) V oh (output high voltage) V dd 0.7 V (min.) This specification is given to allow for different V dd power inputs. For a V dd of 5 volts, you can expect a high output of 4.3 volts or greater (normally, I see 4.7 volts when a PICmicro MCU pin is not under load). If the power voltage input (V dd ) was reduced to volts, low output would still be 0.6 volts and high output becomes.3 volts (V dd 0.7) or greater. The PICmicro MCU pins are specified to drive (source) up to 0 ma and sink (pull the output to ground) 5 ma. These current capabilities easily allow the PICmicro MCU to drive LEDs. The total current sourced or sunk by the PICmicro MCU should not exceed 50 ma (which is six I/O pins sinking the maximum current).

93 58 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING The input threshold voltage, the point at which the input changes from an I to an O and visa versa, is also dependent on the input power (V dd ) voltage level. The threshold is different for different devices and the data sheet should be consulted for precise values. In general, for a number of different PICmicro MCU part numbers, this value is specified as being in the range: 0.5 V dd 0.8 V V threshold 0.48 V dd As a rule, you should use the higher value. For higher V dd s, this is approximately one half V dd. At lower V dd voltages, ( volts), the threshold becomes approximately two-thirds of V dd. For the most part, interfacing to conventional logic devices is very straightforward in the PICmicro MCU. The following sections feature some special interfacing cases and how the PICmicro MCU can be wired to other devices to take advantage of the PICmicro MCU s electrical properties. Using these properties, applications can use standard I/O pins to simulate different interface types and, in some cases, reduce the numbers of pins required for an application. Parallel bus devices Although the PICmicro MCU is very well suited for standalone applications, many applications have to connect to external devices. There are builtin PICmicro MCU interfaces for Non-Return to Zero (NRZ) asynchronous I/O and two-wire serial I/O, but sometimes the best interface is a simulated parallel I/O bus. A simulated parallel bus is useful for increasing the I/O capabilities of the PICmicro MCU using standard I/O chips. These devices can be accessed fairly easily using an eight-bit I/O port and a few extra control pins from the PICmicro MCU. I realize that the PIC7Cxx has the ability to drive a parallel bus, but I tend to shy away from using these devices for this purpose because the PIC7Cxx I/O data bus is 6 bits wide and can only access the full word of data at any one time. Most parallel buses require an eight-bit bus and the PIC7Cxx devices tend to be more expensive than using the midrange parts. Looking at the extra costs of the PIC7Cxx devices, coupled with the complexity of adding the address buffers, you re probably better off using the mid-range devices and simulating the bus as shown here. When I create a parallel bus, I normally use PORTB for eight data bits and use other PORT pins for the _RD and _WR lines. To avoid the extra costs and complexity of decode circuitry, it is probably best to devote one I/O line to each device. Before writing from the PICmicro MCU to the device, TRISB is set to output mode and the value to be written is output on PORTB. Next, the _CS and _WR lines are pulled low and remain active until the device s minimum access times are met. _RD is similar with TRISB being put in input mode, the _CS and _RD pins are held active until the devices minimum read access time is met, at which point the data is strobed into w, _CS, and _RD are driven high. The circuit in Fig. 6-4 requires two parallel output bytes and one parallel input byte. This could be implemented with a 40-pin PICmicro MCU, using the I/O pins directly, but it is much more cost effective to use an 8-pin PICmicro MCU (such as the PIC6F84) and a tristate output buffer and two eight bit registers. In Fig. 6-4, it is assumed that data is clocked in or output with negative active signal pulses. With this circuit, RA0 to RA would be set for output and initialized to 4 (high voltage) driven out. To read the eight data bits on the tristate buffer, the following code could be used:

94 INTERFACING TO EXTERNAL DEVICES 59 Figure 6-4 PICmicro MCU simulated parallel 0 port bsf STATUS, RPO ; Put PORTB into Input Mode movlw 0x0FF movwf TRISB 0X080 bcf STATUS, RPO bcf PORTA, 0 ; Drop the _RD line call Dlay ; Delay until Data Output Valid movf PORT B, w ; Read Data from the Port bsf PORT A, 0 ; _RD (disable _RD Line) Writing to one of the output registers is similar: bsf STATUS, RPO clrf TRIS B 0X080 ; PORTB Output bcf STATUS, RPO bcf PORTA, ; Enable the _WR Line movwf PORTB ; output the Data call Dlay ; Wait Data Receive Valid bsf PORTA, ; _WR. Combining input and output Often when working on applications, you will find some situations where peripheral devices will use more than one pin for I/O. Another case would be when you are connecting two devices, one input and one output and would like to combine them somehow so that you can reduce the number of PICmicro MCU pins required. Fewer PICmicro MCU pins means that you can use cheaper PICmicro MCUs and avoid complex application wiring. This section presents two techniques for doing this and the rules governing their use. This might at first appear problematic and asking for problems with bus contention, but they really do work and can greatly simplify your application. When interfacing the PICmicro MCU to a driver and receiver (such as a memory with a separate output and input), a resistor can be used to avoid bus contention at any of the pins (Fig. 6-5). In this situation, when the PICmicro MCU s I/O pin is driving out, it will be driving the Data In pin register and regardless of the output of the Data Out pin. If the PICmicro MCU and Data Out pins are driving different logic levels, the resister will limit the current flowing between the PICmicro MCU and the memory Data Out pin. The value received on the Data In pin will always be the PICmicro MCU s output due to the voltage drop within the registor.

95 60 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Figure 6-5 PICmicro MCU simulated parallel 0 port When the PICmicro MCU is receiving data from the memory, its I/O pin will be put in input mode and the Data Out pin will drive its value to not only the PICmicro MCU s I/O pin, but the Data In pin as well. In this situation, the Data In pin should not be latching any Data In. To avoid this, in most cases where this circuit combines input and output, the two input and output pins are on the same device and the data mode is controlled by the PICmicro MCU to prevent invalid data from being input into the device. This is an important point because it defines how this trick should be used. The I/O pins that the PICmicro MCU are connected to must be mutually exclusive and can never be transmitting data at the same time. A common use for this method of connection data in and data out pins is used in SPI memories, which have separate data input and output pins. The second trick is to have button input, along with an external device receiver. As is shown in Fig. 6-6, a button can be put on the same net as an input device and the PICmicro MCU pin that drives it. When the button is open or closed, the PICmicro MCU can drive data to the input device, the 00-K and 0-K resistors will limit the current flow between V cc and ground. If the PICmicro MCU is going to read the button high (switch open) or low (switch closed) will be driven on the bus at low currents when the pin is in input mode. If the button switch is open, then the 00-K resistor acts like a pull up and a is returned. When the button switch is closed, then there will be approximately 0.5 volt across the 0-K resistor, which will be read as a 0. The button with the two resistors pulling up and down are like a low-current driver and the voltage produced by them is easily overpowered by active drivers. Like the first method, the external input device cannot receive data except when the PICmicro MCU is driving the circuit. A separate clock or enable should be used to ensure that input data is received when the PICmicro MCU is driving the line. Two points about this method; this can be extrapolated to work with a switch matrix keyboard. The circuit can become very complex, but it will work. Secondly, a Figure 6-6 Combining button in-put with digital I/O

96 INTERFACING TO EXTERNAL DEVICES 6 resistor/capacitor network for debouncing the button cannot be used with this circuit because a resistor-capacitor network will slow down the response of the PICmicro MCU driving the data input pin and will cause problems with the correct value being accepted. When a button is shared with an input device; such as is shown in Fig. 6-6, software button debouncing will have been done inside the PICmicro MCU. Simulated open collector/open drain I/O Open collector/open drain outputs are useful in several different interfacing situations. Along with providing a node in a dotted AND bus, they are also useful to interface with IC and other networks. I find that the single open drain pin available in the different PICmicro MCU devices to be insufficient for many applications, which is why I find it useful to simulate an open drain driver with a standard I/O pin. An open drain pin (shown in Fig. 6-7) consists of a N-channel MOSFET transistor with its source connected to the I/O pin. Because there is no P-channel high driver in the pin circuit, when a is being output the only transistor will be turned off and the pin is allowed to float. Floating, in most applications, means having a pull up and multiple opencollector/open-drain drivers on the net. When the data out bit is low (and TRIS is enabled for output), the pin is pulled low. Otherwise, it is not electrically connected to anything ( tristated ). This action can be simulated by using the following code, which enables the I/O pin output to be low if the carry flag is reset. If the carry flag is set, then the pin is put into input mode. bcf PORT#, pin ; Make Sure PORTB Pin Bit is 0 bsf STATUS, RPO btfss STATUS, C ; If Carry Set, Disable Open Collector goto $ 4 ; Carry Reset, Enable Open Collector nop bsf TRIS 0x080, pin goto $ 3 bcf TRIS 0x080, pin goto $ bcf STATUS, RPO This code, which is designed for mid-range PICmicro MCUs, will either set the pin to input (tristate) mode or pulled low on the sixth cycle after it has been invoked, I normally put this code into a macro, with the port and pin specified as parameters. It will seem like I went to some lengths to ensure that the timing was the same for making the bit tristate (input mode) or pulled low to 0, as well as the state specified by the carry flag. Regardless of the execution path, this code will take eight instruction cycles and the Figure 6-7 configuration Open Drain no pin

97 6 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING I/O pin value will be changed at five cycles. I did this because this function is often used with IC or other network protocols and using the carry flag allows bits to be shifted through this code easily. In the sample open-drain simulation code, I reset the specified pin before potentially changing its TRIS value. This is to prevent it from being the wrong value, based on reads and writes of other I/O pins. This is the inadvertent pin changes that I ve written about elsewhere in the book. DIFFERENT LOGIC LEVELS WITH ECL AND LEVEL SHIFTING Often, when working with PICmicro MCUs and other microcontrollers, you will have to interface devices of different logic families together. For standard positive voltage logic families (i.e., TTL to CMOS), this is not a problem; the devices can be connected directly. But, interfacing a negative voltage logic to a positive voltage logic family (i.e., ECL to CMOS) can cause some problems. Although chips usually are available to provide this interface function (for both input and output), they typically only work in only one direction (which precludes bi-directional busses even if the logic family allows it) and the chips can add a significant cost to the application. The most typical method of providing level conversion is to match the switching threshold voltage levels of the two logic families. As shown in Fig. 6-8, the ground level for the COMS microcontroller has been shifted below ground (the microcontroller s ground is actually the CMOS 0 level). The purpose of this is to place the point where the microcontroller s input logic switches between a 0 and a (known as the input logic threshold voltage) is the same as the ECL Logic. The resistor (which is between K and 0 K) is used to limit the current flow because of the different logic swings of the two different families. Looking at the circuit block diagram, you re probably thinking that the cost of shifting the microcontroller power supply is much greater than just a few interface chips. Actually, this isn t a big concern because of the low power requirements of modern CMOS microcontrollers. In Fig. 6-8, the microcontroller s ground reference can be produced by placing a silicon diode (which has a 0.7 voltage drop across it) between it and the ECL s -volt power supply negative output. The 5-volt and -volt supplies positive output have a common threshold voltage for this circuit and the registor limits the CMOS Figure 6-8 ECL to CMOS logic level conversion

98 LEDs 63 logic swing to the volt ECL swing. This example might seem simplistic, but it would provide the ability to connect a CMOS 0- to 5-volt microcontroller to ECL logic (and allow signals to be sent in either direction, between the PICmicro MCU and the ECL Logic) at a very low cost. LEDs The most common form of output from a microcontroller is the Light-Emitting Diode (LED). As an output device, it is cheap and easy to wire to a microcontroller. Generally, LEDs require anywhere from 5 ma of current to light (which is within the output sink/source specification for most microcontrollers). But, what has to be remembered is, LEDs are diodes, which means that current flows in one direction only. The typical circuit that I use to control an LED from a PICmicro MCU I/O pin is shown in Fig 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, the LED will be turned off. The 0 Ohm resistor is used for current limiting and will prevent excessive current that can damage the microcontroller, LED and the power supply. Elsewhere in the book, I have shown how this resistor value is calculated. Some microcontrollers (such as the PICmicro MCU) already have current-limiting output pins, which lessens the need for the current-limiting resistor. But, I prefer to always put in the resistor to guarantee that a short (either to ground or V cc ) cannot ever damage the microcontroller of the circuit it s connected to (including the power supply). Probably the easiest way to output numeric (both decimal and hex) data is via sevensegment LED displays. These displays were very popular in the 970s (if you re old enough, your first digital watch probably had seven-segment LED displays), but have been largely replaced by LCDs. Seven-segment LED displays (Fig. 6-0) are still useful devices that can be added to a circuit without a lot of software effort. By turning on specific LEDs (each of which light up a segment in the display), the display can be used to output decimal numbers. Each one of the LEDs in the display is given an identifier and a single pin of the LED is brought out of the package. The other LED pins are connected together and wired to a common pin. This common LED pin is used to identify the type of seven-segment display (as either common cathode or common anode). Wiring one display to a microcontroller is quite easy it is typically wired as seven (or eight, if the decimal point, DP, is used) LEDs wired to individual pins. The most important piece of work you ll do when setting up seven-segment LED displays is matching and documenting the microcontroller bits to the LEDs. Spending a few moments at the start of a project will simplify wiring and debugging the display later. Figure 6-9 LED connection to a microcontroller

99 64 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Figure 6-0 display Organization of a 7 segment LED The typical method of wiring multiple seven-segment LED displays together is to wire them all in parallel and then control the current flow through the common pin. Because the current is generally too high for a single microcontroller pin, a transistor is used to pass the current to the common power signal. This transistor selects which display is active. Figure 6- shows common-cathode seven-segment displays connected to a microcontroller. In this circuit, the microcontroller will shift between the displays showing each digit in a very short time slice. This is usually done in a timer interrupt handler. The basis for the interrupt handler s code is: Int - Save Context Registers - Reset Timer and Interrupt - LED_Display 0 ; Turn Off all the LEDs - LED_Output Display[ Cur ] - Cur (Cur ) mod #Displays ; Point to Next Sequence Display - LED_Display Cur ; Display LED for Current Display - Restore Context Registers - Return from Interrupt This code will cycle through each of the digits (and displays), having current go through the transistors for each one. To avoid flicker, I generally run the code so that each digit is turned on/off at least 50 times per second. The more digits you have, the faster you have Figure 6- Wiring four 7 segment LED displays

100 SWITCH BOUNCE 65 to cycle the interrupt handler (i.e., eight seven-segment displays must cycle at least 400 digits per second, which is eight times as fast as a single display). You might feel that assigning a microcontroller bit to select each display LED to be somewhat wasteful (at least I do). I have used high-current TTL demultiplexer (i.e., 74S38) outputs as the cathode path to ground (instead of discrete transistors). When the output is selected from the demultiplexer, it goes low, allowing current to flow through the LEDs of that display (and turning it on). This actually simplifies the wiring of the final application as well. The only issue is to ensure that the demultiplexer output can sink the maximum of 40 ma of current that will come through the common cathode connection. Along with seven-segment displays, 4- and 6-segment LED displays are available, which can be used to display alphanumeric characters (A to Z and 0 to 9). By following the same rules as used when wiring up a seven-segment display, you shouldn t have any problems wiring the display to a PICmicro MCU. Chapter 6 shows how seven- and 6-segment LEDs can be used to display letters and numbers. Switch Bounce When a button is opened or closed, we perceive that it is a clean operation that really looks like a step function. In reality, the contacts of a switch bounce when they make contact, resulting in a jagged signal (Fig. 6-). When this signal is passed to a PICmicro MCU, the microcontroller can recognize this as multiple button presses, which will cause the application software to act as if multiple, very fast button presses have occurred. To avoid this problem the noisy switch press is debounced into an idealized press, or the step function (Fig. 6-3). Two common methods are used to debounce button inputs. The first is to poll the switch line at short intervals until the switch line stays at the same level for an extended period of time. A button is normally considered to be debounced if it Figure 6- Oscilloscope picture of a switch bounce

101 66 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Figure 6-3 operation Idealized switch does not change state for 0 ms or longer. By polling the line every 5 ms, this debouncing method can be conceptualized quite easily (Fig. 6-4). The advantage of this method is that it can be done in an interrupt handler and the line can be scanned periodically with a flag set if the line is high and another flag in the line is low. For the indeterminate stage, neither bit would be set. This method of debouncing is good for debouncing keyboard inputs. The second method is to continually poll the line and wait for 0 ms to go by without the line changing state. The algorithm that I use for this function is: ButLoop: while (Button High); // Poll Until Button is Pressed for (Dlay 0; (Dlay 0msec) and (Button Low); Dlay ); if (Dlay! 0 msec) // Repeat Process if 0 msecs have goto ButLoop; // Not gone by with Button Pressed This code will wait for the button to be pressed and then poll it continuously until either 0 ms has passed or the switch has gone high again. If the switch goes high, the process is repeated until it is held low for 0 ms. This method is well suited to applications that don t have interrupts, only have one button input, and have no need for processing while polling the button. As restrictive as it sounds, many applications fit these criteria. This method can also be used with interrupt inputs along with TMR0 in the PICmicro MCU, which eliminates these restrictions. The interrupt handler behaves like the following pseudo-code when one of the port changes on interrupt bits is used for the button input: interrupt ButtonDebounce() // Set Flags According to the { // Debounced State of the Button if (T0IF ) { // TMR0 Overflow, Button Debounced T0IF 0; T0IE 0; // Reset and Turn off TMR0 Interrupts if (Button High) { Pressed 0; NotPressed 0; // Set the State of the Button } else { Pressed ; NotPressed 0; Figure 6-4 bounce Polling to eliminate

102 MATRIX KEYPADS 67 Figure 6-5 Debounced switch using a Schmidt Trigger } } else { // Port Change Interrupt NotPressed ; // Nothing True RBIF 0; // Reset the Interrupt TMR0 0msecDlay; // Reset Timer 0 for 0 ms T0IF 0; T0IE ; // Enable the Timer Interrupt } } // End ButtonDebounce This code waits for the input pin to change state and then resets the two flags that indicate the button state and starts TRM0 to request an interrupt after 0 ms. After a port change interrupt, notice that I reset the button state flags to indicate to the mainline that the button is in a transition state and is not yet debounced. If TMR0 overflows, then the button is polled for its state and the appropriate button state flags are set and reset. The mainline code should poll the Pressed and NotPressed flags when it is waiting for a specific state. Chapter 5 shows this method of using TMR0 and how interrupts can be implemented with or without interrupts. If you don t want to use the software approaches, you can use a capacitor to filter the bouncing signal and pass it into a Schmidt trigger input. Schmidt trigger inputs have different thresholds, depending on whether the signal is rising or falling. For rising edges, the trigger point is higher than falling. Schmidt trigger inputs have the hysteresis symbol put in the buffer (Fig. 6-5). This method is fairly reliable, but requires an available Schmidt trigger gate in your circuit. A Schmidt trigger input might be available in your PICmicro MCU, but check the data sheet to find out which states and peripheral hardware functions can take advantage of it. Lastly, choose buttons with a positive click when they are pressed and released. These have reduced bouncing, often have a self cleaning feature to reduce poor contacts, and are a lot easier to work with than other switches that don t have this feature. I have used a number of switches over the years that don t have this click and they can be a real problem in circuits with intermittent connections and unexpected bouncing that occurs while the button is pressed and held down. Matrix Keypads Switch matrix keyboards and keypads are really just an extension of the button concepts, with many of the same concerns and issues to watch out for. The big advantage that the matrix keyboards gives you is that they provide a large number of button inputs for a rel-

103 68 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Figure 6-6 x switch matrix atively small number of PICmicro MCU pins. The PICmicro MCU is well designed for simply implementing switch matrix keypads, which, like LCD displays that are explained in the next section, can add a lot to your application with a very small investment in hardware and software. A switch matrix is simply a two-dimensional matrix of wires, with switches at each vertex. The switch is used to interconnect rows and columns in the matrix (Fig. 6-6). This diagram might not look like the simple button, but it will become more familiar when I add switchable ground connections on the columns (Fig. 6-7). In this case, by connecting one of the columns to ground, if a switch is closed, the pull down on the row will connect the line to ground. When the row is polled by an I/O pin, a 0 or low voltage will be returned instead of a (which is what will be returned if the switch in the row that is connected to the ground is open). As stated, the PICmicro MCU is well suited to implement switch matrix keyboards with PORTB s internal pull-ups and the ability of the I/O ports to simulate the open-drain pull-downs of the columns (Fig. 6-8). Normally, the pins connected to the columns are left in tristate (input) mode. When a column is being scanned, the column pin is output enabled driving a 0 and the four input bits are scanned to see if any are pulled low. In this case, the keyboard can be scanned for any closed switches (buttons pressed) using the code: int KeyScan() // Scan the Keyboard and Return when a { // key is pressed int i 0; int key ; while (key ) { for (i 0; (i 4) & ((PORTB & 0x00F) 0x0F0); i ); Figure 6-7 Switch matrix with pull down transistors

104 MATRIX KEYPADS 69 Figure 6-8 to PORTB 4x4 switch matrix connected switch (PORTB & 0x00F) { // Find Key that is Pressed case 0x00E: // Row 0 key i; break; case 0x00D: // Row case 0x00C: key 0x04 i; break; case 0x00B: // Row case 0x00A: case 0x009: case 0x008: key 0x08 i; break; else // Row3 key 0x0C i; break; }//end switch }// end while return key; } // End KeyScan The KeyScan function will only return when a key has been pressed. This routine will not allow keys to be debounced or for other code to execute while it is running. These issues can be resolved by putting the key scan into an interrupt handler, which executes every 5 ms: Interrupt KeyScan( ) { // 5 msec Interval Keyboard Scan int i 0; int key for (i 0; (i 4) & ((PORTB & 0x00F) 0x00F)); i ); if (PORTB & 0x00F)! 0x00F) { // Key Pressed switch (PORTB & 0x00F) { // Find Key that is Pressed case 0x00E: // Row 0 key i;

105 70 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING break; case 0x00D: // Row case 0x00C: key 0x04 i; break; case 0x00B: // Row case 0x00A: case 0x009: case 0x008: key 0x08 i; break; else // Row3 key 0x0C i; break; }//end switch if (key KeySave) { keycount keycount ; // Increment Count // -- Put in Auto Repeat Code Here if (keycount 4) keyvalid key; // Debounced Key } else keycount 0; // No match Start Again KeySave key; // Save Current key for next 5 msec } // Interval }// End KeySave This interrupt handler will set the keyvalid variable to the row/column combination of the key button (which is known as a scan code) when the same value comes up four times in a row. This for time scan is the debounce routine for the keypad. If the value doesn t change for four intervals (0 ms in total), the key is determined to be debounced. There are two things to notice about this code. First, in both routines, I handle the row with the highest priority. If multiple buttons are pressed, then the one with the highest bit number will be the one that is returned to the user. The second point is, this code can have an auto repeat function added to it very easily. To do this, a secondary counter has to be first cleared and then incremented each time the keycount variable is four or greater. To add an auto repeat key every second (00 intervals), the following code is added in the interrupt handler at the comment. if (keycount 4) { keyrepeat keyrepeat ; // Decrement the Key Auto Repeat Value if (keyrepeat 0) { keyrepeat 00; // Restart the second Auto Repeat Count keycount 3; // Reset the counter keyvalid key; // Return the key } } else // Reset the Auto Repeat Counter keyrepeat ; // End Outputting the Value with Auto // Repeat The code and methodology for handling switch matrix keypad scans I ve outlined here probably seems pretty simple. I m sure you ll be surprised that, with a scanned keyboard, it is most difficult to figure out the scan codes for specific keys and how to wire the keyboard. Chapter 5 demonstrates how this can be done.

106 LCDs 7 LCDs LCDs can add a lot to your application in terms of providing a useful interface for the user, debugging an application, or just giving it a professional look. The most common type of LCD controller is the Hitachi 44780, which provides a relatively simple interface between a processor and an LCD. Using this interface is often not attempted by new designers and programmers because it is difficult to find good documentation on the interface, initializing the interface can be a problem, and the displays themselves are expensive. I have worked with Hitachi based LCDs for a while now and I don t believe any of these perceptions. LCDs can be added quite easily to an application and use as few as three digital output pins for control. As for cost, LCDs can be often pulled out of old devices or found in surplus stores for less than a dollar. The purpose of this section is to give a brief tutorial on how to interface with Hitachi based LCDs. I have tried to provide all of the data necessary for successfully adding LCDs to your application. In the book, I use Hitachi based LCDs for a number of different projects. The most common connector used for the based LCDs is 4 pins in a row, with pin centers 0.00 apart. The pins are wired as in Table 6-. As you would probably guess from this description, the interface is a parallel bus, allowing simple and fast reading/writing of data to and from the LCD. The waveform shown in Fig. 6-9 will write an ASCII byte out to the LCD s screen. The ASCII code to be displayed is eight bits long and is sent to the LCD either four or eight bits at a time. If four-bit mode is used, two nybbles of data (sent high four bits and then low four bits with an E clock pulse with each nybble) are sent to make up a full eight-bit transfer. The E clock is used to initiate the data transfer within the LCD. Sending parallel data as either four or eight bits are the two primary modes of operation. Although there are secondary considerations and modes, deciding how to send the data to the LCD is the most crucial decision to be made for an LCD interface application. TABLE 6 Hitachi Based LCD Pinout PIN DESCRIPTION Ground Vcc 3 Contrast Voltage 4 R/S - Instruction/Register Select 5 R/W - Read/Write LCD Registers 6 E - Clock 7-4 D0-D7 Data Pins

107 7 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Eight-bit mode is best used when speed is required in an application and 0 I/O pins are available. Four-bit mode requires six bits. To wire a microcontroller to an LCD in four-bit mode, just the top four bits (DB4-7) are written to. The R/S bit is used to select whether data or an instruction is being transferred between the microcontroller and the LCD. If the bit is set, then the byte at the current LCD cursor position can be read or written. When the bit is reset, either an instruction is being sent to the LCD or the execution status of the last instruction is read back (whether or not it has completed). The different instructions available for use with the are shown in Table 6-3. The bit descriptions for the different commands are: *Not used/ignored. This bit can be either or 0 Set cursor move direction: ID Increment the cursor after each byte written to display if set S Shift display when byte written to display Enable display/cursor D Turn display on()/off(0) C Turn cursor on()/off(0) B Cursor blink on()/off(0) Move cursor/shift display SC Display shift on()/off(0) RL Direction of shift right()/left(0) Set interface length DL Set data interface length 8()/4(0) N Number of display lines (0)/() F Character font 5x0()/5x7(0) Poll the busy flag BF This bit is set while the LCD is processing Move cursor to CGRAM/display A Address Read/write ASCII to the display H Data Reading data back is best used in applications that require data to be moved back and forth on the LCD (such as in applications that scroll data between lines). The busy flag can be polled to determine when the last instruction that has been sent has completed processing. For most applications, there really is no reason to read from the LCD. I usually tie R/W to ground and just wait the maximum amount of time for each instruction (4. ms for clearing the display or moving the cursor/display to the home position, 60 s for all other commands). As well as making my application software simpler, it also frees up a microcontroller pin for other uses. Different LCDs execute instructions at different rates and to Figure 6-9 waveform LCD data write

108 LCDs 73 TABLE 6 3 Hitachi Based LCD Commands R/S R/W D7 D6 D5 D4 D3 D D D0 INSTRUCTION/DESCRIPTION Pins Clear Display * Return Cursor and LCD to Home Position ID S Set Cursor Move Direction D C B Enable Display/Cursor SC RL * * Move Cursor/Shift Display DL N F * * Reset/Set Interface Length A A A A A A Move Cursor to CGRAM 0 0 A A A A A A A Move Cursor to Display 0 BF * * * * * * * Poll the Busy Flag 0 H H H H H H H H Write Hex Character to the Display at the Current Cursor Position H H H H H H H H Read Hex Character at the Current Cursor Positon on the Display avoid problems later on (such as if the LCD is changed to a slower unit), I recommend just using the maximum delays listed here. In terms of options, I have never seen a 5x0 pixel character LCD display. This means that the F bit in the set interface instruction should always be reset (equal to 0). Before you can send commands or data to the LCD module, the module must be initialized. For eight-bit mode, this is done using the following series of operations:. Wait more than 5 ms after power is applied.. Write 0x030 to LCD and wait 5 ms for the instruction to complete. 3. Write 0x030 to LCD and wait 60 usecs for instruction to complete. 4. Write 0x030 AGAIN to LCD and wait 60 usecs or Poll the Busy Flag. 5. Set the Operating Characteristics of the LCD. - Write Set Interface Length - Write 0x00 to prevent shifting after character write. - Write 0x00 to Clear the Display - Write Set Cursor Move Direction Setting Cursor Behavior Bits - Write Enable Display/Cursor & enable Display and Optional Cursor In describing how the LCD should be initialized in four-bit mode, I specify writing to the LCD in terms of nybbles. This is because initially, just single nybbles are sent (and not two nybbles, which make up a byte and a full instruction). As mentioned, when a byte is sent, the high nybble is sent before the low nybble and the E pin is toggled each time that four bits are sent to the LCD. To initialize in four-bit mode the following nybbles are first sent to the LCD:

109 74 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING. Wait more than 5 ms after power is applied.. Write 0x03 to LCD and wait 5 ms for the instruction to complete. 3. Write 0x03 to LCD and wait 60 usecs for instruction to complete. 4. Write 0x03 AGAIN to LCD and wait 60 usecs (or poll the Busy Flag). 5. Set the Operating Characteristics of the LCD. - Write 0x0 to the LCD to Enable Four Bit Mode All following instruction/data writes require two nybble writes: - Write Set Interface Length - Write 0x0/0x00 to prevent shifting of the display - Write 0x00/0x0 to Clear the Display - Write Set Cursor Move Direction Setting Cursor Behavior Bits - Write Enable Display/Cursor & enable Display and Optional Cursor Once the initialization is complete, the LCD can be written to with data or instructions as required. Each character to display is written like the control bytes, except that the R/S line is set. During initialization, by setting the S/C bit during the Move Cursor/Shift Display command, after each character is sent to the LCD, the cursor built into the LCD will increment to the next position (either right or left). Normally, the S/C bit is set (equal to ), along with the R/L bit in the Move Cursor/Shift Display command for characters to be written from left to right (as with a TeleType video display). One area of confusion is how to move to different locations on the display and, as a follow on, how to move to different lines on an LCD display. Table 6-4 shows how different LCD displays that use a single can be set up with the addresses for specific character locations. The LCDs listed are the most popular arrangements available and the layout is given as number of columns by number of lines. The ninth character is the position of the ninth character on the first line. Most LCD displays have a and support chip to control the operation of the LCD. The is responsible for the external interface and provides sufficient control lines for 6 characters on the LCD. The support chip enhances the I/O of the to support up to 8 characters on an LCD in two lines of eight. From Table 6-4, it should be noted that the first two entries (8x, 6x) only have the and not the support chip. This is why the ninth character in the 6x does not appear at address 8 and shows up at the address that is common for a two-line LCD. I ve included the 40 character by 4 line (40x4) LCD because it is quite common. Normally, the LCD is wired as two 40x displays. The actual connector is normally 6 bits wide with all the 4 connections of the in common, except for the E (strobe) pins. The E strobes are used to address between the areas of the display used by the two devices. The actual pinouts and character addresses for this type of display can vary between manufacturers and display part numbers. When using any kind of multiple LCD display, you should probably only display one s cursor at a time to avoid confusing the user. Cursors for the can be turned on as a simple underscore at any time using the Enable Display/Cursor LCD instruction and setting the C bit. I don t recommend using the B (Block mode) bit because this causes a flashing full-character square to be displayed and it is very annoying. The LCD can be thought of as a TeleType display because in normal operation, after a character has been sent to the LCD, the internal cursor is moved one character to the right. The clear display and return cursor and LCD to home position instructions are used to reset the cursor s position to the top right character on the display.

110 LCDs 75 TABLE 6 4 Hitachi Based LCD Types and Character Locations LCD TOP LEFT NINTH SECOND LINE THIRD LINE FOURTH LINE COMMENTS 8x 0 N/A N/A N/A N/A Note. 6x 0 0x040 N/A N/A N/A Note. 6x 0 8 N/A N/A N/A Note 3. 8x 0 N/A 0x040 N/A N/A Note. 0x 0 0x008 0x040 N/A N/A Note. 6x 0 0x008 0x040 N/A N/A Note. 0x 0 0x008 0x040 N/A N/A Note. 4x 0 0x008 0x040 N/A N/A Note. 30x 0 0x008 0x040 N/A N/A Note. 3x 0 0x008 0x040 N/A N/A Note. 40x 0 0x008 0x040 N/A N/A Note. 6x4 0 0x008 0x040 0x00 0x050 Note. 0x4 0 0x008 0x040 0x04 0x054 Note. 40x4 0 N/A N/A N/A N/A Note 4. Note : Single 44780/No Support Chip. Note : with Support Chip. Note 3: with Support Chip. This is quite rare. Note 4: Two 44780s with Support Chips. Addressing is device specific. An example of moving the cursor is shown in Fig To move the cursor, the move cursor to display instruction is used. For this instruction, bit 7 of the instruction byte is set with the remaining seven bits used as the address of the character on the LCD the cursor is to move to. These seven bits provide 8 addresses, which matches the maximum number of LCD character addresses available. Table 6-4 should be used to determine the address of a character offset on a particular line of an LCD display. The character set available in the is basically ASCII. I say basically because some characters do not follow the ASCII convention fully (probably the most significant Figure 6-0 cursor Moving an LCD

111 76 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Figure 6- LCD character set difference is 0x05B or is not available). The ASCII control characters (0x008 to 0x0F) do not respond as control characters and might display funny (Japanese) characters. The LCD character set is shown in Fig. 6-. Eight programmable characters are available and use codes 0x000 to 0x007. They are programmed by pointing the LCD s cursor to the character generator RAM (CGRAM) area at eight times the character address. The next eight bytes written to the RAM are the line information of the programmable character, starting from the top (Fig. 6-). I like to represent this as eight squares by five. Most displays were seven pixels by five for each character, so the extra row may be confusing. Each LCD character is actually eight pixels high, with the bottom row normally used for the underscore cursor. The bottom row can be used for graphic characters, although if you are going to use a visible underscore cursor and have it at the character, I recommend that you don t use this line at all (i.e., set the line to 0x000). Using this box, you can draw in the pixels that define your special character and then use the bits to determine what the actual data codes are. When I do this, I normally use a Figure 6- LCD character box

112 LCDs 77 Figure 6-3 Example LCD custom character piece of graph paper and then write hex codes for each line, as shown in the lower right diagram of a Smiley Face (Fig. 6-3). For some the animate applications, I use character rotation for the animations. This means that, instead of changing the character each time the character moves, I simply display a different character. Doing this means that only two bytes (moving the cursor to the character and the new character to display) have to be sent to the LCD. If animation were accomplished by redefining the characters, then 0 characters would have to be sent to the LCD (one to move into the CGRAM space, the eight defining characters and an instruction returning to display RAM). If multiple characters are going to be used or more than eight pictures for the animation, then you will have to rewrite the character each time. The user-defined character line information is saved in the LCD s CGRAM area. This 64 bytes of memory is accessed using the move cursor into CGRAM instruction in a similar manner to that of moving the cursor to a specific address in the memory with one important difference. This difference is that each character starts at eight times its character value. This means that user-definable character 0 has its data starting at address 0 of the CGRAM, character starts at address 8, character starts at address 0x00 (6), etc. To get a specific line within the user-definable character, its offset from the top (the top line has an offset of 0) is added to the starting address. In most applications, characters are written to all at one time with character 0 first. In this case, the instruction 0x040 is written to the LCD, followed by all of the user-defined characters. The last aspect of the LCD to discuss is how to specify a contrast voltage to the display. I typically use a potentiometer wired as a voltage divider. This will provide an easily variable voltage between ground and V cc, which will be used to specify the contrast (or darkness) of the characters on the LCD screen. You might find that different LCDs work differently with lower voltages providing darker characters in some and higher voltages do the same thing in others. There are a variety of different ways of wiring up an LCD. I noted that the could interface with four or eight bits. To simplify the demands in microcontrollers, a shift register is often used to reduce the number of I/O pins to three. This can be further reduced by using the circuit shown in which the serial data is combined with the contents of the shift register to produce the E strobe at the appropriate in- Figure 6-4 LCD contrast voltage circuit

113 78 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Figure 6-5 interface wire LCD terval. This circuit ANDs (using the -K resistor and IN94 diode) the output of the sixth D-flip-flop of the 74LS74 and the data bit from the device writing to the LCD to form the E strobe. This method requires one less pin than the three-wire interface and a few more instructions of code. The two-wire LCD interface circuit is shown in Fig I normally use a 74LS74 wired as a shift register (as shown in the schematic diagram) instead of a serial-in/parallel-out shift register. This circuit should work without any problems with a dedicated serial-in/parallel-out shift register chip, but the timing/clock polarities might be different. When the 74LS74 is used, notice that the data is latched on the rising (from logic low to high) edge of the clock signal. Figure 6-6 is a timing diagram for the two-wire interface and it shows the 74LS74 being cleared, loaded, and then the E strobe when the data is valid and 6Q and incoming data is high. Figure 6-6 wire LCD write waveform

114 ANALOG I/O 79 The right side of this diagram shows how the shift register is written to for this circuit to work. Before data can be written to it, loading every latch with zeros clears the shift register. Next, a (to provide the E gate) is written followed by the R/S bit and the four data bits. Once the latch is loaded in correctly, the data line is pulsed to strobe the E bit. The biggest difference between the three-wire and two-wire interface is that the shift register has to be cleared before it can be loaded and the two-wire operation requires more than six times the number of clock cycles to load four bits into the LCD. I ve used this circuit with the PICmicro MCU, Basic Stamp, 805, and AVR, and it really makes the wiring of an LCD to a microcontroller very simple. The biggest issue to watch for is to ensure the E strobe s timing is within specification (i.e., greater than 450 ns); the shift register loads can be interrupted without affecting the actual write. This circuit will not work with open-drain only outputs (something that catches up many people). One note about the LCD s E strobe is that in some documentation it is specified as highlevel active; in others, it is specified as falling-edge active. It seems to be falling-edge active, which is why the two-wire LCD interface works even if the line ends up being high at the end of data being shifted in. If the falling edge is used (like in the two-wire interface) then ensure that before the E line is output on 0, there is at least a 450-ns delay with no lines changing state. Analog I/O Before reading through the following sections, I suggest that you familiarize yourself with Analog-to-Digital Converters (ADCs) and Digital-to-Analog Converters (DACs) in Introduction to Electronics on the CD-ROM. These sections will introduce you to the theory of converting analog voltages and digital values between each other and the problems that can arise with them. The following sections introduce you to some of the practical aspects of working with analog data with the PICmicro MCU. This includes position sensing using potentiometers. At first glance, you might think that an ADC-equipped microcontroller is required for this operation, but there are a number of ways of doing this with strictly digital inputs. The IBM PC carries out the same function (it doesn t use an ADC either) for reading joystick positions. For analog output, I focus on the theory and operation behind Pulse-Width Modulated (PWM) analog control signals. This method of control is very popular and is a relatively simple way of providing analog control of a device. It can also be used to communicate analog values between devices without needing any type of communication protocol. The PICmicro MCU has some built-in hardware that makes the implementation of pulsewidth-modulated input and output quite easy to work with. I want to make it clear that audio input and output capabilities cannot be provided in the PICmicro MCU without significant front-end signal processing and filtering. Output from the PICmicro MCU can be simple beeps and boops without special hardware, but anything more complex will require specialized hardware and software. POTENTIOMETERS One of the more useful human input devices is the dial. Rather than relying on some kind of digital data, like a button or character string, the dial allows users a freer range of inputs,

115 80 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING as well as positional feedback information in a mechanical device. For most people, reading a potentiometer value requires setting the potentiometer as a voltage divider and reading the voltage between the two extremes at the wiper (Fig. 6-7). A very elegant way of reading a potentiometer s position using the digital input of a PICmicro MCU is shown in this section. Notice that I consider the measurement to be of the potentiometer s position and not its resistance. This is an important semantic point; as far as using a potentiometer as an input device, I do not care about the actual resistance of its position, just what its position is. The method of reading a potentiometer s position using a digital I/O pin that I am going to show you is very dependent on the parts used and will vary significantly between implementations. The method of reading a potentiometer uses the characteristics of charged capacitor discharging through a resistor. If the charge is constant in the capacitor, then the time to discharge varies according to the exponential curve shown in Fig The charge in a capacitor is proportional with its voltage. If a constant voltage (i.e., from a PICmicro MCU I/O pin) can be applied to a capacitor, then its charge will be constant. This means that in the voltage discharge curve shown in Fig. 6-8, if the initial voltage is known along with the capacitance and resistance, then the voltage at any point in time can be predicted. The equation in Fig. 6-8: V (t) V Start ( e ** t/rc) can be reworked to find R, if V, V Start,t,and C are known: R t/c * ln[(v Start V)/V Start ] Figure 6-7 Potentiometer input to PICmicro MCU ADC Rather than calculate the value through, you can make the approximation of ms for a resistance of 0 k and a capacitance of 0. F with a PICmicro MCU, which has a high-tolow threshold of.5 volts. To measure the resistance in a PICmicro MCU, I use the circuit shown in Fig For this circuit, the PICmicro MCU s I/O pin outputs a high, which charges the capacitor (which is limited by the potentiometer). After the capacitor is charged, the pin is changed to input, the charge in the capacitor draws through the resistor with a voltage determined by the V (t) formula. When the pin first changes state, the voltage across the resistor will be greater than the threshold for some period of time. When the voltage across the potentiometer falls below the voltage threshold, the input pin value returned to the software will be zero. If the time required for Figure 6-8 delay Measure RC time

116 ANALOG I/O 8 Figure 6-9 PICmicro MCU measure of RC time delay voltage across the pin to change from reading of to a 0 is recorded, it will be proportional to the resistance between the potentiometer s wiper and the capacitor. The pseudo code for carrying out the potentiometer read is: int ReadPot() // Return the Potentiometer s Position { int i; pin output; pin ; // Charge the Capacitor for (i 0; i charge; i ); pin input; // Let the Capacitor Discharge for ( i 0; pin ; i ); return I ; } // End ReadPot The PICmicro MCU assembly code for implementing this potentiometer read is not much more complex than this pseudo code. Later, the book provides some examples of how potentiometer reads are actually accomplished. The 00-Ohm resistor between the PICmicro MCU pin and the RC network is used to prevent any short circuits to ground if the potentiometer is set so that no resistance is in the circuit when the capacitor is changed. This method of reading a potentiometer s position is very reliable, but not very accurate, nor is it particularly fast. When setting this up for the first time, in a specific circuit, you will have to experiment to find the actual range that it will display. This is because of part variances (including the PICmicro MCU) and the power supply characteristics. For this reason, I do not recommend using the potentiometer/capacitor circuit in any products. Tuning the values returned will be much more expensive than the costs of a PICmicro MCU with a built-in ADC. PULSE-WIDTH MODULATION (PWM) I/O The PICmicro MCU, like most other digital devices, does not handle analog voltages very well. This is especially true for situations where high-current voltages are involved. The best way to handle analog voltages is by using a string of varying wide pulses to indicate the actual voltage level. This string of pulses is known as a Pulse-Width-Modulated (PWM) analog signal and it can be used to pass analog data from a digital device, control DC devices, or even output an analog voltage. This section covers PWM signals and how they can be used with the PICmicro MCU. In the discussion of TMR and TMR, earlier in the book, I presented how PWM signals are implemented and read using the CCP built-in hardware of the PICmicro MCU. This

117 8 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Figure 6-30 Pulse wave modulated signal waveform section shows how PWM signals can be used for I/O in PICmicro MCUs that do not have the CCP module built in. A PWM signal (Fig. 6-30) is a repeating signal that is on for a set period of time that is proportional to the voltage that is being output. I call the on time the pulse width in Fig The duty cycle is the percentage of time that the on time is relative to the PWM signal s period. To output a PWM signal, the following code is used: Period PWMPeriod; On PWMperiod - PWMoff; // Initialize the Output // Parameters while ( ) { PWM ON; for (i 0; i On; i ); PWM off; For ( ; i PWMPeriod; i ); } // end while // Start the Pulse // Output ON for On Period of // Time // Turn off the Pulse // Output off for the rest of the // PWM Period This code can be implemented remarkably simply in the PICmicro MCU, but rather than showing it, there is one aspect I want to change. This method is not recommended because it uses all the processor resources of the PICmicro MCU and does not allow for any other processing. To avoid this problem, I would recommend using the TMR0 interrupt as: Interrupt PWMOutput() // When Timer Overflows, Toggle On and Off { // and Reset Timer to the correct delay for // the Value if (PWM ON) { // If PWM is ON, Turn it off and Set Timer PWM off; // Value TMR0 PWMPeriod - PWMOn; } else { // If PWM is off, Turn it ON and Set Timer PWM ON; // Value TMR0 PWMOn; } // end if INTCON.T0IF 0; // Reset Interrupts } // End PWMOutput TMR0 Interrupt Handler This code is quite easy to port to PICmicro MCU assembly language. For example, if the PWM period was ms (executing in a 4-MHz PICmicro MCU), a divide-by-four prescaler value could be used with the timer and the interrupt-handler assembly-language code would be:

118 ANALOG I/O 83 org 4 Int movwf _w movf STATUS, w movwf _status btfsc PWM goto PWM_ON nop bsf PWM movlw 6 6 subwf PWMOn, w goto PWM_Done PWM_ON bcf PWM movf PWMOn, w sublw 6 6 goto PWM_Done PWM_Done sublw 0 movwf TMR0 bcf INTCON, T0IF movf _status, w movwf STATUS swapf _w, f swapf _w, w retfie ; Interrupt Handler ; Save Context Registers ; - Assume TMR0 is the only enabled Interrupt ; Is PWM O/P Currently High or Low? ; Low - Nop to Match Cycles with High ; Output the Start of the Pulse ; Get the PWM On Period ; Add to PWM to Get Correct Period for ; Interrupt Handler Delay and Missed cycles ; in maximum 04 usec Cycles ; PWM is On - Turn it Off ; Output the Low of the PWM Cycle ; Calculate the Off Period ; Subtract from the Period for the Interrupt ; Handler Delay and Missed cycles in maximum ; 04 usec Cycles ; Have Finished Changing the PWM Value ; Get the Value to Load into the Timer ; Reset the Interrupt Handler ; Restore the Context Registers In this code, TMR0 is loaded in such a way that the PWM s period is always ms (a count of 50 ticks with the prescaler value of four). To get the value added and subtracted from the total, I first took the difference between the number of ticks to get ms (50) and the full timer range (56). Next, I counted the total number of instruction cycles of the interrupt handler (which is 3), divided it by four, and added the result to the -ms difference. The operation probably seems confusing because I was able to optimize the time for the PWM signal off: to: Time Off Period - ON movf ON, w sublw 6 6 sublw 0 movwf TMR0 I realize that this doesn t make any sense the first time you look at it, so I go through it by showing how it works.

119 84 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Using the original equation, you should note that this calculates the number of cycles to be delayed by TMR0, but the actual value to be loaded into TMR0 is calculated as: TMR0 Delay Value 0x000 - (Time Off) 0x000 - (Period ON) 0x000 - (56 50 Interrupt Execution- ON) 0x000 - (6 6 ON) 0x000 - ( ON) 0x000 - ON 0x00F4 ON Going back to the three instructions that load TMR0, you can show that they execute as: movf ON, w sublw 6 6 ; w ON ; w w ; - ON ; 0x0FF ON ; 3 0x0FF ON sublw 0 ; w 0 - w ; 0 - (3 0x0FF ON) ; 0 0x0FF (3 0x0FF ON) ; 0x0FF 3 0x0FF 0x0FF ON ; 0x0FF 3 ON ; 0x0F4 ON which is (surprisingly enough) the same result as what was found with the TMR0 delay value equation. The formula in itself is not that impressive, except that it dovetails very well with the PWM on half of the code. The process of coming up with this code probably belongs in another chapter on optimization, but to be honest with you, I came up with it using nothing but trial and error along with the feeling that this kind of optimization was possible. This is an example of what I mean when I say that you should look for opportunities when processing data in the PICmicro MCU. More often than not, you will come up with something like these few instructions, which are very efficient, and integrate different cases startlingly well. Notice that, in this code, the PWM signal will never fully be on (a high DC voltage) or fully off (a ground-level DC voltage). This is because when the routine enters the subroutine handler, it changes the output, regardless of whether or not it is required for the length of the interrupt handler. In actuality, if you time it out, you will see that the 3 instruction cycles that the interrupt handler takes between changing the value works out to a.4- percent loss of full on and full off. This should not be significant in most applications and will serve as a heartbeat to let the receiver know the PICmicro MCU is still functioning even though the output is stuck at an extreme. In this example, I have expended quite a bit of energy to ensure that the period remains the same, regardless of the on time. This was done to ensure that the changes in the duty cycle remained proportional to the changes in the on period. This is important if the PWM output is going to be passed through a low-pass filter (Fig. 6-3) to output an analog voltage. Figure 6-3 Pulse width modulated analog voltage

120 ANALOG I/O 85 In many applications where a PWM signal is communicating with another digital device, this effort to ensure that the period is constant and is not required. In these cases, a timer is used to time the on period. This can be shown as the pseudo-code: Int TimeOn() { int i 0; while (PWMIP off); for ( ; PWMIP ON; i ); return i; } // end TimeOn // Time the Width of an incoming Pulse // Wait for the Pulse to Start // Time the Pulse Width // Return the Pulse Width With the actual PICmicro MCU assembly-language code being quite simple, but dependent on the maximum pulse width value being timed, very long pulses will require large counters or delays in between the PWM input (PWMIP in TimeOn) poll. Passing analog data back and forth between digital devices in any format is not going to be accurate because of the errors in digitizing the value and restoring it. This is especially true for PWM signals, which can have very large errors because of the sender and receiver not being properly synched and the receiver not starting to poll at the correct time interval. In fact, the measured value could have an error of upwards of 0 percent from the actual value. This loss of data accuracy means that the analog signals should not be used for data transfers. But, as is shown in Chapters 5 and 6, PWM signals are an excellent way to control analog devices, such as lights and motors. When using a PWM to drive an analog device, it is important to be sure that the frequency is faster than what a human can perceive. As noted in the LED section, this frequency is 30 Hz or more. But for motors and other devices that might have an audible whine, the PWM signal should have a frequency of 0 khz or more to ensure that the signal does not bother the user. In Chapter 6, I discuss this in more detail and demonstrate how an audible 0 KHz whine can be produced. The problem with the higher frequencies is that the granularity of the PWM signal decreases. This is because of the inability of the PICmicro MCU (or what ever digital device is driving the PWM output) to change the output in relatively small time increments from on to off, relative to the size of the PWM signal s period. In the previous example code, four instruction cycles (of s each) are the lowest level of granularity for the PWM signal that results in about 50 unique output values. If the PWM signal s period was decreased to 00 s, from ms, for a 0-kHz frequency, the same code would only have 5 or so unique output values that could be output. In this case, to retain the original code s granularity, the PICmicro MCU would have to be sped up 0 times (not possible for most applications) or another way of implementing the PWM will have to be found. AUDIO OUTPUT When I was originally blocking out this book, I wanted to include PICmicro MCU audio output and input. After some experimentation and a search on the Internet to see what other people have done (or not done, as in the case of audio input to the PICmicro MCU), I have come to the conclusion that audio input is not appropriate for the PICmicro MCU. The PICmicro MCU could have some kind of filtering input, but it simply does not have

121 86 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING the processing capability to do more than respond to a specific frequency at a threshold volume. For this reason, I would discourage you from passing audio input to the PICmicro MCU and just use the PICmicro MCU to provide audio output using the techniques outlined in this section. When I discuss the PICmicro MCU s processing capabilities with regard to audio, I tend to be quite disparaging. The reason for this is the lack of hardware multipliers in the low-end and mid-range PICmicro MCUs and the inability of all the devices to natively handle greater than eight bits of in a floating-point format. The PICmicro MCU processor has been optimized to respond to digital inputs and cannot implement the real-time processing routines needed for complex analog I/O. Despite this, you can implement some surprisingly sophisticated audio output that goes beyond simple beeps and boops (Fig. 6-3). The circuit in Fig. 6-3 passes DC waveforms through the capacitor (which filters out the kickback spikes) to the speaker or piezo buzzer. When a tone is output, your ear will hear a reasonably good tone, but if you were to look at the actual signal on an oscilloscope, you would see the waveform shown in Fig. 6-33, both from the PICmicro MCU s I/O pin and the piezo buzzer itself. The PICmicro MCU pin, capacitor, and speaker are actually a quite complex analog circuit. Notice that the voltage output on the I/O pin is changed from a straight waveform. This is because of the inductive effects of the piezo buffer. The important thing to note in Fig is that the upward spikes appear at the correct period for the output signal. Timing the output signal is generally accomplished by toggling an output pin at a set period within the TMRO interrupt handler. To generate a -khz signal shown in a PICmicro MCU running a 4 MHz, you can use the code (which does not use the prescaler) for TMR0 and the PICmicro MCU s interrupt providing the speaker charges are in the background. org 4 int movwf _w ; Save Context Registers bcf INTCON, TOIF ; Reset the Interrupt movlw 56 - (50-4) movwf TMRO ; Reset TMR0 for another 500 usecs btfsc SPKR ; Toggle the Speaker goto $ bsf SPKER ; Speaker Output High goto $ bcf SPKER ; Speaker Output Low swapf _w, f ; Restore Context Registers swapf _w, w retfie Figure 6-3 Circuit for driving PICmicro MCU audio

122 ANALOG I/O 87 Figure 6-33 PICmicro MCU driving a speaker output There are two points to notice about this interrupt handler. First, I don t bother saving the STATUS register s contents because neither the zero, neither carry nor digit carry flags are changed by any of the instructions used in the handler. The second point to notice is the reload value of TMRO to generate a -khz output in a 4-MHz PICmicro MCU (an instruction clock period of s), I have to delay 500 cycles for the wave s high and low. Because TMRO has a divide-by-two counts on its input, I have to wait a total of 50 ticks. When I record TMRO, notice that I also take into account the cycles taken to get to the reload (which is seven or eight), divide them by two and take them away from the reload value. For this handler, the reload value might be off by one cycle, depending on how the mainline executes, for a worst-case error of 0.% (,000 ppm). This level of accuracy is approximately the same as what you would get for a ceramic resonator; so, the actual frequency should not be off an appreciable amount from the expected. This level of accuracy will not cause noticeable warbling (changes in the frequency) caused by the changing interrupt latency as you run the application. The actual changes are very small and not detectable by the human ear. When developing applications that output audio signals, I try to keep the tone within the range of 500 Hz to khz. This is well within the range of human hearing and is quite easy to implement in a PICmicro MCU. When you look at the Christmas tree project in Chapter 6, you can see how this is done to create simple tunes on the PICmicro MCU. I wanted to finish off this section by describing how the PICmicro MCU can create more complex sounds, such as telephone TouchTone audio signals. The problem with TouchTones is that they are a combination of two frequencies (that are listed in the appendices). When they re added together, you get a signal like the bottom one shown in Fig This signal is very hard to replicate with a digital circuit. If you want to create a complex waveform like this, I recommend mixing two PICmicro MCU-controlled frequency outputs together or using a chip that is designed for the specific purpose that you have in mind. The Parallax Basic Stamp II and PicBasic Pro do have instructions that allow you to drive telephone TouchTones, but they require a filter circuit to work properly. I have found that even with the filter, the phone system does not recognize the data being sent very reliably.

123 88 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Relays and Solenoids Figure 6-34 output Mixed audio Some real-life devices that you might have to control by a microcontroller are electromagnetic, such as relays, solenoids, and motors. These devices cannot be driven directly by a microcontroller because of the current required and the noise generated by them. This means that special interfaces must be used to control electromagnetic devices. The simplest method to control these devices is to just switch them on and off and by supplying power to the coil in the device. The circuit shown in Fig is true for relays (as shown), solenoids (which are coils that draw an iron bar into them when they are energized), or a DC motor (which will only turn in one direction). In this circuit, the microcontroller turns on the Darlington transistor pair, causing current to pass through the relay coils, closing the contacts. To open the relay, the output is turned off (or a 0 is output). The shunt diode across the coil is used as a kick-back suppressor. When the current is turned off, the magnetic flux in the coil will induce a large back EMF (voltage), which must be absorbed by the circuit or a voltage spike will occur, which can damage the relay power supply and even the microcontroller. This diode must never be forgotten in a circuit that controls an electromagnetic device. The kick-back voltage is usually on the order of several hundred volts for a few nanoseconds. This voltage causes the diode to breakdown and allows current to flow, attenuating the induced voltage which can damage the PICmicro MCU and other electronic devices in the application circuit. Figure 6-35 relay control Microcontroller

124 DC AND STEPPER MOTORS 89 Figure 6-36 ULN003A driver array Rather than designing discrete circuits to carry out this function, I like to use integrated chips for the task. One of the most useful devices is the ULN003A (Fig. 6-36) or the ULN803 series of chips, which have Darlington transistor pairs and shunt diodes built in for multiple drivers. DC and Stepper Motors Motors can be controlled by exactly the same hardware as shown in the previous section, but as I noted, they will only run in one direction. A network of switches (transistors) can be used to control turning a motor in either direction; this is known as an H-bridge (Fig. 6-37). In this circuit, if all the switches are open, no current will flow and the motor won t turn. If switches and 4 are closed, the motor will turn in one direction. If switches and 3 are closed, the motor will turn in the other direction. Both switches on one side of the bridge should never be closed at the same time because this will cause the motor power supply will burn out or a fuse will blow because a short circuit is directly between the motor power and ground. Controlling a motor s speed is normally done by pulsing the control signals in the form of a PWM signal, as shown previously in this chapter (Fig. 6-30). This will control the average power delivered to the motors. The higher the ratio of the pulse width to the period (the duty cycle), the more power delivered to the motor. Figure 6-37 H bridge motor driver

125 90 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Figure 6-38 driver 93D H bridge motor The frequency of the PWM signal should be greater than 0 khz to prevent the PWM from producing an audible signal in the motors as the field is turned on and off. Like the ULN003A simplified the wiring of a relay control, the 93D (Fig. 6-38) or 98 chips can be used to control a motor. The 93D chip can control two motors (one on each side) connected to the buffer outputs (pins 3, 6,, and 4). Pins, 7, 0, and 5 are used to control the voltage level (the switches in the H-bridge diagram) of the buffer outputs. Pins and 9 are used to control whether or not the buffers are enabled. The buffer controls can be PWM inputs, which make control of the motor speed very easy to implement. Vs is 5 V used to power the logic in the chip and Vss is the power supplied to the motors (anywhere from 4.5 to 36 volts). A maximum of 500 ma can be supplied to the motors. Like the ULN003A, the 93D contains integral shunt diodes. This means that to attach a motor to the 93D, no external shunt diodes are required. In this example circuit, you ll notice that I ve included an optional snubber resistor and capacitor. These two components, wired across the brush contacts of the motor, will help reduce electromagnetic emissions and noise spikes from the motor. In the motor-control circuits that I have built, I have never found them to be necessary. But if you find erratic operation from the microcontroller when the motors are running, you might want to put in the 0.- F capacitor and 5 Ohm ( watt) resistor snubber across the motor s brushes (as shown in the circuit). An issue with using the 93D and 98 motor controller chips and is that they are bipolar devices with a 0.7-volt drop across each driver (.4 to.5 volts for a dual driver circuit, Fig. 6-39). This drop, with the significant amount of current required for a motor, results Figure 6-39 to the 93D Wiring a motor

126 DC AND STEPPER MOTORS 9 Figure 6-40 Stepper motor in a fairly significant amount of power dissipation within the driver. The 93D is limited to amp total output and the 98 is limited to 3 amps. For these circuits to work best, a large heatsink is required. To minimize the problem of heating and power loss, I have more recently been looking at using power MOSFETS to control motors. Later, the book shows how to wire these transistors in a circuit to control a motor. Stepper motors are much simpler to develop control software for than a regular DC motor. This is because the motor is turned one step at a time or can turn at a specific rate (specified by the speed in which the steps are executed). In terms of the hardware interface, stepper motors are a bit more complex to wire and require more current (meaning that they are less efficient), but these are offset by the advantages in software control. A bipolar stepper motor consists of a permanent magnet on the motor s shaft that has its position specified by a pair of coils (Fig. 6-40). To move the magnet and the shafts, the coils are energized in different patterns to attract the magnet. For the motor shown in Fig. 6-40, the following sequence would be used to turn the magnet (and the shaft) clockwise (Table 6-5). In this sequence, coil A attracts the north pole of the magnet to put the magnet in an initial position. Then, coil B attracts the south pole, turning the magnet 90 degrees. This continues on to turn the motor 90 degrees for each step. The output shaft of a stepper motor is often geared down so that each step causes a very small angular deflection (a couple of degrees at most, rather than the 90 degrees in the previous example). This provides more torque output from the motor and greater positional control of the output shaft. A stepper motor can be controlled by something like a 93D (each side driving one coil). But there are also stepper-motor controller chips, such as the UC57. TABLE 6 5 Commands to Move a Stepper Motor STEP ANGLE COIL A COIL B 0 S 90 N 3 80 N 4 70 S 5 360/0 S

127 9 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Figure 6-4 UC57 control of a stepper motor In this chip, a step pulse is sent from the microcontroller along with a specified direction. The INH pin will turn off the output drivers and allow the stepper shaft to be moved manually. The UC57 is capable of outputting bilevel coil levels (which improves efficiency and reduces induced noise), as well as half stepping the motor (which involves energizing both coils to move the magnet/shaft by 45 degrees and not just 90 degrees). These options are specific to the motor/controller used (a bipolar stepper motor can have four to eight wires coming out of it). Before deciding on features to be used, a thorough understanding of the motor and its operation is required. R/C Servo Control Servos designed for use in radio-controlled airplanes, cars, and boats can be easily interfaced to a PICmicro MCU. They are often used for robots and applications where simple mechanical movement is required. This might be surprising because a positional servo is considered to be an analog device. The output of an R/C servo is usually a wheel that can be rotated from 0 to 90 degrees. (some servos can turn from 0 to 80 and others have very high torque outputs for special applications). Typically, they only require 5 V, ground, and an input signal. An R/C servo is an analog device, the input is a PWM signal at digital voltage levels. This pulse is between.0 and.0 ms long and repeats every 0 ms (Fig. 6-4). The length of the PWM pulse determines the position of the servo s wheel. A.0-ms pulse will cause the wheel to go to 0 degrees and a.0-ms pulse will cause the wheel to go to 90 degrees. With the PICmicro MCU s TMR capable of outputting a PWM signal, controlling a servo could be considered very easy, although the TMR output will probably not give you the positional accuracy that you will want. To produce a PWM signal using a PICmicro MCU, I normally use a timer interrupt (set every 8 ms) that outputs a.0- to.0-ms PWM signal using pseudo-code: Interrupt() { int i 0; BitOutput( Servo, ); // Interrupt Handler Code // Output the Signal

128 Serial Interfaces 93 Figure 6-4 waveform Servo PWM for (i 0; i ( msec ServoDlay); i ); BitOutput( Servo, ); for (; i msec; i ); } // End Interrupt Handler // Delay full msecs This code can be easily expanded to control more than one servo (by adding more output lines and ServoDlay variables). This method of controlling servos is also nice because the ServoDlay variables can be updated without affecting the operation of the interrupt handler. The interrupt handler takes two ms out of every 0. Thus, a 0-percent cycle overhead provides the PWM function (and this doesn t change even if more servo outputs are added to the device). Serial Interfaces Most intersystem (or intercomputer) communications are done serially. Thus, a byte of data is sent over a single wire, one bit at a time, with the timing coordinated between the sender and the receiver. The obvious advantage of transmitting data serially is that fewer connections are required. A number of common serial communication protocols are used by microcontrollers. In some devices, these protocols are built into the chip itself, to simplify the effort required developing software for the application. SYNCHRONOUS For synchronous data communications in a microcontroller, a clock signal is sent along with serial data (Fig. 6-43). The clock signal strobes the data into the receiver and the transfer can occur on the rising or falling edge of the clock. A typical circuit, using discrete devices, could be like that shown in Fig This circuit converts serial data into eight digital outputs, which all are available at the same time (When the O/P clock is strobed). For most applications, the second 374 (which Figure 6-43 data waveform Synchronous

129 94 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Figure 6-44 output circuit Synchronous provides the parallel data) is not required. This serial-to-parallel conversion can also be accomplished using serial-to-parallel chips, but I prefer using eight-bit registers because they are generally easier to find than other TTL parts. The two very common synchronous data protocols are Microwire and SPI. These methods of interfacing are used in a number of chips (such as the serial EEPROMs used in the BASIC Stamps). Although the Microwire and SPI standards are quite similar, there are a number of differences. I consider these protocols to be methods of transferring synchronous serial data, rather than microcontroller network protocols because each device is individually addressed (even though the clock/data lines can be common between multiple devices). If the chip select for the device is not asserted, the device ignores the clock and data lines. With these protocols, only a single master can be on the bus. A possible connection of two devices is shown in Fig If a synchronous serial port is built into the microcontroller, the data transmit circuitry might look like that shown in Fig This circuit will shift out eight bits of data. For protocols, such as Microwire, where a start bit is initially sent, the start bit is sent using direct reads and writes to the I/O pins. To receive data, a similar circuit would be used, but data would be shifted into the shift register and then read by the microcontroller. The Microwire protocol is capable of transferring data at up to Mbps. Sixteen bits are transferred at a time. To read 6 bits of data, the waveform looks like that shown in Fig After selecting a chip and sending a start bit, the clock strobes out an eight-bit command byte (labeled OP, OP, A5 to A0 in the previous diagram), followed by (optionally) a Figure 6-45 Synchronous device bus

130 SERIAL INTERFACES 95 Figure 6-46 output Synchronous 6-bit address word transmitted and then another 6-bit word, either written or read by the microcontroller. With a -Mbps maximum speed, the clock is both high and low for 500 ns. Transmitted bits should be sent 00 ns before the rising edge of the clock. When reading a bit, it should be checked 00 ns before the falling edge of the clock. Although these timings will work for most devices, you should understand the requirements of the device being interfaced to. The SPI protocol is similar to Microwire, but with a few differences. SPI is capable of up to 3-Mbps data-transfer rate. The SPI data word size is eight bits. 3 SPI has a hold that allows transmitter to suspend data transfer. 4 Data in SPI can be transferred as multiple bytes, known as blocks or pages. Like Microwire, SPI first sends a byte instruction to the receiving device. After the byte is sent, a 6-bit address is optionally sent, followed by eight bits of I/O. As noted, SPI does allow for multiple byte transfers. An SPI data transfer is shown in Fig The SPI clock is symmetrical (an equal low and high time). Output data should be available at least 30 ns before the clock line goes high and read 30 ns before the falling edge of the clock. When wiring a Microwire or SPI device, you can do a trick to simplify the microcontroller connection; combine the DI and DO lines into one pin. Figure 6-49 is identical to what was shown earlier in this chapter when interfacing the PICmicro MCU into a circuit where there is another driver. In this method of connecting the two devices, when the data pin on the microcontroller has completed sending the serial data, the output driver can be turned off and the microcontroller can read the data coming from the device. The current-limiting resistor between Figure 6-47 Microwire data read

131 96 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Figure 6-48 SPI data write the data pin and DI/DO limits any current flows when both the microcontroller and device are driving the line. IC The most popular form of microcontroller network is IC (Inter-Intercomputer Communications). This standard was originally developed by Philips in the late 70s as a method to provide an interface between microprocessors and peripheral devices without wiring full address, data, and control busses between devices. IC also allows sharing of network resources between processors (which is known as multi-mastering). The IC bus consists of two lines, a clock line (SCL), which is used to strobe data (from the SDA line) from or to the master that currently has control over the bus. Both of these bus lines are pulled up (to allow multiple devices to drive them). An IC-controlled stereo system might be wired as in Fig The two bus lines are used to indicate that a data transmission is about to begin, as well as pass the data on the bus. To begin a data transfer, a master puts a start condition on the bus. Normally, (when the bus is in the idle state, both the clock and data lines are not being driven (and are pulled high). To initiate a data transfer, the master requesting the bus pulls down the SDA bus line, followed by the SCL bus line. During data transmission, this is an invalid condition (because the data line is changing while the clock line is active/high). Each bit is then transmitted to or from the slave (the device the message is being communicated with by the master) with the negative clock edge being used to latch in the data (Fig. 6-5). To end data transmission, the reverse is executed, the clock line is allowed to go high, which is followed by the data line. Data is transmitted in a synchronous (clocked) fashion. The most-significant bit sent first and, after eight bits are sent, the master allows the data line to float (it doesn t drive it low) while strobing the clock to allow the receiving device to pull the data line low as an Figure 6-49 Combining DO & DI

132 SERIAL INTERFACES 97 Figure 6-50 network wiring Example IC Figure 6-5 waveforms IC signals and acknowledgment that the data was received. After the acknowledge bit, both the clock and data lines are pulled low in preparation for the next byte to be transmitted or a stop/start condition is put on the bus. Figure 6-5 shows the data waveform. Sometimes, the acknowledge bit will be allowed to float high even though the data transfer has completed successfully. This is done to indicate that the data transfer has completed and the receiver (usually a slave device or a master, which is unable to initiate data transfer) can prepare for the next data request. The two maximum speeds for IC (because the clock is produced by a master, there really is no minimum speed) are standard mode and fast mode. Standard mode runs at up to 00 kbps and fast mode can transfer data at up to 400 kbps. Figure 6-53 shows the timing specifications for both the standard (Std., 00-kHz data rate) and fast (400-kHz data rate). A command is sent from the master to the receiver in the format shown in Fig The receiver address is seven bits long and is the bus address of the receiver. There is a loose standard to use the most significant four bits are used to identify the type of device; the next three bits are used to specify one-of-eight devices of this type (or further specify the device type). As stated, this is a loose standard. Some devices require certain patterns for the second three bits and others (such as some large serial EEPROMS) use these bits to specify an ad- Figure 6-5 IC data byte transmission

133 98 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Figure 6-53 timing IC signal Figure 6-54 transmission IC data dress inside of the device. As well, there is a ten-bit address standard in which the first four bits are all set and the next bit reset. The last two are the most-significant two bits of the address, with the final eight bits being sent in a following byte. All this means is that it is very important to map out the devices to be put on the bus and all of their addresses.the first four bit patterns in Table 6-6 generally follow this convention for different devices. This is really all there is to IC communication, except for a few points. In some de- TABLE 6 6 Reserved IC Device Type Bit Patterns Reserved Address Voice Synthesizer 00 - PCM Audio Interface Audible Tone Generation 0 - LCD/LED Displays Video Interface 00 - A/D and D/A interfaces 00 - Serial Memory 00 - RF tuning/control 0 - Clock/Calendar - Reserved/Ten Bit Address

134 SERIAL INTERFACES 99 vices, a start bit has to be resent to reset the receiving device for the next command (i.e., in a serial EEPROM read, the first command sends the address to read from and the second reads the data at that address). Note that IC is multi-mastering, which is to say that multiple microcontrollers can initiate data transfers on a single IC bus. This obviously results in possible collisions (which is when two devices attempt to drive the bus at the same time). Obviously, if one microcontroller takes the bus (sends a start condition) before another one attempts to do so, there is no problem. The problem arises when multiple devices initiate the start condition at the same time. Actually, arbitration in this case is really quite simple. During the data transmission, hardware (or software) in both transmitters synchronize the clock pulses so that they match each other exactly. During the address transmission, if a bit that is expected to be a by a master is actually a 0, then it drops off the bus because another master is on the bus. The master that drops off will wait until the stop condition and then re-initiate the message. I realize that this is hard to understand with just a written description. The CAN section shows how this is done with an asynchronous bus, which is very analogous to this situation. A bit-banging IC interface can be implemented in software of the PICmicro MCU quite easily. But, because of software overhead, the fast mode probably cannot be implemented even the standard mode s 00 kbps will be a stretch for most devices. I find that implementing IC in software to be best when the PICmicro MCU is the single master in a network. That way it doesn t have to be synchronized to any other devices or accept messages from any other devices that are masters and are running a hardware implementation of IC that might be too fast for the software slave. ASYNCHRONOUS (NRZ) SERIAL Asynchronous long-distance communications came about as a result of the Baudot teletype. This device mechanically (and, later, electronically) sent a string of electrical signals (now called bits) to a receiving printer. This data packet format is still used today for the electrical asynchronous transmission protocols described in the following sections. With the invention of the teletype, data could be sent and retrieved automatically without having to an operator to be sitting by the teletype all night, unless an urgent message was expected. Normally, the nightly messages could be read in the morning. Before going on, some people get unreasonably angry about the definition and usage of the terms data rate and baud rate. Baud rate is the maximum number of possible data-bit transitions per second. This includes the start, parity, and stop bits at the ends of the data packet shown in Fig. 6-55, as well as the five data bits in the middle. I use the term packet because we are including more than just data (some additional information is in there as well), so character or byte (if there were eight bits of data) are not appropriate terms. This means that for every five data bits transmitted, eight bits in total are transmitted (thus, nearly 40% of the data-transmission bandwidth is lost in teletype asynchronous serial communications). The data rate is the number of data bits that are transmitted per second. For this example, if you were transmitting at 0 baud (which is a common teletype data speed), the actual data rate is bits per second (or, assuming five bits per character, 3.75 characters per second).

135 300 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Figure 6-55 Baudot asynchronous serial data I use the term data rate to describe the baud rate. This means that when I say data rate, I am specifying the number of bits of all types that can be transmitted in a given period of time (usually one second). I realize that this is not absolutely correct, but it makes sense to me to use it in this form and this book is consistent throughout (and I will not use the term baud rate). With only five data bits, the Baudot code could only transmit up to 3 distinct characters. To handle a complete character set, a specific five-digit code was used to notify the receiving teletype that the next five-bit character would be an extended character. With the alphabet and most common punctuation characters in the primary 3, this second data packet wasn t required very often. The data packet diagram shows three control bits. The start bit is used to synchronize the receiver to the incoming data. The PICmicro MCU USART (Universal Synchronous/ Asynchronous Receiver/Transmitter) has an overspeed clock (running at 6 times the incoming bit speed), which samples the incoming data and verifies whether or not the data is valid (Fig. 6-56). When waiting for a character, the receiver hardware polls the line repeatedly at /6-bit period intervals until a 0 (space) is detected. The receiver then waits half a cycle before polling the line again to see if a glitch was detected and not a start bit. Notice that polling occurs in the middle of each bit to avoid problems with bit transitions (if the transmitter s clock is slightly different from the receiver s, the chance of misreading a bit will be minimized). Once the start bit is validated, the receiver hardware polls the incoming data once every bit period multiple times (again, to ensure that glitches are not read as incorrect data). The stop bit was originally provided to give both the receiver and the transmitter some time before the next packet is transferred (in early computers, the serial data stream was created and processed by the computers and not by custom hardware, as in modern computers). The parity bit is a crude method of error detection that was first brought in with teletypes. The purpose of the parity bit is to indicate whether the data was received correctly. An odd Figure 6-56 Reading an asynch data packet

136 SERIAL INTERFACES 30 parity meant that if all the data bits and parity bits set to a mark were counted, then the result would be an odd number. Even parity is checking all the data and parity bits and seeing if the number of mark bits is an odd number. Along with even and odd parity are mark, space, and no parity. Mark parity means that the parity bit is always set to a, space parity is always having a 0 for the parity bit, and no parity is eliminating the parity bit altogether. The most common form of asynchronous serial data packet is 8-N-, which means eight data bits, no parity, and one stop bit. This reflects the capabilities of modern computers to handle the maximum amount of data with the minimum amount of overhead and with a very high degree of confidence that the data will be correct. I stated that parity bits are a crude form of error detection. I said that because they can only detect one bit error (e.g., if two bits are in error, the parity check will not detect the problem). If you are working in a high-induced-noise environment, you might want to consider using a data protocol that can detect (and, ideally, correct) multiple-bit errors. RS-3 In the early days of computing (the 950s), although data could be transmitted at high speed, it couldn t be read and processed and continuously. So, a set of handshaking lines and protocols were developed for what became known as RS-3 serial communications. With RS-3, the typical packet contains seven bits, (which is the number of bits that each ASCII character contained). This simplified the transmission of man-readable text, but made sending object code and data (which were arranged as bytes) more complex because each byte would have to be split up into two nybbles (which are four bits long). Further complicating this is that the first 3 characters of the ASCII character set are defined as special characters (e.g., carriage return, back space, etc.). This meant the data nybbles would have to be converted or (shifted up) into valid characters (this is why, if you ever see binary data transmitted from a modem or embedded in an message, data is either sent as hex codes or the letters A to Q). With this protocol, to send a single byte of data, two bytes (with the overhead bits resulting in 0 bits in total) would have to be sent. As pointed out, modern asynchronous serial data transmission normally occur eight bits at a time, which will avoid this problem and allow transmission of full bytes without breaking them up or converting them. The actual RS-3 communications model is shown in Fig In RS-3, different equipment is wired according to the functions that they perform. DTE (Data Terminal Equipment) and is meant to be the connector used for computers (the PC uses this type of connection). DCE (Data Communications Equipment) was meant for modems and terminals that transfer the data. Figure 6-57 computer communication via modem

137 30 PICmicro MCU APPLICATION DESIGN AND HARDWARE INTERFACING Understanding what the RS-3 model different equipment fits under is crucial to successfully connecting two devices by RS-3. With a pretty good understanding of the serial data, you can now look at the actual voltage signals. As mentioned, when RS-3 was first developed into a standard, computers and the electronics that drive them were still very primitive and unreliable. Because of that, we ve got a couple of legacies to deal with. The first is the voltage levels of the data. A mark () is actually Volts and a space (0) is V (Fig. 6-58). From Fig. 6-58, you should see that the hardware interface is not simply a TTL or CMOS-level buffer. Later, this section introduces you to some methods of generating and detecting these interface voltages. Voltages in the switching region ( 3 V) might not be read as a 0 or, depending on the device. You should always be sure that the voltages going into or out of a PICmicro MCU RS-3 circuit are in the valid regions. Of more concern are the handshaking signals. These six additional lines (which are at the same logic levels as the transmit/receive lines and shown in Fig. 6-58) are used to interface between devices and control the flow of information between computers. The Request To Send (RTS) and Clear To Send (CTS) lines are used to control data flow between the computer (DCE) and the modem (DTE device). When the PC is ready to send data, it asserts (outputs a mark) on RTS. If the DTE device is capable of receiving data, it will assert the CTS line. If the PC is unable to receiver data (i.e., the buffer is full or it is processing what it already has), it will de-assert the RTS line to notify the DTE device that it cannot receive any additional information. The Data Transmitter Ready (DTR) and Data Set Ready (DSR) lines are used to establish communications. When the PC is ready to communicate with the DTE device, it asserts DTR. If the DTE device is available and ready to accept data, it will assert DSR to notify the computer than the link is up and ready for data transmission. If a hardware error is in the link, then the DTE device will de-assert the DSR line to notify the computer of the problem. Modems, if the carrier between the receiver is lost, will de-assert the DSR line. Two more handshaking lines are available in the RS-3 standard that you should be aware of. Even so, chances are that you will never connect anything to them. The first is the Data Carrier Detect (DCD), which is asserted when the modem has connected with another device (i.e., the other device has picked up the phone ). The Ring Indicator (RI) is used to indicate to a PC whether or not the phone on the other end of the line is ringing or if it is busy. This line is very rarely used in PICmicro MCU applications. A common ground connection exists between the DCE and DTE devices. This connection is crucial for the RS-3-level converters to determine the actual incoming voltages. The ground pin should never be connected to a chassis or shield ground (to avoid large cur- RS-3 volt- Figure 6-58 age levels

Distributed by: www.jameco.com 1-800-831-4242 The content and copyrights of the attached material are the property of its owner. M PIC16F87X 28/40-pin 8-Bit CMOS FLASH Microcontrollers Microcontroller

More information

Distributed by: www.jameco.com 1-800-831-4242 The content and copyrights of the attached material are the property of its owner. 28/40-Pin 8-Bit CMOS FLASH Microcontrollers Devices Included in this Data

More information

PIC16F Pin, 8-Bit CMOS FLASH Microcontroller. Devices Included in this Data Sheet: Pin Diagram. Microcontroller Core Features:

PIC16F Pin, 8-Bit CMOS FLASH Microcontroller. Devices Included in this Data Sheet: Pin Diagram. Microcontroller Core Features: 28-Pin, 8-Bit CMOS FLASH Microcontroller Devices Included in this Data Sheet: PIC16F872 Microcontroller Core Features: High-performance RISC CPU Only 35 single word instructions to learn All single cycle

More information

8-Bit CMOS Microcontrollers with A/D Converter

8-Bit CMOS Microcontrollers with A/D Converter 8-Bit CMOS Microcontrollers with A/D Converter Devices included in this data sheet: PIC16C72 PIC16C73 PIC16C73A PIC16C74 PIC16C74A PIC16C76 PIC16C77 Microcontroller Core Features: High-performance RISC

More information

PIC16C63A/65B/73B/74B

PIC16C63A/65B/73B/74B 8-Bit CMOS Microcontrollers with A/D Converter Devices included in this data sheet: PIC16C63A PIC16C65B PIC16CXX Microcontroller Core Features: High performance RISC CPU Only 35 single word instructions

More information

PIC16C77X. 28/40-Pin, 8-Bit CMOS Microcontrollers w/ 12-Bit A/D * * * * * Enhanced features. Microcontroller Core Features: Pin Diagram PIC16C774

PIC16C77X. 28/40-Pin, 8-Bit CMOS Microcontrollers w/ 12-Bit A/D * * * * * Enhanced features. Microcontroller Core Features: Pin Diagram PIC16C774 28/40-Pin, 8-Bit CMOS Microcontrollers w/ 12-Bit A/D Microcontroller Core Features: High-performance RISC CPU Only 35 single word instructions to learn All single cycle instructions except for program

More information

8-Bit CMOS Microcontrollers. PIC16C6X Features A R62 63 R A R A R Program Memory 1K 2K 2K 4K 2K 2K 4K 4K 8K 8K

8-Bit CMOS Microcontrollers. PIC16C6X Features A R62 63 R A R A R Program Memory 1K 2K 2K 4K 2K 2K 4K 4K 8K 8K 8-Bit CMOS Microcontrollers PIC16C6X Devices included in this data sheet: PIC16C61 PIC16C62 PIC16C62A PIC16CR62 PIC16C63 PIC16CR63 PIC16C64 PIC16C64A PIC16CR64 PIC16C65 PIC16C65A PIC16CR65 PIC16C66 PIC16C67

More information

Building an Analog Communications System

Building an Analog Communications System Building an Analog Communications System Communicate between two PICs with analog signals. Analog signals have continous range. Analog signals must be discretized. Digital signal converted to analog Digital

More information

PIC16CR7X Data Sheet. 28/40-Pin, 8-Bit CMOS ROM Microcontrollers Microchip Technology Inc. DS21993C

PIC16CR7X Data Sheet. 28/40-Pin, 8-Bit CMOS ROM Microcontrollers Microchip Technology Inc. DS21993C Data Sheet 28/40-Pin, 8-Bit CMOS ROM Microcontrollers 2007 Microchip Technology Inc. DS21993C Note the following details of the code protection feature on Microchip devices: Microchip products meet the

More information

PIC16C63A/65B/73B/74B

PIC16C63A/65B/73B/74B 8-Bit CMOS Microcontrollers with A/D Converter Devices included in this data sheet: PIC16C63A PIC16C65B PIC16C73B PIC16C74B PIC16CXX Microcontroller Core Features: High-performance RISC CPU Only 35 single

More information

PIC16F72 Data Sheet. 28-Pin, 8-Bit CMOS FLASH Microcontoller with A/D Converter Microchip Technology Inc. DS39597C

PIC16F72 Data Sheet. 28-Pin, 8-Bit CMOS FLASH Microcontoller with A/D Converter Microchip Technology Inc. DS39597C Data Sheet 28-Pin, 8-Bit CMOS FLASH Microcontoller with A/D Converter 2007 Microchip Technology Inc. DS39597C Note the following details of the code protection feature on Microchip devices: Microchip products

More information

PIC16C9XX. 8-Bit CMOS Microcontroller with LCD Driver. Available in Die Form. Devices included in this data sheet: Microcontroller Core Features:

PIC16C9XX. 8-Bit CMOS Microcontroller with LCD Driver. Available in Die Form. Devices included in this data sheet: Microcontroller Core Features: 8-Bit CMOS Microcontroller with LCD Driver Devices included in this data sheet: PIC16C923 PIC16C924 Microcontroller Core Features: High performance RISC CPU Only 35 single word instructions to learn 4K

More information

28/40/44-Pin, 8-Bit CMOS Flash Microcontrollers with 10-Bit A/D and nanowatt Technology. Interrupts 10-bit A/D (ch)

28/40/44-Pin, 8-Bit CMOS Flash Microcontrollers with 10-Bit A/D and nanowatt Technology. Interrupts 10-bit A/D (ch) 28/40/44-Pin, 8-Bit CMOS Flash Microcontrollers with 10-Bit A/D and nanowatt Technology Low-Power Features: Power-Managed modes: - Primary Run (XT, RC oscillator, 76 A, 1MHz, 2V) - RC_RUN (7 A, 31.25 khz,

More information

PIC16F716 Data Sheet. 8-bit Flash-based Microcontroller with A/D Converter and Enhanced Capture/Compare/PWM

PIC16F716 Data Sheet. 8-bit Flash-based Microcontroller with A/D Converter and Enhanced Capture/Compare/PWM Data Sheet 8-bit Flash-based Microcontroller with A/D Converter and Enhanced Capture/Compare/PWM 2003 Microchip Technology Inc. Preliminary DS41206A Note the following details of the code protection feature

More information

PIC16C712/716 Data Sheet

PIC16C712/716 Data Sheet Data Sheet 8-Bit CMOS Microcontrollers with A/D Converter and Capture/Compare/PWM 2005 Microchip Technology Inc. DS41106B Note the following details of the code protection feature on Microchip devices:

More information

PIC16C925/ /68-Pin CMOS Microcontrollers with LCD Driver. High Performance RISC CPU: Analog Features: Special Microcontroller Features:

PIC16C925/ /68-Pin CMOS Microcontrollers with LCD Driver. High Performance RISC CPU: Analog Features: Special Microcontroller Features: 64/68-Pin CMOS Microcontrollers with LCD Driver High Performance RISC CPU: Only 35 single word instructions to learn All single cycle instructions except for program branches which are two-cycle Operating

More information

PIC16F716 Data Sheet. 8-bit Flash-based Microcontroller with A/D Converter and Enhanced Capture/Compare/PWM

PIC16F716 Data Sheet. 8-bit Flash-based Microcontroller with A/D Converter and Enhanced Capture/Compare/PWM Data Sheet 8-bit Flash-based Microcontroller with A/D Converter and Enhanced Capture/Compare/PWM 2003 Microchip Technology Inc. Preliminary DS41206A Note the following details of the code protection feature

More information

PIC16C717/770/ /20-Pin, 8-Bit CMOS Microcontrollers with 10/12-Bit A/D. Microcontroller Core Features: Pin Diagram. Peripheral Features:

PIC16C717/770/ /20-Pin, 8-Bit CMOS Microcontrollers with 10/12-Bit A/D. Microcontroller Core Features: Pin Diagram. Peripheral Features: 18/20-Pin, 8-Bit CMOS Microcontrollers with 10/12-Bit A/D Microcontroller Core Features: High-performance RISC CPU Only 35 single word instructions to learn All single cycle instructions except for program

More information

MCV18E Data Sheet. 18-Pin Flash Microcontroller Microchip Technology Inc. DS41399A

MCV18E Data Sheet. 18-Pin Flash Microcontroller Microchip Technology Inc. DS41399A Data Sheet 18-Pin Flash Microcontroller 2009 Microchip Technology Inc. DS41399A Note the following details of the code protection feature on Microchip devices: Microchip products meet the specification

More information

PIC16F62X. FLASH-Based 8-Bit CMOS Microcontrollers. Devices included in this data sheet: Special Microcontroller Features: High Performance RISC CPU:

PIC16F62X. FLASH-Based 8-Bit CMOS Microcontrollers. Devices included in this data sheet: Special Microcontroller Features: High Performance RISC CPU: FLASH-Based 8-Bit CMOS Microcontrollers Devices included in this data sheet: PIC16F627 PIC16F628 Referred to collectively as PIC16F62X. High Performance RISC CPU: Only 35 instructions to learn All single-cycle

More information

PIC16F7X7 Data Sheet. 28/40/44-Pin, 8-Bit CMOS Flash Microcontrollers with 10-Bit A/D and nanowatt Technology Microchip Technology Inc.

PIC16F7X7 Data Sheet. 28/40/44-Pin, 8-Bit CMOS Flash Microcontrollers with 10-Bit A/D and nanowatt Technology Microchip Technology Inc. Data Sheet 28/40/44-Pin, 8-Bit CMOS Flash Microcontrollers with 10-Bit A/D and nanowatt Technology 2004 Microchip Technology Inc. DS30498C Note the following details of the code protection feature on Microchip

More information

PIC16F627A/628A/648A Data Sheet

PIC16F627A/628A/648A Data Sheet Data Sheet FLASH-Based 8-Bit CMOS Microcontrollers 2002 Microchip Technology Inc. Preliminary DS40044A Note the following details of the code protection feature on Microchip devices: Microchip products

More information

PIC16F627A/628A/648A Data Sheet

PIC16F627A/628A/648A Data Sheet Data Sheet Flash-Based, 8-Bit CMOS Microcontrollers with nanowatt Technology 2009 Microchip Technology Inc. DS40044G Note the following details of the code protection feature on Microchip devices: Microchip

More information

ELCT 912: Advanced Embedded Systems

ELCT 912: Advanced Embedded Systems ELCT 912: Advanced Embedded Systems Lecture 5: PIC Peripherals on Chip Dr. Mohamed Abd El Ghany, Department of Electronics and Electrical Engineering The PIC Family: Peripherals Different PICs have different

More information

PIC16F87/88 Data Sheet

PIC16F87/88 Data Sheet Data Sheet 18/20/28-Pin Enhanced FLASH Microcontrollers with nanowatt Technology 2003 Microchip Technology Inc. Preliminary DS30487B Note the following details of the code protection feature on Microchip

More information

PIC16(L)F720/ Pin Flash Microcontrollers. Low-Power Features: Devices Included In This Data Sheet: High-Performance RISC CPU:

PIC16(L)F720/ Pin Flash Microcontrollers. Low-Power Features: Devices Included In This Data Sheet: High-Performance RISC CPU: 20-Pin Flash Microcontrollers Devices Included In This Data Sheet: PIC16F720 PIC16F721 PIC16LF720 PIC16LF721 High-Performance RISC CPU: Only 35 Instructions to Learn: - All single-cycle instructions except

More information

PIC16F882/883/884/886/887

PIC16F882/883/884/886/887 28/40/44-Pin Flash-Based, 8-Bit CMOS Microcontrollers High-Performance RISC CPU Only 35 Instructions to Learn: - All single-cycle instructions except branches Operating Speed: - DC 20 MHz oscillator/clock

More information

PIC16F72X/PIC16LF72X Data Sheet

PIC16F72X/PIC16LF72X Data Sheet Data Sheet 28/40/44-Pin Flash-Based, 8-Bit CMOS Microcontrollers 2008 Microchip Technology Inc. Preliminary DS41341B Note the following details of the code protection feature on Microchip devices: Microchip

More information

PIC16F631/677/685/687/689/690

PIC16F631/677/685/687/689/690 20-Pin Flash-Based, 8-Bit CMOS Microcontrollers High-Performance RISC CPU Only 35 Instructions to Learn: - All single-cycle instructions except branches Operating Speed: - DC 20 MHz oscillator/clock input

More information

rfpic12f675 FLASH-Based Microcontroller with ASK/FSK Transmitter High Performance RISC CPU: Pin Diagram: UHF ASK/FSK Transmitter: Peripheral Features:

rfpic12f675 FLASH-Based Microcontroller with ASK/FSK Transmitter High Performance RISC CPU: Pin Diagram: UHF ASK/FSK Transmitter: Peripheral Features: FLASH-Based Microcontroller with ASK/FSK Transmitter High Performance RISC CPU: Only 35 instructions to learn - All single cycle instructions except branches Operating speed: - Precision Internal 4 MHz

More information

PIC16C5X. EPROM/ROM-Based 8-Bit CMOS Microcontroller Series. Peripheral Features: Devices Included in this Data Sheet: CMOS Technology:

PIC16C5X. EPROM/ROM-Based 8-Bit CMOS Microcontroller Series. Peripheral Features: Devices Included in this Data Sheet: CMOS Technology: EPROM/ROM-Based 8-Bit CMOS Microcontroller Series Devices Included in this Data Sheet: PIC16C54 PIC16CR54 PIC16C55 PIC16C56 PIC16CR56 PIC16C57 PIC16CR57 PIC16C58 PIC16CR58 Note: 16C5X refers to all revisions

More information

PIC16F882/883/884/886/887 Data Sheet

PIC16F882/883/884/886/887 Data Sheet Data Sheet 28/40/44-Pin, Enhanced Flash-Based 8-Bit CMOS Microcontrollers with nanowatt Technology 2008 Microchip Technology Inc. DS41291E Note the following details of the code protection feature on Microchip

More information

Distributed by: www.jameco.com 1-800-831-4242 The content and copyrights of the attached material are the property of its owner. M PIC16C5X EPROM/ROM-Based 8-Bit CMOS Microcontroller Series Devices Included

More information

PIC16C781/782 Data Sheet

PIC16C781/782 Data Sheet Data Sheet 8-Bit CMOS Microcontrollers with A/D, D/A, OPAMP, Comparators and PSMC 2001 Microchip Technology Inc. Preliminary DS41171A Note the following details of the code protection feature on PICmicro

More information

PIC16F688 Data Sheet. 14-Pin Flash-Based, 8-Bit CMOS Microcontrollers with nanowatt Technology Microchip Technology Inc. Preliminary DS41203B

PIC16F688 Data Sheet. 14-Pin Flash-Based, 8-Bit CMOS Microcontrollers with nanowatt Technology Microchip Technology Inc. Preliminary DS41203B Data Sheet 14-Pin Flash-Based, 8-Bit CMOS Microcontrollers with nanowatt Technology 2004 Microchip Technology Inc. Preliminary DS41203B Note the following details of the code protection feature on Microchip

More information

PIC16F688 Data Sheet. 14-Pin Flash-Based, 8-Bit CMOS Microcontrollers with nanowatt Technology Microchip Technology Inc.

PIC16F688 Data Sheet. 14-Pin Flash-Based, 8-Bit CMOS Microcontrollers with nanowatt Technology Microchip Technology Inc. Data Sheet 14-Pin Flash-Based, 8-Bit CMOS Microcontrollers with nanowatt Technology 2007 Microchip Technology Inc. DS41203D Note the following details of the code protection feature on Microchip devices:

More information

PIC16F/LF722A/723A Data Sheet

PIC16F/LF722A/723A Data Sheet Data Sheet 28-Pin Flash Microcontrollers with nanowatt XLP Technology DS41417A Note the following details of the code protection feature on Microchip devices: Microchip products meet the specification

More information

PIC16F631/677/685/687/689/690 Data Sheet

PIC16F631/677/685/687/689/690 Data Sheet Data Sheet 20-Pin Flash-Based, 8-Bit CMOS Microcontrollers with nanowatt Technology 2007 Microchip Technology Inc. DS41262D Note the following details of the code protection feature on Microchip devices:

More information

PIC12F683 Data Sheet. 8-Pin Flash-Based, 8-Bit CMOS Microcontrollers with nanowatt Technology

PIC12F683 Data Sheet. 8-Pin Flash-Based, 8-Bit CMOS Microcontrollers with nanowatt Technology Data Sheet 8-Pin Flash-Based, 8-Bit CMOS Microcontrollers with nanowatt Technology * 8-bit, 8-pin Devices Protected by Microchip s Low Pin Count Patent: U.S. Patent No. 5,847,450. Additional U.S. and foreign

More information

PIC18F2X1X/4X1X. 28/40/44-Pin Flash Microcontrollers with 10-Bit A/D and nanowatt Technology. Flexible Oscillator Structure: Power-Managed Modes:

PIC18F2X1X/4X1X. 28/40/44-Pin Flash Microcontrollers with 10-Bit A/D and nanowatt Technology. Flexible Oscillator Structure: Power-Managed Modes: 28/40/44-Pin Flash Microcontrollers with 10-Bit A/D and nanowatt Technology Power-Managed Modes: Run: CPU On, Peripherals On Idle: CPU Off, Peripherals On Sleep: CPU Off, Peripherals Off Idle mode Currents

More information

TECHNICAL NOTE. A COMPACT ALGORITHM USING THE ADXL202 DUTY CYCLE OUTPUT by Harvey Weinberg

TECHNICAL NOTE. A COMPACT ALGORITHM USING THE ADXL202 DUTY CYCLE OUTPUT by Harvey Weinberg TECHNICAL NOTE ONE TECHNOLOGY WAYP.O. BOX 9106NORWOOD, MASSACHUSETTS 02062-9106781/329-4700 A COMPACT ALGORITHM USING THE ADXL202 DUTY CYCLE OUTPUT by Harvey Weinberg Introduction There are many applications

More information

Section 22. Basic 8-bit A/D Converter

Section 22. Basic 8-bit A/D Converter M Section 22. A/D Converter HIGHLIGHTS This section of the manual contains the following major topics: 22.1 Introduction...22-2 22.2 Control Registers...22-3 22.3 A/D Acquisition Requirements...22-6 22.4

More information

PIC16(L)F720/721 Data Sheet

PIC16(L)F720/721 Data Sheet Data Sheet 20-Pin Flash Microcontrollers with nanowatt XLP Technology 2011 Microchip Technology Inc. Preliminary DS41430B Note the following details of the code protection feature on Microchip devices:

More information

Section 3. Reset HIGHLIGHTS. Reset. This section of the manual contains the following major topics:

Section 3. Reset HIGHLIGHTS. Reset. This section of the manual contains the following major topics: Section 3. HIGHLIGHTS This section of the manual contains the following major topics: 3.1 Introduction... 3-2 3.2 s and Delay Timers... 3-4 3.3 Registers and Status Bit Values... 3-14 3.4 Design Tips...

More information

PIC16F684 Data Sheet. 14-Pin Flash-Based, 8-Bit CMOS Microcontrollers with nanowatt Technology Microchip Technology Inc. Preliminary DS41202C

PIC16F684 Data Sheet. 14-Pin Flash-Based, 8-Bit CMOS Microcontrollers with nanowatt Technology Microchip Technology Inc. Preliminary DS41202C Data Sheet 14-Pin Flash-Based, 8-Bit CMOS Microcontrollers with nanowatt Technology 2004 Microchip Technology Inc. Preliminary DS41202C Note the following details of the code protection feature on Microchip

More information

rfpic12f675k/675f/675h Data Sheet

rfpic12f675k/675f/675h Data Sheet K/675F/675H Data Sheet 20-Pin FLASH-Based 8-Bit CMOS Microcontroller with UHF ASK/FSK Transmitter 2003 Microchip Technology Inc. Preliminary DS70091A Note the following details of the code protection feature

More information

PIC16C5X Data Sheet. EPROM/ROM-Based 8-bit CMOS Microcontroller Series Microchip Technology Inc. Preliminary DS30453D

PIC16C5X Data Sheet. EPROM/ROM-Based 8-bit CMOS Microcontroller Series Microchip Technology Inc. Preliminary DS30453D Data Sheet EPROM/ROM-Based -bit CMOS Microcontroller Series 2002 Microchip Technology Inc. Preliminary DS30453D EPROM/ROM-Based -bit CMOS Microcontroller Series Devices Included in this Data Sheet: PIC16C54

More information

PIC12F752/HV Pin Flash-Based, 8-Bit CMOS Microcontrollers. Peripheral Features. High-Performance RISC CPU. Microcontroller Features

PIC12F752/HV Pin Flash-Based, 8-Bit CMOS Microcontrollers. Peripheral Features. High-Performance RISC CPU. Microcontroller Features 8-Pin Flash-Based, 8-Bit CMOS Microcontrollers High-Performance RISC CPU Only 35 Instructions to Learn: - All single-cycle instructions except branches Operating Speed: - DC 20 MHz clock input - DC 200

More information

PIC12F635/PIC16F636/639 Data Sheet

PIC12F635/PIC16F636/639 Data Sheet Data Sheet 8/14-Pin, Flash-Based 8-Bit CMOS Microcontrollers with nanowatt Technology DS41232D 8/14-Pin Flash-Based, 8-Bit CMOS Microcontrollers With nanowatt Technology High-Performance RISC CPU: Only

More information

Design and Construction of PIC-based IR Remote Control Moving Robot

Design and Construction of PIC-based IR Remote Control Moving Robot Design and Construction of PIC-based IR Remote Control Moving Robot Sanda Win, Tin Shein, Khin Maung Latt Abstract This document describes an electronic speed control designed to drive two DC motors from

More information

Embedded Systems. Interfacing PIC with external devices Analog to digital Converter. Eng. Anis Nazer Second Semester

Embedded Systems. Interfacing PIC with external devices Analog to digital Converter. Eng. Anis Nazer Second Semester Embedded Systems Interfacing PIC with external devices Analog to digital Converter Eng. Anis Nazer Second Semester 2016-2017 What is the time? What is the time? Definition Analog: can take any value Digital:

More information

PIC12F609/12HV609 PIC12F615/12HV615 Data Sheet

PIC12F609/12HV609 PIC12F615/12HV615 Data Sheet PIC12F609/12HV609 PIC12F615/12HV615 Data Sheet 8-Pin, Flash-Based 8-Bit CMOS Microcontrollers *8-bit, 8-pin Devices Protected by Microchip s Low Pin Count Patent: U.S. Patent No. 5,847,450. Additional

More information

PIC18F45J10 Family Data Sheet

PIC18F45J10 Family Data Sheet PIC18F45J10 Family Data Sheet 28/40/44-Pin High-Performance RISC Microcontrollers with nanowatt Technology 2007 Microchip Technology Inc. Preliminary DS39682C te the following details of the code protection

More information

PIC18F2525/2620/4525/4620 Data Sheet

PIC18F2525/2620/4525/4620 Data Sheet Data Sheet 28/40/44-Pin Enhanced Flash Microcontrollers with 10-Bit A/D and nanowatt Technology 2007 Microchip Technology Inc. Preliminary DS39626C te the following details of the code protection feature

More information

PIC12F529T39A. 14-Pin, 8-Bit Flash Microcontroller. High-Performance RISC CPU. Low-Power Features/CMOS Technology. Special Microcontroller Features

PIC12F529T39A. 14-Pin, 8-Bit Flash Microcontroller. High-Performance RISC CPU. Low-Power Features/CMOS Technology. Special Microcontroller Features 14-Pin, 8-Bit Flash Microcontroller High-Performance RISC CPU Only 34 Single-Word Instructions All Single-Cycle Instructions except for Program Branches which are Two-Cycle Four-Level Deep Hardware Stack

More information

PIC18F2423/2523/4423/4523 Data Sheet

PIC18F2423/2523/4423/4523 Data Sheet Data Sheet 28/40/44-Pin, Enhanced Flash Microcontrollers with 12-Bit A/D and nanowatt Technology 2007 Microchip Technology Inc. Preliminary DS39755B te the following details of the code protection feature

More information

PIC18F45J10 Family Data Sheet

PIC18F45J10 Family Data Sheet PIC18F45J10 Family Data Sheet 28/40/44-Pin High-Performance, RISC Microcontrollers 2009 Microchip Technology Inc. DS39682E te the following details of the code protection feature on Microchip devices:

More information

On-chip RC oscillator based Watchdog Timer(WDT) can be operated freely 12 I/O pins with their own independent direction control 3. Applications The ap

On-chip RC oscillator based Watchdog Timer(WDT) can be operated freely 12 I/O pins with their own independent direction control 3. Applications The ap MDT2010 1. General Description This EPROM-Based 8-bit micro-controller uses a fully static CMOS design technology combines higher speeds and smaller size with the low power and high noise immunity of CMOS.

More information

MICROPROCESSORS A (17.383) Fall Lecture Outline

MICROPROCESSORS A (17.383) Fall Lecture Outline MICROPROCESSORS A (17.383) Fall 2010 Lecture Outline Class # 07 October 26, 2010 Dohn Bowden 1 Today s Lecture Syllabus review Microcontroller Hardware and/or Interface Finish Analog to Digital Conversion

More information

GCE A level 1145/01 ELECTRONICS ET5. P.M. THURSDAY, 31 May hours. Centre Number. Candidate Number. Surname. Other Names

GCE A level 1145/01 ELECTRONICS ET5. P.M. THURSDAY, 31 May hours. Centre Number. Candidate Number. Surname. Other Names Surname Other Names Centre Number 0 Candidate Number GCE A level 1145/01 ELECTRONICS ET5 P.M. THURSDAY, 31 May 2012 1 1 2 hours For s use Question Maximum Mark Mark Awarded 1. 6 2. 9 3. 8 4. 6 1145 010001

More information

PIC16F753/HV /16-Pin, Flash-Based 8-Bit CMOS Microcontrollers. High-Performance RISC CPU: Peripheral Features: Microcontroller Features:

PIC16F753/HV /16-Pin, Flash-Based 8-Bit CMOS Microcontrollers. High-Performance RISC CPU: Peripheral Features: Microcontroller Features: 14/16-Pin, Flash-Based 8-Bit CMOS Microcontrollers High-Performance RISC CPU: Only 35 Instructions to Learn: - All single-cycle instructions except branches Operating Speed: - DC 20 MHz clock input - DC

More information

PIC Analog Voltage to PWM Duty Cycle

PIC Analog Voltage to PWM Duty Cycle Name Lab Section PIC Analog Voltage to PWM Duty Cycle Lab 5 Introduction: In this lab you will convert an analog voltage into a pulse width modulation (PWM) duty cycle. The source of the analog voltage

More information

PIC16F753/HV /16-Pin, Flash-Based 8-Bit CMOS Microcontrollers. High-Performance RISC CPU. extreme Low-Power (XLP) Features. Peripheral Features

PIC16F753/HV /16-Pin, Flash-Based 8-Bit CMOS Microcontrollers. High-Performance RISC CPU. extreme Low-Power (XLP) Features. Peripheral Features 14/16-Pin, Flash-Based 8-Bit CMOS Microcontrollers High-Performance RISC CPU Only 35 Instructions to Learn: - All single-cycle instructions except branches Operating Speed: - DC 20 MHz clock input - DC

More information

PIC16(L)F1516/7/8/9. 28/40/44-Pin Flash Microcontrollers with XLP Technology. Devices Included In This Data Sheet. Analog Features

PIC16(L)F1516/7/8/9. 28/40/44-Pin Flash Microcontrollers with XLP Technology. Devices Included In This Data Sheet. Analog Features 28/40/44-Pin Flash Microcontrollers with XLP Technology Devices Included In This Data Sheet PIC16F1516 PIC16F1517 PIC16F1518 PIC16F1519 PIC16LF1516 PIC16LF1517 PIC16LF1518 PIC16LF1519 High-Performance

More information

AN1730. Digital Amplification Control of an Analog Signal Using the MC68HC705J1A. Introduction

AN1730. Digital Amplification Control of an Analog Signal Using the MC68HC705J1A. Introduction Order this document by /D Digital Amplification Control of an Analog Signal Using the MC68HC705JA By Mark Glenewinkel Consumer Systems Group Austin, Texas Introduction This application note describes the

More information

MK7A20P 8 bit microcontroller

MK7A20P 8 bit microcontroller MK7A2P. Feature ROM size: 2,48 Words OTP ROM RAM size: 72 Bytes 76 single word instruction Stack level: 2 I/O ports: 2 - Port B: 8 pull high I/O pin and has wake up function - Port A~3: 4 normal I/O pin

More information

PIC16LF1554/ Pin Flash, 8-Bit Microcontrollers with XLP Technology. Description. High-Performance RISC CPU. Peripheral Features

PIC16LF1554/ Pin Flash, 8-Bit Microcontrollers with XLP Technology. Description. High-Performance RISC CPU. Peripheral Features 20-Pin Flash, 8-Bit Microcontrollers with XLP Technology Description The PIC16LF1554/1559 microcontrollers with Microchip enhanced mid-range core deliver unique on-chip features for the design of mtouch

More information

High-Performance 8-Bit CMOS EPROM Microcontrollers RD1/AD9 RD0/AD8 RE0/ALE RE1/OE RE2/WR RE3/CAP4 MCLR/VPP TEST

High-Performance 8-Bit CMOS EPROM Microcontrollers RD1/AD9 RD0/AD8 RE0/ALE RE1/OE RE2/WR RE3/CAP4 MCLR/VPP TEST High-Performance 8-Bit CMOS EPROM Microcontrollers Devices included in this data sheet: PIC17C752 PIC17C756 Microcontroller Core Features: Only 58 single word instructions to learn All single cycle instructions

More information

GCE A level 1145/01 ELECTRONICS ET5

GCE A level 1145/01 ELECTRONICS ET5 Surname Centre Number Candidate Number Other Names 2 GCE A level 1145/01 ELECTRONICS ET5 S16-1145-01 A.M. FRIDAY, 17 June 2016 1 hour 30 minutes For s use ADDITIONAL MATERIALS In addition to this examination

More information

MICROBOARD ADVANCED MANUAL

MICROBOARD ADVANCED MANUAL MICROBOARD ADVANCED MANUAL Revised and edited by David Zeibin, Summer 2001 Based on documents by Ben Bathgate, Mike Cumming, Patrick Pilarski, and Paul Bartosek Special thanks to Dr Chris Backhouse HOW

More information

MDT General Description. 2. Features. 3. Applications. 4. Pin Assignment

MDT General Description. 2. Features. 3. Applications. 4. Pin Assignment 1. General Description This EPROM-Based 8-bit micro-controller uses a fully static CMOS technology process to achieve higher speed and smaller size with the low power consump-tion and high noise immunity.

More information

PIC ADC to PWM and Mosfet Low-Side Driver

PIC ADC to PWM and Mosfet Low-Side Driver Name Lab Section PIC ADC to PWM and Mosfet Low-Side Driver Lab 6 Introduction: In this lab you will convert an analog voltage into a pulse width modulation (PWM) duty cycle. The source of the analog voltage

More information

GCE A level 1145/01 ELECTRONICS ET5

GCE A level 1145/01 ELECTRONICS ET5 Surname Other Names Centre Number 2 Candidate Number GCE A level 1145/01 ELECTRONICS ET5 A.M. WEDNESDAY, 12 June 2013 1½ hours ADDITIONAL MATERIALS In addition to this examination paper, you will need

More information

8-bit Microcontroller with 2K Bytes In-System Programmable Flash. ATtiny20

8-bit Microcontroller with 2K Bytes In-System Programmable Flash. ATtiny20 Features High Performance, Low Power AVR 8-bit Microcontroller Advanced RISC Architecture 112 Powerful Instructions Most Single Clock Cycle Execution 16 x 8 General Purpose Working Registers Fully Static

More information

PIC16(L)F1512/3. 28-Pin Flash Microcontrollers with XLP Technology. High-Performance RISC CPU. Analog Features. Memory

PIC16(L)F1512/3. 28-Pin Flash Microcontrollers with XLP Technology. High-Performance RISC CPU. Analog Features. Memory 28-Pin Flash Microcontrollers with XLP Technology High-Performance RISC CPU C Compiler Optimized Architecture Only 49 Instructions Operating Speed: - DC 20 MHz clock input @ 2.5V - DC 16 MHz clock input

More information

General-Purpose OTP MCU with 14 I/O LInes

General-Purpose OTP MCU with 14 I/O LInes General-Purpose OTP MCU with 14 I/O LInes Product Specification PS004602-0401 PRELIMINARY ZiLOG Worldwide Headquarters 910 E. Hamilton Avenue Campbell, CA 95008 Telephone: 408.558.8500 Fax: 408.558.8300

More information

PIC16(L)F1824/8. 14/20-Pin Flash Microcontrollers with XLP Technology. Extreme Low-Power Management PIC16LF1824/8 with XLP. High-Performance RISC CPU

PIC16(L)F1824/8. 14/20-Pin Flash Microcontrollers with XLP Technology. Extreme Low-Power Management PIC16LF1824/8 with XLP. High-Performance RISC CPU 14/20-Pin Flash Microcontrollers with XLP Technology High-Performance RISC CPU Only 49 Instructions to Learn: - All single-cycle instructions except branches Operating Speed: - DC 32 MHz oscillator/clock

More information

Controlling DC Brush Motor using MD10B or MD30B. Version 1.2. Aug Cytron Technologies Sdn. Bhd.

Controlling DC Brush Motor using MD10B or MD30B. Version 1.2. Aug Cytron Technologies Sdn. Bhd. PR10 Controlling DC Brush Motor using MD10B or MD30B Version 1.2 Aug 2008 Cytron Technologies Sdn. Bhd. Information contained in this publication regarding device applications and the like is intended

More information

14/20-Pin MCUs with High-Precision 16-Bit PWMs

14/20-Pin MCUs with High-Precision 16-Bit PWMs 14/20-Pin MCUs with High-Precision 16-Bit PWMs Description PIC16(L)F1574/5/8/9 microcontrollers combine the capabilities of 16-bit PWMs with Analog to suit a variety of applications. These devices deliver

More information

PIC16C5X Data Sheet. EPROM/ROM-Based 8-bit CMOS Microcontroller Series Microchip Technology Inc. Preliminary DS30453D

PIC16C5X Data Sheet. EPROM/ROM-Based 8-bit CMOS Microcontroller Series Microchip Technology Inc. Preliminary DS30453D Data Sheet EPROM/ROM-Based 8-bit CMOS Microcontroller Series 2002 Microchip Technology Inc. Preliminary DS30453D Note the following details of the code protection feature on PICmicro MCUs. The PICmicro

More information

8-bit Microcontroller with 512/1024 Bytes In-System Programmable Flash. ATtiny4/5/9/10

8-bit Microcontroller with 512/1024 Bytes In-System Programmable Flash. ATtiny4/5/9/10 Features High Performance, Low Power AVR 8-Bit Microcontroller Advanced RISC Architecture 54 Powerful Instructions Most Single Clock Cycle Execution 16 x 8 General Purpose Working Registers Fully Static

More information

EN: This Datasheet is presented by the m anufacturer. Please v isit our website for pricing and availability at ore.hu.

EN: This Datasheet is presented by the m anufacturer. Please v isit our website for pricing and availability at   ore.hu. EN: This Datasheet is presented by the m anufacturer. Please v isit our website for pricing and availability at www.hest ore.hu. Data Sheet 28/40/44-Pin Enhanced Flash Microcontrollers with ECAN Technology,

More information

JX pin PIC Microcontroller Project Board

JX pin PIC Microcontroller Project Board JX-877 40-pin PIC Microcontroller Project Board Specification Connect to PC s parallel port for programming with CX-6 cable (included) PIC16F877-20/P on-board, support all 40-pin of PIC16F and 18F series.

More information

Interfacing to Analog World Sensor Interfacing

Interfacing to Analog World Sensor Interfacing Interfacing to Analog World Sensor Interfacing Introduction to Analog to digital Conversion Why Analog to Digital? Basics of A/D Conversion. A/D converter inside PIC16F887 Related Problems Prepared By-

More information

Pulse Width Modulation

Pulse Width Modulation ECEn 621" Computer Arithmetic" Project Notes Week 1 Pulse Width Modulation 1 Pulse Width Modulation A method of regulating the amount of voltage delivered to a load. The average value of the voltage fed

More information

PIC Functionality. General I/O Dedicated Interrupt Change State Interrupt Input Capture Output Compare PWM ADC RS232

PIC Functionality. General I/O Dedicated Interrupt Change State Interrupt Input Capture Output Compare PWM ADC RS232 PIC Functionality General I/O Dedicated Interrupt Change State Interrupt Input Capture Output Compare PWM ADC RS232 General I/O Logic Output light LEDs Trigger solenoids Transfer data Logic Input Monitor

More information

Full-Featured, Low Pin Count Microcontrollers with XLP

Full-Featured, Low Pin Count Microcontrollers with XLP Full-Featured, Low Pin Count Microcontrollers with XLP Description microcontrollers feature Analog, Core Independent Peripherals and Communication Peripherals, combined with extreme Low Power (XLP) for

More information

PIC16(L)F /20/28-Pin Flash Microcontrollers with XLP Technology. Extreme Low-Power Management PIC16LF1847 with XLP: High-Performance RISC CPU:

PIC16(L)F /20/28-Pin Flash Microcontrollers with XLP Technology. Extreme Low-Power Management PIC16LF1847 with XLP: High-Performance RISC CPU: 18/20/28-Pin Flash Microcontrollers with XLP Technology High-Performance RISC CPU: C Compiler Optimized Architecture 256 bytes Data EEPROM Up to 14 Kbytes Linear Program Memory Addressing Up to 1024 bytes

More information

Full-Featured, 14/20 Low Pin Count Microcontrollers with XLP

Full-Featured, 14/20 Low Pin Count Microcontrollers with XLP Full-Featured, 14/20 Low Pin Count Microcontrollers with XLP Description PIC16(L)F18326/18346 microcontrollers feature Analog, Core Independent Peripherals and Communication Peripherals, combined with

More information

Hashemite University Faculty of Engineering Mechatronics Engineering Department. Microprocessors and Microcontrollers Laboratory

Hashemite University Faculty of Engineering Mechatronics Engineering Department. Microprocessors and Microcontrollers Laboratory Hashemite University Faculty of Engineering Mechatronics Engineering Department Microprocessors and Microcontrollers Laboratory The Hashemite University Faculty of Engineering Department of Mechatronics

More information

Hi Hsiao-Lung Chan Dept Electrical Engineering Chang Gung University, Taiwan

Hi Hsiao-Lung Chan Dept Electrical Engineering Chang Gung University, Taiwan Timers and CCP Modules Hi Hsiao-Lung Chan Dept Electrical Engineering Chang Gung University, Taiwan chanhl@mail.cgu.edu.twcgu PIC18 Timers Timer2, Timer4 8-bit timers use instruction cycle clock as the

More information

TKT-3500 Microcontroller systems

TKT-3500 Microcontroller systems TKT-3500 Microcontroller systems Lec 4 Timers and other peripherals, pulse-width modulation Ville Kaseva Department of Computer Systems Tampere University of Technology Fall 2010 Sources Original slides

More information

PIC12F529T39A Data Sheet

PIC12F529T39A Data Sheet Data Sheet 14-Pin, 8-Bit Flash Microcontroller 2012 Microchip Technology Inc. Preliminary DS41635A Note the following details of the code protection feature on Microchip devices: Microchip products meet

More information

PIC12LF1840T39A. 8-Bit Flash Microcontroller with XLP Technology. High-Performance RISC CPU: Low-Power Features: RF Transmitter:

PIC12LF1840T39A. 8-Bit Flash Microcontroller with XLP Technology. High-Performance RISC CPU: Low-Power Features: RF Transmitter: 8-Bit Flash Microcontroller with XLP Technology High-Performance RISC CPU: Only 49 Instructions to Learn: - All single-cycle instructions except branches Operating Speed: - DC 32 MHz oscillator/clock input

More information

MDT10P General Description. 2. Features. 3. Applications

MDT10P General Description. 2. Features. 3. Applications 1. General This ROM-Based 8-bit micro-controller uses a fully static CMOS technology process to achieve high speed, small size, the low power and high noise immunity. On chip memory includes 2K words EPROM,

More information

Lesson 19 In-Circuit Programming

Lesson 19 In-Circuit Programming Elmer 160 Lesson 19 Overview Lesson 19 Introduction When the designer makes a new circuit, there is often some time spent in developing the software for that circuit. Removing the PIC from the circuit

More information

MDT2005E. 1. General Description. 2. Features

MDT2005E. 1. General Description. 2. Features MDT2005E 1. General Description This EPROM-Based 8-bit micro-controller uses a fully static CMOS design technology combines higher speeds and smaller size with the low power and high noise immunity of

More information

EEL 4744C: Microprocessor Applications. Lecture 9. Part 2. M68HC12 Serial I/O. Dr. Tao Li 1

EEL 4744C: Microprocessor Applications. Lecture 9. Part 2. M68HC12 Serial I/O. Dr. Tao Li 1 EEL 4744C: Microprocessor Applications Lecture 9 Part 2 M68HC12 Serial I/O Dr. Tao Li 1 Reading Assignment Software and Hardware Engineering (new version): Chapter 15 SHE (old version): Chapter 11 HC12

More information

Designing with a Microcontroller (v6)

Designing with a Microcontroller (v6) Designing with a Microcontroller (v6) Safety: In this lab, voltages are less than 15 volts and this is not normally dangerous to humans. However, you should assemble or modify a circuit when power is disconnected

More information

AB-44 APPLICATION BRIEF. Using the 87C51GB SHARON LOPEZ APPLICATIONS ENGINEER. March Order Number

AB-44 APPLICATION BRIEF. Using the 87C51GB SHARON LOPEZ APPLICATIONS ENGINEER. March Order Number APPLICATION BRIEF Using the 87C51GB SHARON LOPEZ APPLICATIONS ENGINEER March 1991 Order Number 270957-001 Information in this document is provided in connection with Intel products Intel assumes no liability

More information