AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

17
2002-2014 Microchip Technology Inc. DS00000840B-page 1 AN840 INTRODUCTION In choosing the appropriate microcontroller for a specific application, it is necessary to select one which includes all the needed peripherals. It is also essential to know how to integrate these peripherals to meet the desired output requirements. The PIC16F7X and PIC16C7X families are both 8-bit mid-range microcontrollers. The PIC16F7X family is a Flash device, while the PIC16C7X family is a one-time-programming (OTP) device. Two code examples are presented in this application note covering the Analog-to-Digital Converter (ADC), Timer2, Capture/Compare/PWM (CCP) and the Universal Synchronous Asynchronous Receiver Transmitter (USART), for both the PIC16F7X and PIC16C7X families. This application note covers three main subjects: Configuration of the above-mentioned peripherals Integration of these peripherals How their operation affects the other peripherals Also provided are calculations, data, hardware schematic and source code in C and assembly. A/D MODULE FIGURE 1: ANALOG-TO-DIGITAL CONVERSION BLOCK DIAGRAM The A/D allows the conversion of an analog input signal to a corresponding 8-bit digital number. The output of the internal sample and hold circuit is the input into the converter, which generates the result via successive approximation. The analog reference voltage is software-selectable to either the device’s positive supply voltage (VDD) or the voltage level on the VREF pin. The A/D converter has a unique feature of being able to operate while the device is in Sleep mode. The A/D module has three registers: A/D Control Register 0 (ADCON0) A/D Control Register 1 (ADCON1) A/D Result Register (ADRES) In the sample program (see Appendix A: “Source Code in Assembly” or Appendix B: “Source Code in C”), the code segment, init_ADC, sets up the A/D via ADCON0 and ADCON1. The ADCON0 register controls the operation of the A/D module. This register is used to select the conversion clock frequency and the analog channel. It is where the start and completion of conversion is determined. The ADCON1 register configures the functions of the port pins. The PIC16F7X and PIC16C7X microcontrollers have either five or eight I/O pins which can be configured as analog inputs. It is important to take note that ADCON1 does not override the respective TRIS register which is used to configure the data direction of the PORT register. The ADCON1, TRISA and TRISE 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). The sample programs in Appendix A: “Source Code in Assembly” and Appendix B: “Source Code in C” use two analog channels, AN0 and AN1, which are switched after every conversion is completed. After the ADCON0 and ADCON1 registers are configured, the GO/DONE bit in ADCON0 is set to a ‘1to start the conversion and then monitored to track when the conversion is complete. When the A/D conversion is complete, the result is loaded into the ADRES register, the GO/DONE bit is cleared, and the A/D Interrupt Flag bit (ADIF) is set. The sample code reads the ADRES register and passes it on to the USART and CCP modules. Switching between the two analog input channels is done by changing the value of the CHS2:CHS0 bits of the ADCON0 register (see Figure 1). Note that Figure 1 only shows AN1 and AN0, but any of the available analog input channels can be selected via the CHS2:CHS0 bits. Authors: Mary Tamar Tan, Mark Pallones Microchip Technology Inc. 000 001 8-bit A/D AN1 AN0 V AIN V REF V DD CHS2:CHS0 PIC16F7X/PIC16C7X Peripherals Configuration and Integration

Transcript of AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

Page 1: AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

AN840PIC16F7X/PIC16C7X Peripherals Configuration and Integration

INTRODUCTIONIn choosing the appropriate microcontroller for aspecific application, it is necessary to select one whichincludes all the needed peripherals. It is also essentialto know how to integrate these peripherals to meet thedesired output requirements.

The PIC16F7X and PIC16C7X families are both 8-bitmid-range microcontrollers. The PIC16F7X family is aFlash device, while the PIC16C7X family is aone-time-programming (OTP) device. Two codeexamples are presented in this application notecovering the Analog-to-Digital Converter (ADC),Timer2, Capture/Compare/PWM (CCP) and theUniversal Synchronous Asynchronous ReceiverTransmitter (USART), for both the PIC16F7X andPIC16C7X families.

This application note covers three main subjects:

• Configuration of the above-mentioned peripherals• Integration of these peripherals • How their operation affects the other peripherals

Also provided are calculations, data, hardwareschematic and source code in C and assembly.

A/D MODULE

FIGURE 1: ANALOG-TO-DIGITAL CONVERSION BLOCK DIAGRAM

The A/D allows the conversion of an analog input signalto a corresponding 8-bit digital number. The output ofthe internal sample and hold circuit is the input into theconverter, which generates the result via successiveapproximation. The analog reference voltage issoftware-selectable to either the device’s positivesupply voltage (VDD) or the voltage level on the VREFpin. The A/D converter has a unique feature of beingable to operate while the device is in Sleep mode.

The A/D module has three registers:

• A/D Control Register 0 (ADCON0)• A/D Control Register 1 (ADCON1)• A/D Result Register (ADRES)

In the sample program (see Appendix A: “SourceCode in Assembly” or Appendix B: “Source Codein C”), the code segment, init_ADC, sets up the A/Dvia ADCON0 and ADCON1. The ADCON0 registercontrols the operation of the A/D module. This registeris used to select the conversion clock frequency andthe analog channel. It is where the start and completionof conversion is determined. The ADCON1 registerconfigures the functions of the port pins. ThePIC16F7X and PIC16C7X microcontrollers have eitherfive or eight I/O pins which can be configured as analoginputs. It is important to take note that ADCON1 doesnot override the respective TRIS register which is usedto configure the data direction of the PORT register.The ADCON1, TRISA and TRISE registers control theoperation of the A/D port pins. The port pins that aredesired as analog inputs must have theircorresponding TRIS bits set (input). The sampleprograms in Appendix A: “Source Code inAssembly” and Appendix B: “Source Code in C”use two analog channels, AN0 and AN1, which areswitched after every conversion is completed.

After the ADCON0 and ADCON1 registers areconfigured, the GO/DONE bit in ADCON0 is set to a ‘1’to start the conversion and then monitored to trackwhen the conversion is complete. When the A/Dconversion is complete, the result is loaded into theADRES register, the GO/DONE bit is cleared, and theA/D Interrupt Flag bit (ADIF) is set. The sample codereads the ADRES register and passes it on to theUSART and CCP modules. Switching between the twoanalog input channels is done by changing the value ofthe CHS2:CHS0 bits of the ADCON0 register (seeFigure 1). Note that Figure 1 only shows AN1 and AN0,but any of the available analog input channels can beselected via the CHS2:CHS0 bits.

Authors: Mary Tamar Tan,Mark PallonesMicrochip Technology Inc.

000

001

8-bit A/D

AN1

AN0

VAIN

VREF

VDD

CHS2:CHS0

2002-2014 Microchip Technology Inc. DS00000840B-page 1

Page 2: AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

AN840

TIMERSThe PIC16F7X and PIC16C7X families of devices havethree timer modules. Each module can generate aninterrupt to indicate that an event has occurred (i.e.,timer overflow).

The three timer modules are:

• Timer0 Module• Timer1 Module • Timer2 Module

Timer0 module is a simple 8-bit timer/counter. Theclock source can be either the internal system clock(FOSC/4) or an external clock. In Timer mode, theTimer0 module will increment every instruction cycle(without prescaler). In Counter mode, Timer0 willincrement, either on every rising or falling edge of pinRA4/T0CKI.

Timer1 module is a 16-bit timer/counter consisting oftwo 8-bit registers (TMR1H and TMR1L), which arereadable and writable. The TMR1 register pair(TMR1H:TMR1L) increments from 0000h to FFFFhand rolls over to 0000h. In Timer mode, Timer1increments every instruction cycle. In Counter mode, itincrements on every rising edge of the external clockinput.

Timer2 is an 8-bit timer with a prescaler, a postscalerand a Period register. Using the prescaler andpostscaler at their maximum settings, the overflow timeis the same as a 16-bit timer. Timer2 is the PWM timebase when the CCP module is used in the PWM mode.

Additional information and details on the use of thesethree timers can be found in the PIC16F7X andPIC16C7X family data sheets.

CAPTURE/COMPARE/PWM MODULE (CCP)PIC16F7X and PIC16C7X have two CCP (Capture/Compare/PWM) modules. Each module contains a16-bit register which can operate as a 16-bit Captureregister, as a 16-bit Compare register or as a 10-bitPWM Master/Slave Duty Cycle register. The CCPmodules are identical in operation, with the exceptionof the operation of the Special Event Trigger. Each CCPmodule has three registers, which are shown below:

Additional information and details on the use of CCPcan be found in the PIC16F7X and PIC16C7X familydata sheets.

TIMER2 AS THE PWM TIME BASETimer2 is an 8-bit timer which can be used as the PWMtime base for the CCP. For the PWM mode, thefollowing registers need to be configured:

• Timer2 Period Register (PR2)• Timer2 Control Register (T2CON)• PIR1 Register

The init_TIMER2 code segment shows an exampleof the Timer2 configuration for PWM mode (seeAppendix A: “Source Code in Assembly” orAppendix B: “Source Code in C”). The PWM outputhas a time base (period) and a time that the outputstays high (duty cycle). The frequency of the PWM isthe inverse of the period (1/period). The PWM period isspecified by writing to the PR2 register. The PWM dutycycle is latched from CCPR1L into CCPR1H. Settingup the period and duty cycle is discussed in detail inSection “PWM Mode of the CCP Module”. TheTMR2ON bit of the T2CON register is set to startTimer2 operation. The TMR2 register is readable andwritable and is cleared on all device Resets. Timer2increments from 00h until it matches PR2 and thenresets to 00h on the next increment cycle. The TMR2Interrupt Flag bit (TMR2IF) is set whenever a matchbetween the TMR2 and PR2 registers occurs. In thecode example, the TMR2IF flag is cleared after everyTMR2/PR2 match to reset Timer2 and to signal a startof conversion for the A/D.

CCP1 CCP2 Comment

CCP1CON CCP2CON CCP Control registerCCPR1H CCPR2H CCP High byteCCPR1L CCPR2L CCP Low byteCCP1 CCP2 CCP pin

DS00000840B-page 2 2002-2014 Microchip Technology Inc.

Page 3: AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

AN840

PWM MODE OF THE CCP MODULEBoth PIC16F7X and PIC16C7X have two CCPmodules that are identical in operation, with theexception being the operation of the Special EventTrigger. In Pulse-Width Modulation (PWM) mode, theCCPx pin produces up to a 10-bit resolution PWMoutput. Since the CCPx pin is multiplexed with thePORT data latch, the corresponding TRIS bit must becleared to make the CCPx pin an output. In thisapplication note, only the PWM mode of the CCP2module is being used. The code example in AppendixA: “Source Code in Assembly” and Appendix B:“Source Code in C” sets up the following registers forPWM operation:

• PORTC Data Direction Register (TRISC)• Timer2 Period Register (PR2)• CCP2CON Register• CCPR2L Register

The code segment, init_PWM, is an example on howto initialize the CCP2 module for PWM mode. Since theCCP2 pin is multiplexed with the RC1/CPP2 data latch,the TRISC<1> bit must be cleared to make the CCP1pin an output. The PWM period is specified by writingto the PR2 register. The PWM period can be calculatedusing Equation 4.

Equation 1 is the formula used to obtain the maximumPWM resolution.

EQUATION 1: MAXIMUM PWM RESOLUTION EQUATION

A maximum PWM resolution of ten bits is used. To getthe value of the PR2 register, the PWM frequency andthe PWM period must be calculated first. The PWMfrequency can be obtained by rearranging Equation 1.

EQUATION 2: PWM FREQUENCY EQUATION

Substituting the values of the PWM resolution (‘10’)and oscillator frequency (4 MHz) to Equation 2 will yielda PWM frequency of 3906.25 Hz. PWM period isdefined as shown in Equation 3.

EQUATION 3: RELATIONSHIP OF PWM PERIOD AND PWM FREQUENCY

Note that the PWM period can also be computed usingEquation 4.

EQUATION 4: PWM PERIOD EQUATION

The PWM frequency (FPWM) is defined as. For the code example, the Timer2

prescale value is set to ‘1’. TOSC is the reciprocal of theoscillator frequency (FOSC), which is 4 MHz.

By equating Equation 3 and Equation 4, expressingTOSC in terms of FOSC and rearranging the terms, thePR2 value can be obtained, as seen in Equation 5 andEquation 6.

EQUATION 5: RESULT OF EQUATIONS 3 AND 4

EQUATION 6: PR2 VALUE AS A FUNCTION OF FOSC AND FPWM

Using Equation 6 will yield a PR2 decimal value equalto 255 or a hexadecimal value FF. Any value greaterthan 255 will result in a 100% duty cycle.

The PWM duty cycle is specified by writing to theCCPR2L register and to the DCxB1:DCxB0(CCP2CON<5:4>) bits. Up to 10-bit resolution isavailable: the CCPR2L contains the eight MSbs andCCP2CON<5:4> contains the two LSbs. This 10-bitvalue is represented by CCPR2L and CCP2CON<5:4>in Equation 7. The code examples in Appendix A:“Source Code in Assembly” and Appendix B:“Source Code in C” use only 8 bits (CCPR2L) ofresolution, so the CCP2CON<5:4> bits areprogrammed to a ‘0’. The 8-bit A/D result is written intothe CCPR2L register after each A/D conversion. Thisallows the PWM output to be controlled by themeasured A/D value. The duty cycle can be calculatedat any time using Equation 7.

EQUATION 7: PWM DUTY CYCLE AT ANY TIME INSTANT

Resolution 2FOSCFPWM-------------- bitslog=

FPWM FOSC

2Resolution------------------------=

PWM Period 1FPWM--------------=

(TMR2 Prescale Value)

PWM Period PR2 1+ 4 TOSC =

1 PWM period

1FPWM-------------- PR2 1+ 4 1

FOSC------------ TMR2 prescale value =

PR2 FOSC

FPWM 4 TMR2 prescale value ------------------------------------------------------------------------------------- 1–=

T OSC TMR2 prescale value

PWM Duty Cycle CCPR2L:CCP2CON<5:4> =

2002-2014 Microchip Technology Inc. DS00000840B-page 3

Page 4: AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

AN840

UNIVERSAL SYNCHRONOUS ASYNCHRONOUS RECEIVER TRANSMITTER (USART)The Universal Synchronous Asynchronous ReceiverTransmitter (USART) module is one of the two serialI/O modules, the other being the SSP module. TheUSART is also known as a Serial CommunicationsInterface or SCI. The USART can be configured as afull-duplex asynchronous system that cancommunicate with peripheral devices such as CRTterminals and personal computers, or it can beconfigured as a half-duplex synchronous system thatcan communicate with peripheral devices such as A/Dor D/A integrated circuits, serial EEPROMs, etc. In thesample program, it is configured as a full-duplexasynchronous system to communicate with a personalcomputer. In this application note, the USART is onlyused for transmission. The registers needed to be setup are:

• Baud Rate Generator Register (SPBRG) • Transmit Status and Control Register (TXSTA)• Receive Status and Control Register (RCSTA)• Transmit Data Register (TXREG)

The init_USART code segment provides a sampleconfiguration of the USART module (see Appendix A:“Source Code in Assembly” or Appendix B:“Source Code in C”). The SPBRG is a dedicated 8-bitBaud Rate Generator. The SPBRG register controlsthe period of a free-running 8-bit timer. InAsynchronous mode, bit BRGH (TXSTA<2>) alsocontrols the baud rate. In Synchronous mode, bitBRGH is ignored. To compute for the baud rate,Equation 8 is used.

EQUATION 8: BAUD RATE EQUATION

Since the baud rate is set to 2400 baud, the SPBRGvalue will be obtained by rearranging Equation 8.

EQUATION 9: SPBRG VALUE EQUATION

Substituting the value of FOSC = 4 MHz, an SPBRGdecimal value of 25 will be obtained. Simply convert itinto hex (19h) and load it into the SPBRG register.

The TXSTA register is where the Asynchronous modeand the 8-bit transmission are selected. The TransmitEnable (TXEN) bit of the TXSTA register enablestransmission and the Transmit Shift Register Status bit(TRMT) is a read-only bit which indicates the status ofthe Transmit Shift register (TSR). To start transmission,it is necessary to set the Serial Port Enable bit (SPEN)in the RCSTA register. Writing to the TXREG initiatesthe transmission. The code example copies the A/Dresult into the TXREG. The value is automaticallymoved into the TSR and shifted out on the RC6/TX pin.

PERIPHERAL INTEGRATIONAfter each peripheral is configured, the next step is tointegrate them with each other. The LOOP codesegment in the sample program shows how eachperipheral is connected to each other (see AppendixA: “Source Code in Assembly”). The program waitsfor TMR2IF to be set to signal the start of theAnalog-to-Digital conversion. When A/D is done, theprogram waits again for the TRMT Flag bit to be set.After the conversion is completed, the A/D result isstored in the ADRES register and the ADRES value iscopied to both the TXREG and CCPR2L registers to beoutputted on the TX and CCP2 pins, respectively.

Baud Rate FOSC

64 SPBRG Value 1+ --------------------------------------------------------------=

SPBRG Value FOSC

64 Baud Rate------------------------------------ 1–=

DS00000840B-page 4 2002-2014 Microchip Technology Inc.

Page 5: AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

AN840

FIRMWAREThe firmware flowchart in Figure 2 combines both theconfiguration and integration processes discussedearlier. At first, all I/O ports are initialized. Serial portsare also enabled for USART transmission followed bythe configuration of Timer2, A/D, CCP and USARTperipherals. For the A/D, only one analog input channelis selected during the configuration process. Timer2 isenabled and the program starts polling the TMR2IFFlag bit. TMR2IF sets whenever a match between theTMR2 and PR2 registers takes place. When a matchoccurs, TMR2IF is then cleared in software and A/Dconversion begins.

After the A/D conversion is completed, the programmonitors the TRMT bit to be set, indicating the TSRregister of the USART is empty and ready fortransmission. The A/D value is then written to theTXREG and CCPR2L registers. The next analogchannel is then selected and the process is repeated.

The USART and CCP outputs are received andprocessed by external hardware devices.

FIGURE 2: FIRMWARE FLOWCHART

Yes

Yes

Configure T 2

Configure A/D

Configure CCP for PWM mode

Configure USART

Enable

No

TMR2IF = 1 ?

Yes

Put A D Value in TXREG

Put A D Value in CCPR2L

Switch Analog Input Channel

Initialize PORTC Output Pins

Enable Serial Ports

Clear TMR2 to PR2 Match Flag Bit

Start A D Conversion

Initialize PORTA Input Pins

No

A/D Done ?

No

TRMT = 1 ?

Start

2002-2014 Microchip Technology Inc. DS00000840B-page 5

Page 6: AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

AN840

HARDWARE

FIGURE 3: PIC16F7X/PIC16C7X DEMO SCHEMATIC DIAGRAM

The schematic diagram of the hardware used in thisapplication note is shown in Figure 3. It is basically apart of the PICDEM™ 2 Plus schematic with a fewadditional components. RP1 and RP2 trimpots areused to demonstrate a method of switching betweenanalog input channels. They also determine the inputvoltage levels fed to the A/D. LED L1 is connected tothe PWM output pin, RC1/CCP2, which is in series withthe current limiting resistor, R1. U2 is an RS-232 linedriver that provides electrical interface between theUSART and the serial port connector, P1.

GND

U2 MA3232C

15

P1 DE9S - FRS

U1 PIC16F7 / PIC16C7

R3 10 Ω

C6 0.1 μF

C8 0.1 μF

C5 0.1 μF

R1 330 Ω

C3 0.1 μF

C4 0.1 μF

R2 470 Ω RP1

5 kΩ

RP2 5 kΩ

X1 4 MHz

C1 15 pF

C2 15 pF

C7 0.1 μF

VDD

VDD

VDD

6 7 8 9

1 2 3 4 5

1 16

C1- C2+

C2-

T1IN T2IN R1OUT R2OUT

V+ V-

T1OUT T2OUT RB1IN RB2IN

C1+

V CC 3

4

5

11 10 12 9

11 32

1

13

14

10 9 8 7 6

5 4 3 2

12

40 39 38 37 36 35 34 33

30 29 28 27 22 21 20 19

26

25 24 23 18 17 16

VDD VDD

MCLR

CLKIN

CLKOUT

RE2 RE1 RE0 RA5 RA4 RA3 RA2 RA1 RA0

VSS

2 6

14 7

13 8

RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0

RD7 RD6 RD5 RD4 RD3 RD2 RD1 RD0

RC7 RC6 RC5 RC4 RC3 RC2 RC1

VSS 1

1

DS00000840B-page 6 2002-2014 Microchip Technology Inc.

Page 7: AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

AN840

PROCESS FLOW

FIGURE 4: SIMPLIFIED APPLICATION BLOCK DIAGRAM

The application process flow is shown in Figure 4.When the analog input voltage is fed to the A/D, itconverts the input voltage into a corresponding digitalvalue. The input comes from AN0 or AN1 depending onthe configured analog input channel. The digital resultswill be sent to both the USART and the CCP. TheUSART sends this value to a Serial Terminal Program,which displays an output value on a certain formatdepending on the terminal configuration. Likewise, thePWM of the CCP varies the duty cycle of the outputpulse to control the brightness of an LED.

SERIAL TRANSMISSION AND DISPLAY

FIGURE 5: SERIAL TRANSMISSION BLOCK DIAGRAM

The USART output is sent to the Serial TerminalProgram by connecting the USB-to-UART SerialConverter to the serial port connector included in thePICDEM 2 Plus Demo Board and to the USB port of apersonal computer (see Figure 5). Microchip’sMCP2200 is used as the USB-to-UART SerialConverter for this application.

Since two analog channels are used in the A/D, twovalues will also be displayed on the PC monitor. ASerial Terminal Program is used to capture, control anddebug binary streams of data. It must be setup to2400 baud, eight data bits, one Stop bit and no parity tomatch the USART software configuration. Thedisplayed value can also be set to either ASCII, ANSI,hexadecimal, binary or other types of numericalrepresentation, depending on the Serial TerminalProgram features.

Analog Input Voltage A D

USART

LED Brightness

Serial Terminal Display

PIC16F7X/PIC16C7X

USART Serial Terminal Program

MCP2200 USB-to-UART Serial

Converter

USB

PICDEM 2 PLUS DEMO BOARD

Seria

l Por

t Co

nnec

tor

2002-2014 Microchip Technology Inc. DS00000840B-page 7

Page 8: AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

AN840

PWM DUTY CYCLE AND LED BRIGHTNESSFigure 6 shows sample PWM output waveforms withdifferent input voltages. If only the input voltage acrossAN0 (VAIN0) is adjusted and AN1 voltage (VAIN1) is setto zero, waveforms (A) and (B) will result. Note that asthe input voltage is increased, the Average Duty Cycle(DCAVE) also increases. In addition, the Average DCVoltage (VDC) across the PWM output pin alsoimproves, making the LED output glow brighter.However, when the voltage across the AN1 pin is alsoadjusted, a much higher output can be attained. In (C)and (D), VAIN0 is set to its previous value and VAIN1 isset to 2V. This leads to much higher DCAVE and VDCvalues and, in turn, to a much brighter LED output.

FIGURE 6: PWM OUTPUT WAVEFORMS

The brightness of the LED connected to the CCP2 pinis determined by combining the settings of the twotrimpots. A greater voltage across the two analog inputpins, AN0 and AN1, will result in a higher duty cycleratio and a brighter LED display output. Also, themaximum brightness will be achieved by setting thetwo trimpots to their maximum positions. The LED willbe turned off when the two trimpots are in theirminimum positions.

(A) VAIN0 = 1V, VAIN1 = 0V, DCAVE = 11.82%, VDC = 448.2 mV

(C) VAIN0 = 1V, VAIN1 = 2V, DCAVE = 29.95 %, VDC = 1.358V

(B) VAIN0 = 3.5 V, VAIN1 = 0V, DCAVE = 40.45%, VDC = 1.535V

(D) VAIN0 = 3.5V, VAIN1 = 2V, DCAVE = 53.82 %, VDC = 2.491V

000 000 000 000 001 001 CHS2:CHS0

DS00000840B-page 8 2002-2014 Microchip Technology Inc.

Page 9: AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

AN840

OUTPUT SIGNALS AND DISPLAYFigure 7 shows the summary of sample input andoutput signals. The analog input signals are purely DCvoltages which are set to 2V and 4V for AN0 and AN1,respectively. When Channel 0 (CHS2:CHS0 = 000) isselected, the pulse width is narrow (i.e., a low dutycycle ratio). Moreover, the USART output and the serialdecoding at the same instant are shown having a hexvalue of 4D. On the other hand, when Channel 1 isused (CHS2:CHS0 = 001), the pulse width is wider,which indicates a higher duty cycle ratio. The USARThex output is equal to E7, which is a much greater valuethan 4D.

FIGURE 7: SUMMARY OF INPUT AND OUTPUT SIGNAL WAVEFORMS

A screen capture of a Serial Terminal Program outputis shown in Figure 8. RealTerm, a freeware serialterminal software, is used for this example. The outputis displayed as Hex[space] in Figure 8 to match theserial decoding values in Figure 7. The output’snumerical representation and other display options canbe selected under the Display menu in the RealTermwindow.

PWM Output

USART Output

Serial Decoding

Analog Input

CHS2:CHS0

2002-2014 Microchip Technology Inc. DS00000840B-page 9

Page 10: AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

AN840

FIGURE 8: SERIAL TERMINAL PROGRAM DISPLAY

The program is capable of producing an average DCvoltage of almost 4.91V across the CCP2 pin outputand a minimum voltage of a few microvolts. In addition,the USART output terminal display range is from 00h toFFh. The minimum and maximum output valuesdepend mainly on the position of the two trimpots.Setting both trimpots to their minimum positions willproduce minimum output values, and maximum outputvalues for their maximum positions.

To conclude, a greater voltage across the analog inputterminal will result in a higher duty cycle ratio, a brighterLED output and a greater terminal display value. Onthe contrary, reducing the input voltage will also dim theLED and decrease the Serial Terminal display value.

CONCLUSIONIn order to achieve the desired output values anddisplay, it is often necessary to configure eachperipheral one step at a time before putting themtogether.

This application note describes a method on how theA/D, Timer2, CCP and USART are configured,implemented and integrated to achieve the desiredA/D output values and display. Data are alsoprovided to demonstrate how the peripherals behaveat specific time instants.

DS00000840B-page 10 2002-2014 Microchip Technology Inc.

Page 11: AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

AN840

APPENDIX A: SOURCE CODE IN ASSEMBLYSoftware License Agreement

The software supplied herewith by Microchip Technology Incorporated (the “Company”) is intended and supplied to you, theCompany’s customer, for use solely and exclusively with products manufactured by the Company.The software is owned by the Company and/or its supplier, and is protected under applicable copyright laws. All rights are reserved.Any use in violation of the foregoing restrictions may subject the user to criminal sanctions under applicable laws, as well as to civilliability for the breach of the terms and conditions of this license.THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES, WHETHER EXPRESS, IMPLIED ORSTATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR APARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLEFOR SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.

2002-2014 Microchip Technology Inc. DS00000840B-page 11

Page 12: AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

AN840

EXAMPLE A-1: SAMPLE PROGRAM IN ASSEMBLY;*******************************************************************************

; Revision Date:

; 04-03-2014

;

; File Name:

; FACT003B.asm

;

; Summary:

; This is the main file used for the Application Note AN840

;

; Hardware implementation requires:

; PICDEM2 PLUS DEMO BOARD

;

; Generation Information:

; Device : PIC16F74

; Compiler : MPASM v5.54

; MPLAB : MPLAB X 2.00

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

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

;Copyright (c) 2013 released Microchip Technology Inc. All rights reserved.

;

;Microchip licenses to you the right to use, modify, copy and distribute

;Software only when embedded on a Microchip microcontroller or digital signal

;controller that is integrated into your product or third party product

;(pursuant to the sublicense terms in the accompanying license agreement).

;

;You should refer to the license agreement accompanying this Software for

;additional information regarding your rights and obligations.

;

;SOFTWARE AND DOCUMENTATION ARE PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND,

;EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF

;MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.

;IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER

;CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR

;OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES

;INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR

;CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF

;SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES

;(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.

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

#include p16f74.inc

__CONFIG _FOSC_RC & _WDTE_OFF & _PWRTE_OFF & _CP_OFF & _BOREN_ON

org 0x00

init_PORTS

banksel TRISA ; goto bank 1

movlw 0x03

movwf TRISA ; set <Ra0:Ra1> as inputs

movlw 0x00

movwf TRISC ; make all PORTC pins as output

banksel RCSTA ; switch to bank 0

bsf RCSTA, SPEN ; enable serial ports

DS00000840B-page 12 2002-2014 Microchip Technology Inc.

Page 13: AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

AN840

EXAMPLE A-1: SAMPLE PROGRAM IN ASSEMBLY (CONTINUED)init_ADC

banksel ADCON1 ; switch to bank 1

movlw 0x04

movwf ADCON1 ; set RA0, RA1, RA3 as analog ports, and Vref = Vdd

banksel ADCON0 ; switch to bank 0

movlw 0xC1

movwf ADCON0 ; conversion clock = Frc

; set RA0/AN0 as analog channel

; turn on A/D Module

init_PWM

banksel PR2 ; switch to bank 1

movlw 0xFF

movwf PR2 ; set value for TIMER2 Period Register

banksel CCPR2L ; switch to bank 0

movlw 0x0F

movwf CCPR2L ; set initial value for Capture/Compare/PWM Register2

movlw 0x0F

movwf CCP2CON ; select PWM mode

init_TIMER2

movlw 0x00

movwf T2CON ; prescale = 1:1, disable TIMER2

init_USART

banksel SPBRG ; switch to bank 1

movlw 0x19

movwf SPBRG ; baud rate = 2400 for Fosc = 4 MHz

movlw 0x20

movwf TXSTA ; enable asynchronous transmission

banksel T2CON ; switch to bank 0

bsf T2CON, TMR2ON ; enable TIMER2

LOOP btfss PIR1, TMR2IF ; wait for TMR2 and PR2 to match

goto $-1

bcf PIR1, TMR2IF ; clear TMR2 and PR2 match flag bit

bsf ADCON0, GO ; start an A-to-D Conversion

btfsc ADCON0, GO ; wait for conversion to complete

goto $-1

banksel TXSTA ; switch to bank 1

btfss TXSTA, TRMT ; wait for TRMT flag bit to be set

goto $-1

banksel ADRES ; switch to bank 0

movf ADRES, W ; move ADRES register value to W register

movwf TXREG ; copy value on W register to TXREG

movwf CCPR2L ; copy value on W register to Duty Cycle register

movf ADCON0, W ; move ADCON0 register value to W register

xorlw 0x08

movwf ADCON0 ; change analog input channel

goto LOOP

END

2002-2014 Microchip Technology Inc. DS00000840B-page 13

Page 14: AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

AN840

APPENDIX B: SOURCE CODE IN C

EXAMPLE B-1: SAMPLE PROGRAM IN C/*******************************************************************************

File Name:

FACT003B.c

Summary:

This is the main file used for the Application Note AN840

Hardware implementation requires:

PICDEM2 PLUS DEMO BOARD

Generation Information :

Device : PIC16F74

Compiler : XC8 v1.30

MPLAB : MPLAB X 2.00

*******************************************************************************/

/*******************************************************************************

Copyright (c) 2013 released Microchip Technology Inc. All rights reserved.

Microchip licenses to you the right to use, modify, copy and distribute

Software only when embedded on a Microchip microcontroller or digital signal

controller that is integrated into your product or third party product

(pursuant to the sublicense terms in the accompanying license agreement).

You should refer to the license agreement accompanying this Software for

additional information regarding your rights and obligations.

SOFTWARE AND DOCUMENTATION ARE PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND,

EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF

MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.

IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER

CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR

OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES

INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR

CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF

SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES

(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.

*******************************************************************************/

#include<xc.h>

#pragma config FOSC = RC // Oscillator Selection bits (RC oscillator)

#pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT disabled)

#pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled)

#pragma config CP = OFF // FLASH Program Memory Code Protection bit (Code protection off)

#pragma config BOREN = ON // Brown-out Reset Enable bit (BOR enabled)

void init_ADC (void);

void init_PWM (void);

void init_TIMER2 (void);

void init_USART (void);

DS00000840B-page 14 2002-2014 Microchip Technology Inc.

Page 15: AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

AN840

EXAMPLE B-1: SAMPLE PROGRAM IN C (CONTINUED)void main (void)

{

TRISA = 0x03; // set RA0 and RA1 as inputs

TRISC = 0xBD; // make PORTC pins as output

SPEN = 1; // enable asynchronous serial ports

init_ADC ();

init_PWM();

init_TIMER2();

init_USART ();

TMR2ON = 1;

while(1)

{

while(!TMR2IF); // wait for TMR2 and PR2 match flag bit to be set

TMR2IF = 0; // clear TMR2 and PR2 match flag bit

GO_DONE = 1; // start an A-to-D Conversion

while(GO_DONE) // wait for conversion to complete

{

while(!TRMT); // wait for TRMT flag bit to be set

TXREG = ADRES; // put A/D result into TXREG register

CCPR2L = ADRES; // put A/D result into Duty Cycle register

}

ADCON0 ^= 0x08; // change analog input channel

}

}

void init_ADC (void)

{

ADCON1 = 0x04; // set RA0, RA1, RA3 as analog ports, and Vref = Vdd

ADCON0 = 0xC1; // conversion clock = Frc

// set RA0/AN0 as analog channel

// turn on A/D Module

}

void init_PWM (void)

{

PR2 = 0xFF; // PWM period = 256 us

CCPR2L = 0x0F; // PWM duty cycle MSB

CCP2CON = 0x0F; // PWM duty cycle LSB (CCP2CON<5:4> bits)

}

void init_TIMER2 (void)

{

T2CON = 0x00; // prescale = 1:1, disable TIMER2

}

void init_USART (void)

{

SPBRG = 0x19; // baud rate = 2400 for Fosc = 4 MHz

SYNC = 0; // select asychronous mode

TXEN = 1; // enable asynchronous transmission

}

2002-2014 Microchip Technology Inc. DS00000840B-page 15

Page 16: AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

Note the following details of the code protection feature on Microchip devices:• Microchip products meet the specification contained in their particular Microchip Data Sheet.

• Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the intended manner and under normal conditions.

• There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data Sheets. Most likely, the person doing so is engaged in theft of intellectual property.

• Microchip is willing to work with the customer who is concerned about the integrity of their code.

• Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not mean that we are guaranteeing the product as “unbreakable.”

Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of ourproducts. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such actsallow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.

Information contained in this publication regarding deviceapplications and the like is provided only for your convenienceand may be superseded by updates. It is your responsibility toensure that your application meets with your specifications.MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS ORIMPLIED, WRITTEN OR ORAL, STATUTORY OROTHERWISE, RELATED TO THE INFORMATION,INCLUDING BUT NOT LIMITED TO ITS CONDITION,QUALITY, PERFORMANCE, MERCHANTABILITY ORFITNESS FOR PURPOSE. Microchip disclaims all liabilityarising from this information and its use. Use of Microchipdevices in life support and/or safety applications is entirely atthe buyer’s risk, and the buyer agrees to defend, indemnify andhold harmless Microchip from any and all damages, claims,suits, or expenses resulting from such use. No licenses areconveyed, implicitly or otherwise, under any Microchipintellectual property rights.

DS00000840B-page 16

QUALITY MANAGEMENT SYSTEM CERTIFIED BY DNV

== ISO/TS 16949 ==

Trademarks

The Microchip name and logo, the Microchip logo, dsPIC, FlashFlex, KEELOQ, KEELOQ logo, MPLAB, PIC, PICmicro, PICSTART, PIC32 logo, rfPIC, SST, SST Logo, SuperFlash and UNI/O are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.

FilterLab, Hampshire, HI-TECH C, Linear Active Thermistor, MTP, SEEVAL and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U.S.A.

Silicon Storage Technology is a registered trademark of Microchip Technology Inc. in other countries.

Analog-for-the-Digital Age, Application Maestro, BodyCom, chipKIT, chipKIT logo, CodeGuard, dsPICDEM, dsPICDEM.net, dsPICworks, dsSPEAK, ECAN, ECONOMONITOR, FanSense, HI-TIDE, In-Circuit Serial Programming, ICSP, Mindi, MiWi, MPASM, MPF, MPLAB Certified logo, MPLIB, MPLINK, mTouch, Omniscient Code Generation, PICC, PICC-18, PICDEM, PICDEM.net, PICkit, PICtail, REAL ICE, rfLAB, Select Mode, SQI, Serial Quad I/O, Total Endurance, TSHARC, UniWinDriver, WiperLock, ZENA and Z-Scale are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.

SQTP is a service mark of Microchip Technology Incorporated in the U.S.A.

GestIC and ULPP are registered trademarks of Microchip Technology Germany II GmbH & Co. KG, a subsidiary of Microchip Technology Inc., in other countries.

All other trademarks mentioned herein are property of their respective companies.

© 2002-2014, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved.

Printed on recycled paper.

ISBN: 978-1-63276-239-9

Microchip received ISO/TS-16949:2009 certification for its worldwide

2002-2014 Microchip Technology Inc.

headquarters, design and wafer fabrication facilities in Chandler and Tempe, Arizona; Gresham, Oregon and design centers in California and India. The Company’s quality system processes and procedures are for its PIC® MCUs and dsPIC® DSCs, KEELOQ® code hopping devices, Serial EEPROMs, microperipherals, nonvolatile memory and analog products. In addition, Microchip’s quality system for the design and manufacture of development systems is ISO 9001:2000 certified.

Page 17: AN840 PIC16F7X/PIC16C7X Peripherals Configuration and ...

2002-2014 Microchip Technology Inc. DS00000840B-page 17

AMERICASCorporate Office2355 West Chandler Blvd.Chandler, AZ 85224-6199Tel: 480-792-7200 Fax: 480-792-7277Technical Support: http://www.microchip.com/supportWeb Address: www.microchip.comAtlantaDuluth, GA Tel: 678-957-9614 Fax: 678-957-1455Austin, TXTel: 512-257-3370 BostonWestborough, MA Tel: 774-760-0087 Fax: 774-760-0088ChicagoItasca, IL Tel: 630-285-0071 Fax: 630-285-0075ClevelandIndependence, OH Tel: 216-447-0464 Fax: 216-447-0643DallasAddison, TX Tel: 972-818-7423 Fax: 972-818-2924DetroitNovi, MI Tel: 248-848-4000Houston, TX Tel: 281-894-5983IndianapolisNoblesville, IN Tel: 317-773-8323Fax: 317-773-5453Los AngelesMission Viejo, CA Tel: 949-462-9523 Fax: 949-462-9608New York, NY Tel: 631-435-6000San Jose, CA Tel: 408-735-9110Canada - TorontoTel: 905-673-0699 Fax: 905-673-6509

ASIA/PACIFICAsia Pacific OfficeSuites 3707-14, 37th FloorTower 6, The GatewayHarbour City, KowloonHong KongTel: 852-2943-5100Fax: 852-2401-3431Australia - SydneyTel: 61-2-9868-6733Fax: 61-2-9868-6755China - BeijingTel: 86-10-8569-7000 Fax: 86-10-8528-2104China - ChengduTel: 86-28-8665-5511Fax: 86-28-8665-7889China - ChongqingTel: 86-23-8980-9588Fax: 86-23-8980-9500China - HangzhouTel: 86-571-8792-8115 Fax: 86-571-8792-8116China - Hong Kong SARTel: 852-2943-5100 Fax: 852-2401-3431China - NanjingTel: 86-25-8473-2460Fax: 86-25-8473-2470China - QingdaoTel: 86-532-8502-7355Fax: 86-532-8502-7205China - ShanghaiTel: 86-21-5407-5533 Fax: 86-21-5407-5066China - ShenyangTel: 86-24-2334-2829Fax: 86-24-2334-2393China - ShenzhenTel: 86-755-8864-2200 Fax: 86-755-8203-1760China - WuhanTel: 86-27-5980-5300Fax: 86-27-5980-5118China - XianTel: 86-29-8833-7252Fax: 86-29-8833-7256China - XiamenTel: 86-592-2388138 Fax: 86-592-2388130China - ZhuhaiTel: 86-756-3210040 Fax: 86-756-3210049

ASIA/PACIFICIndia - BangaloreTel: 91-80-3090-4444 Fax: 91-80-3090-4123India - New DelhiTel: 91-11-4160-8631Fax: 91-11-4160-8632India - PuneTel: 91-20-3019-1500Japan - OsakaTel: 81-6-6152-7160 Fax: 81-6-6152-9310Japan - TokyoTel: 81-3-6880- 3770 Fax: 81-3-6880-3771Korea - DaeguTel: 82-53-744-4301Fax: 82-53-744-4302Korea - SeoulTel: 82-2-554-7200Fax: 82-2-558-5932 or 82-2-558-5934Malaysia - Kuala LumpurTel: 60-3-6201-9857Fax: 60-3-6201-9859Malaysia - PenangTel: 60-4-227-8870Fax: 60-4-227-4068Philippines - ManilaTel: 63-2-634-9065Fax: 63-2-634-9069SingaporeTel: 65-6334-8870Fax: 65-6334-8850Taiwan - Hsin ChuTel: 886-3-5778-366Fax: 886-3-5770-955Taiwan - KaohsiungTel: 886-7-213-7830Taiwan - TaipeiTel: 886-2-2508-8600 Fax: 886-2-2508-0102Thailand - BangkokTel: 66-2-694-1351Fax: 66-2-694-1350

EUROPEAustria - WelsTel: 43-7242-2244-39Fax: 43-7242-2244-393Denmark - CopenhagenTel: 45-4450-2828 Fax: 45-4485-2829France - ParisTel: 33-1-69-53-63-20 Fax: 33-1-69-30-90-79Germany - DusseldorfTel: 49-2129-3766400Germany - MunichTel: 49-89-627-144-0 Fax: 49-89-627-144-44Germany - PforzheimTel: 49-7231-424750Italy - Milan Tel: 39-0331-742611 Fax: 39-0331-466781Italy - VeniceTel: 39-049-7625286 Netherlands - DrunenTel: 31-416-690399 Fax: 31-416-690340Poland - WarsawTel: 48-22-3325737 Spain - MadridTel: 34-91-708-08-90Fax: 34-91-708-08-91Sweden - StockholmTel: 46-8-5090-4654UK - WokinghamTel: 44-118-921-5800Fax: 44-118-921-5820

Worldwide Sales and Service

03/25/14