AN840

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

AN840

PIC16F7X/PIC16C7X Peripherals Configuration and Integration

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

CHS2:CHS0 After the ADCON0 and ADCON1 registers are


configured, the GO/DONE bit in ADCON0 is set to a ‘1’
001
AN1 to start the conversion and then monitored to track
VAIN when the conversion is complete. When the A/D
conversion is complete, the result is loaded into the
AN0
000 8-bit A/D ADRES register, the GO/DONE bit is cleared, and the
VDD A/D Interrupt Flag bit (ADIF) is set. The sample code
reads the ADRES register and passes it on to the
VREF 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.

 2002-2014 Microchip Technology Inc. DS00000840B-page 1


AN840
TIMERS TIMER2 AS THE PWM TIME BASE
The PIC16F7X and PIC16C7X families of devices have Timer2 is an 8-bit timer which can be used as the PWM
three timer modules. Each module can generate an time base for the CCP. For the PWM mode, the
interrupt to indicate that an event has occurred (i.e., following registers need to be configured:
timer overflow). • Timer2 Period Register (PR2)
The three timer modules are: • Timer2 Control Register (T2CON)
• Timer0 Module • PIR1 Register
• Timer1 Module The init_TIMER2 code segment shows an example
• Timer2 Module of the Timer2 configuration for PWM mode (see
Timer0 module is a simple 8-bit timer/counter. The Appendix A: “Source Code in Assembly” or
clock source can be either the internal system clock Appendix B: “Source Code in C”). The PWM output
(FOSC/4) or an external clock. In Timer mode, the has a time base (period) and a time that the output
Timer0 module will increment every instruction cycle stays high (duty cycle). The frequency of the PWM is
(without prescaler). In Counter mode, Timer0 will the inverse of the period (1/period). The PWM period is
increment, either on every rising or falling edge of pin specified by writing to the PR2 register. The PWM duty
RA4/T0CKI. cycle is latched from CCPR1L into CCPR1H. Setting
up the period and duty cycle is discussed in detail in
Timer1 module is a 16-bit timer/counter consisting of Section “PWM Mode of the CCP Module”. The
two 8-bit registers (TMR1H and TMR1L), which are TMR2ON bit of the T2CON register is set to start
readable and writable. The TMR1 register pair Timer2 operation. The TMR2 register is readable and
(TMR1H:TMR1L) increments from 0000h to FFFFh writable and is cleared on all device Resets. Timer2
and rolls over to 0000h. In Timer mode, Timer1 increments from 00h until it matches PR2 and then
increments every instruction cycle. In Counter mode, it resets to 00h on the next increment cycle. The TMR2
increments on every rising edge of the external clock Interrupt Flag bit (TMR2IF) is set whenever a match
input. between the TMR2 and PR2 registers occurs. In the
Timer2 is an 8-bit timer with a prescaler, a postscaler code example, the TMR2IF flag is cleared after every
and a Period register. Using the prescaler and TMR2/PR2 match to reset Timer2 and to signal a start
postscaler at their maximum settings, the overflow time of conversion for the A/D.
is the same as a 16-bit timer. Timer2 is the PWM time
base when the CCP module is used in the PWM mode.
Additional information and details on the use of these
three timers can be found in the PIC16F7X and
PIC16C7X family data sheets.

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

CCP1 CCP2 Comment


CCP1CON CCP2CON CCP Control register
CCPR1H CCPR2H CCP High byte
CCPR1L CCPR2L CCP Low byte
CCP1 CCP2 CCP pin
Additional information and details on the use of CCP
can be found in the PIC16F7X and PIC16C7X family
data sheets.

DS00000840B-page 2  2002-2014 Microchip Technology Inc.


AN840
PWM MODE OF THE CCP MODULE Note that the PWM period can also be computed using
Equation 4.
Both PIC16F7X and PIC16C7X have two CCP
modules that are identical in operation, with the EQUATION 4: PWM PERIOD EQUATION
exception being the operation of the Special Event
Trigger. In Pulse-Width Modulation (PWM) mode, the PWM Period =  PR2  + 1   4  T OSC 
CCPx pin produces up to a 10-bit resolution PWM
output. Since the CCPx pin is multiplexed with the (TMR2 Prescale Value)
PORT data latch, the corresponding TRIS bit must be
cleared to make the CCPx pin an output. In this
The PWM frequency (FPWM) is defined as
application note, only the PWM mode of the CCP2
1   PWM period  . For the code example, the Timer2
module is being used. The code example in Appendix
prescale value is set to ‘1’. TOSC is the reciprocal of the
A: “Source Code in Assembly” and Appendix B:
oscillator frequency (FOSC), which is 4 MHz.
“Source Code in C” sets up the following registers for
PWM operation: By equating Equation 3 and Equation 4, expressing
TOSC in terms of FOSC and rearranging the terms, the
• PORTC Data Direction Register (TRISC)
PR2 value can be obtained, as seen in Equation 5 and
• Timer2 Period Register (PR2)
Equation 6.
• CCP2CON Register
• CCPR2L Register
EQUATION 5: RESULT OF EQUATIONS 3
The code segment, init_PWM, is an example on how
AND 4
to initialize the CCP2 module for PWM mode. Since the
CCP2 pin is multiplexed with the RC1/CPP2 data latch, 1 1
-------------- =  PR2  + 1   4  ------------  TMR2 prescale value 
the TRISC<1> bit must be cleared to make the CCP1 FPWM FOSC
pin an output. The PWM period is specified by writing
to the PR2 register. The PWM period can be calculated
using Equation 4.
EQUATION 6: PR2 VALUE AS A FUNCTION
Equation 1 is the formula used to obtain the maximum OF FOSC AND FPWM
PWM resolution.
FOSC
EQUATION 1: MAXIMUM PWM PR2 = ------------------------------------------------------------------------------------
-–1
FPWM  4   TMR2 prescale value 
RESOLUTION EQUATION
FOSC 
Resolution = log 2 -------------
- bits Using Equation 6 will yield a PR2 decimal value equal
FPWM to 255 or a hexadecimal value FF. Any value greater
than 255 will result in a 100% duty cycle.
A maximum PWM resolution of ten bits is used. To get The PWM duty cycle is specified by writing to the
the value of the PR2 register, the PWM frequency and CCPR2L register and to the DCxB1:DCxB0
the PWM period must be calculated first. The PWM (CCP2CON<5:4>) bits. Up to 10-bit resolution is
frequency can be obtained by rearranging Equation 1. available: the CCPR2L contains the eight MSbs and
CCP2CON<5:4> contains the two LSbs. This 10-bit
EQUATION 2: PWM FREQUENCY value is represented by CCPR2L and CCP2CON<5:4>
EQUATION in Equation 7. The code examples in Appendix A:
“Source Code in Assembly” and Appendix B:
FOSC “Source Code in C” use only 8 bits (CCPR2L) of
FPWM = -----------------------
-
2Resolution resolution, so the CCP2CON<5:4> bits are
programmed to a ‘0’. The 8-bit A/D result is written into
Substituting the values of the PWM resolution (‘10’) the CCPR2L register after each A/D conversion. This
and oscillator frequency (4 MHz) to Equation 2 will yield allows the PWM output to be controlled by the
a PWM frequency of 3906.25 Hz. PWM period is measured A/D value. The duty cycle can be calculated
defined as shown in Equation 3. at any time using Equation 7.

EQUATION 3: RELATIONSHIP OF PWM EQUATION 7: PWM DUTY CYCLE AT ANY


PERIOD AND PWM TIME INSTANT
FREQUENCY
PWM Duty Cycle =  CCPR2L:CCP2CON<5:4>  
1
PWM Period = --------------
FPWM  TOSC   TMR2 prescale value

 2002-2014 Microchip Technology Inc. DS00000840B-page 3


AN840
UNIVERSAL SYNCHRONOUS The TXSTA register is where the Asynchronous mode
and the 8-bit transmission are selected. The Transmit
ASYNCHRONOUS RECEIVER Enable (TXEN) bit of the TXSTA register enables
TRANSMITTER (USART) transmission and the Transmit Shift Register Status bit
The Universal Synchronous Asynchronous Receiver (TRMT) is a read-only bit which indicates the status of
Transmitter (USART) module is one of the two serial the Transmit Shift register (TSR). To start transmission,
I/O modules, the other being the SSP module. The it is necessary to set the Serial Port Enable bit (SPEN)
USART is also known as a Serial Communications in the RCSTA register. Writing to the TXREG initiates
Interface or SCI. The USART can be configured as a the transmission. The code example copies the A/D
full-duplex asynchronous system that can result into the TXREG. The value is automatically
communicate with peripheral devices such as CRT moved into the TSR and shifted out on the RC6/TX pin.
terminals and personal computers, or it can be
configured as a half-duplex synchronous system that PERIPHERAL INTEGRATION
can communicate with peripheral devices such as A/D
or D/A integrated circuits, serial EEPROMs, etc. In the After each peripheral is configured, the next step is to
sample program, it is configured as a full-duplex integrate them with each other. The LOOP code
asynchronous system to communicate with a personal segment in the sample program shows how each
computer. In this application note, the USART is only peripheral is connected to each other (see Appendix
used for transmission. The registers needed to be set A: “Source Code in Assembly”). The program waits
up are: for TMR2IF to be set to signal the start of the
Analog-to-Digital conversion. When A/D is done, the
• Baud Rate Generator Register (SPBRG) program waits again for the TRMT Flag bit to be set.
• Transmit Status and Control Register (TXSTA) After the conversion is completed, the A/D result is
• Receive Status and Control Register (RCSTA) stored in the ADRES register and the ADRES value is
• Transmit Data Register (TXREG) copied to both the TXREG and CCPR2L registers to be
The init_USART code segment provides a sample outputted on the TX and CCP2 pins, respectively.
configuration of the USART module (see Appendix A:
“Source Code in Assembly” or Appendix B:
“Source Code in C”). The SPBRG 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<2>) also
controls the baud rate. In Synchronous mode, bit
BRGH is ignored. To compute for the baud rate,
Equation 8 is used.

EQUATION 8: BAUD RATE EQUATION

FOSC
Baud Rate = -------------------------------------------------------------
-
64    SPBRG Value + 1 

Since the baud rate is set to 2400 baud, the SPBRG


value will be obtained by rearranging Equation 8.

EQUATION 9: SPBRG VALUE EQUATION

FOSC
SPBRG Value = ------------------------------------ –1
64  Baud Rate

Substituting the value of FOSC = 4 MHz, an SPBRG


decimal value of 25 will be obtained. Simply convert it
into hex (19h) and load it into the SPBRG register.

DS00000840B-page 4  2002-2014 Microchip Technology Inc.


AN840
FIRMWARE
The firmware flowchart in Figure 2 combines both the
configuration and integration processes discussed
earlier. At first, all I/O ports are initialized. Serial ports
are also enabled for USART transmission followed by
the configuration of Timer2, A/D, CCP and USART
peripherals. For the A/D, only one analog input channel
is selected during the configuration process. Timer2 is
enabled and the program starts polling the TMR2IF
Flag bit. TMR2IF sets whenever a match between the
TMR2 and PR2 registers takes place. When a match
occurs, TMR2IF is then cleared in software and A/D
conversion begins.
After the A/D conversion is completed, the program
monitors the TRMT bit to be set, indicating the TSR
register of the USART is empty and ready for
transmission. The A/D value is then written to the
TXREG and CCPR2L registers. The next analog
channel is then selected and the process is repeated.
The USART and CCP outputs are received and
processed by external hardware devices.

FIGURE 2: FIRMWARE FLOWCHART

Start

Initialize PORTA Input Pins


Clear TMR2 to PR2 Match Flag Bit
Initialize PORTC Output Pins
Start AͬD Conversion
Enable Serial Ports

No
Configure TŝŵĞƌ2
A/D Done ?

Configure A/D
Yes

Configure CCP for PWM mode


No

Configure USART TRMT = 1 ?

Enable dŝŵĞƌϮ Yes

Put AͬD Value in TXREG


No
TMR2IF = 1 ? Put AͬD Value in CCPR2L

Yes Switch Analog Input Channel

 2002-2014 Microchip Technology Inc. DS00000840B-page 5


AN840
HARDWARE

FIGURE 3: PIC16F7X/PIC16C7X DEMO SCHEMATIC DIAGRAM


VDD U1
C7 PIC16F7y / PIC16C7y
0.1 μF 11 40
VDD RB7
32 39
VDD RB6
38
RB5
1 37 VDD
C1 MCLR RB4
36
15 pF RB3
13 35
CLKIN RB2
34
RB1
X1 33
C2 RB0 C4 C5 C8
4 MHz
15 pF 0.1 μF 0.1 μF 0.1 μF
14 30
CLKOUT RD7

16
29
RD6 C6
28 3 2

C1+

VCC
RD5 C1- V+ 0.1 μF
10 27 4 6
RE2 RD4 C2+ V-
9 22 C3
RE1 RD3
8 21 0.1 μF 5
RE0 RD2 C2-
7 20
VDD RA5 RD1
6 19 11 14 1
RA4 RD0 T1IN T1OUT 6
5 10 7 2
RA3 T2IN T2OUT 7
4 26 12 13 3
RA2 RC7 R1OUT RB1IN 8

GND
RP2 3 25 9 8 4
5 kΩ RA1 RC6 R2OUT RB2IN 9
2 24 5
R2 RA0 RC5
23 U2

15
RP1 470 Ω RC4 MA3232C
18
5 kΩ RC3 P1
17 R1 R3
>1 DE9S - FRS
RC2 330 Ω 10 Ω
12 VSS 16
RC1
ϯϭ VSS 1ϱ

The schematic diagram of the hardware used in this


application note is shown in Figure 3. It is basically a
part of the PICDEM™ 2 Plus schematic with a few
additional components. RP1 and RP2 trimpots are
used to demonstrate a method of switching between
analog input channels. They also determine the input
voltage levels fed to the A/D. LED L1 is connected to
the PWM output pin, RC1/CCP2, which is in series with
the current limiting resistor, R1. U2 is an RS-232 line
driver that provides electrical interface between the
USART and the serial port connector, P1.

DS00000840B-page 6  2002-2014 Microchip Technology Inc.


AN840
PROCESS FLOW

FIGURE 4: SIMPLIFIED APPLICATION


BLOCK DIAGRAM

LED
W
Brightness

Analog
Input Voltage AͬD

Serial
USART Terminal
Display

The application process flow is shown in Figure 4.


When the analog input voltage is fed to the A/D, it
converts the input voltage into a corresponding digital
value. The input comes from AN0 or AN1 depending on
the configured analog input channel. The digital results
will be sent to both the USART and the CCP. The
USART sends this value to a Serial Terminal Program,
which displays an output value on a certain format
depending on the terminal configuration. Likewise, the
PWM of the CCP varies the duty cycle of the output
pulse to control the brightness of an LED.

SERIAL TRANSMISSION AND


DISPLAY

FIGURE 5: SERIAL TRANSMISSION BLOCK DIAGRAM

MCP2200
Connector
Serial Port

USB Serial
USART USB-to-UART Serial Terminal Program
Converter
PIC16F7X/PIC16C7X

PICDEMΡ 2 PLUS DEMO BOARD

The USART output is sent to the Serial Terminal Since two analog channels are used in the A/D, two
Program by connecting the USB-to-UART Serial values will also be displayed on the PC monitor. A
Converter to the serial port connector included in the Serial Terminal Program is used to capture, control and
PICDEM 2 Plus Demo Board and to the USB port of a debug binary streams of data. It must be setup to
personal computer (see Figure 5). Microchip’s 2400 baud, eight data bits, one Stop bit and no parity to
MCP2200 is used as the USB-to-UART Serial match the USART software configuration. The
Converter for this application. displayed value can also be set to either ASCII, ANSI,
hexadecimal, binary or other types of numerical
representation, depending on the Serial Terminal
Program features.

 2002-2014 Microchip Technology Inc. DS00000840B-page 7


AN840
PWM DUTY CYCLE AND LED
BRIGHTNESS
Figure 6 shows sample PWM output waveforms with
different input voltages. If only the input voltage across
AN0 (VAIN0) is adjusted and AN1 voltage (VAIN1) is set
to zero, waveforms (A) and (B) will result. Note that as
the input voltage is increased, the Average Duty Cycle
(DCAVE) also increases. In addition, the Average DC
Voltage (VDC) across the PWM output pin also
improves, making the LED output glow brighter.
However, when the voltage across the AN1 pin is also
adjusted, a much higher output can be attained. In (C)
and (D), VAIN0 is set to its previous value and VAIN1 is
set to 2V. This leads to much higher DCAVE and VDC
values and, in turn, to a much brighter LED output.

FIGURE 6: PWM OUTPUT WAVEFORMS

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

CHS2:CHS0 000 001 000 000 001 000

(C) VAIN0 = 1V, VAIN1 = 2V, DCAVE = 29.95 %, VDC = 1.358V (D) VAIN0 = 3.5V, VAIN1 = 2V, DCAVE = 53.82 %, VDC = 2.491V

The brightness of the LED connected to the CCP2 pin


is determined by combining the settings of the two
trimpots. A greater voltage across the two analog input
pins, AN0 and AN1, will result in a higher duty cycle
ratio and a brighter LED display output. Also, the
maximum brightness will be achieved by setting the
two trimpots to their maximum positions. The LED will
be turned off when the two trimpots are in their
minimum positions.

DS00000840B-page 8  2002-2014 Microchip Technology Inc.


AN840
OUTPUT SIGNALS AND DISPLAY
Figure 7 shows the summary of sample input and
output signals. The analog input signals are purely DC
voltages which are set to 2V and 4V for AN0 and AN1,
respectively. When Channel 0 (CHS2:CHS0 = 000) is
selected, the pulse width is narrow (i.e., a low duty
cycle ratio). Moreover, the USART output and the serial
decoding at the same instant are shown having a hex
value of 4D. On the other hand, when Channel 1 is
used (CHS2:CHS0 = 001), the pulse width is wider,
which indicates a higher duty cycle ratio. The USART
hex output is equal to E7, which is a much greater value
than 4D.

FIGURE 7: SUMMARY OF INPUT AND OUTPUT SIGNAL WAVEFORMS

CHS2:CHS0    

Analog Input

PWM Output

USART Output

Serial Decoding

A screen capture of a Serial Terminal Program output


is shown in Figure 8. RealTerm, a freeware serial
terminal software, is used for this example. The output
is displayed as Hex[space] in Figure 8 to match the
serial decoding values in Figure 7. The output’s
numerical representation and other display options can
be selected under the Display menu in the RealTerm
window.

 2002-2014 Microchip Technology Inc. DS00000840B-page 9


AN840
FIGURE 8: SERIAL TERMINAL PROGRAM DISPLAY

The program is capable of producing an average DC


voltage of almost 4.91V across the CCP2 pin output
and a minimum voltage of a few microvolts. In addition,
the USART output terminal display range is from 00h to
FFh. The minimum and maximum output values
depend mainly on the position of the two trimpots.
Setting both trimpots to their minimum positions will
produce minimum output values, and maximum output
values for their maximum positions.
To conclude, a greater voltage across the analog input
terminal will result in a higher duty cycle ratio, a brighter
LED output and a greater terminal display value. On
the contrary, reducing the input voltage will also dim the
LED and decrease the Serial Terminal display value.

CONCLUSION
In order to achieve the desired output values and
display, it is often necessary to configure each
peripheral one step at a time before putting them
together.
This application note describes a method on how the
A/D, Timer2, CCP and USART are configured,
implemented and integrated to achieve the desired
A/D output values and display. Data are also
provided to demonstrate how the peripherals behave
at specific time instants.

DS00000840B-page 10  2002-2014 Microchip Technology Inc.


AN840
APPENDIX A: SOURCE CODE IN ASSEMBLY
Software License Agreement
The software supplied herewith by Microchip Technology Incorporated (the “Company”) is intended and supplied to you, the
Company’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 civil
liability 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 OR
STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE
FOR SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.

 2002-2014 Microchip Technology Inc. DS00000840B-page 11


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.


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


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.


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


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 our
products. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such acts
allow 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 device Trademarks


applications and the like is provided only for your convenience
The Microchip name and logo, the Microchip logo, dsPIC,
and may be superseded by updates. It is your responsibility to
FlashFlex, KEELOQ, KEELOQ logo, MPLAB, PIC, PICmicro,
ensure that your application meets with your specifications.
PICSTART, PIC32 logo, rfPIC, SST, SST Logo, SuperFlash
MICROCHIP MAKES NO REPRESENTATIONS OR
and UNI/O are registered trademarks of Microchip Technology
WARRANTIES OF ANY KIND WHETHER EXPRESS OR
Incorporated in the U.S.A. and other countries.
IMPLIED, WRITTEN OR ORAL, STATUTORY OR
OTHERWISE, RELATED TO THE INFORMATION, FilterLab, Hampshire, HI-TECH C, Linear Active Thermistor,
INCLUDING BUT NOT LIMITED TO ITS CONDITION, MTP, SEEVAL and The Embedded Control Solutions
QUALITY, PERFORMANCE, MERCHANTABILITY OR Company are registered trademarks of Microchip Technology
FITNESS FOR PURPOSE. Microchip disclaims all liability Incorporated in the U.S.A.
arising from this information and its use. Use of Microchip Silicon Storage Technology is a registered trademark of
devices in life support and/or safety applications is entirely at Microchip Technology Inc. in other countries.
the buyer’s risk, and the buyer agrees to defend, indemnify and
Analog-for-the-Digital Age, Application Maestro, BodyCom,
hold harmless Microchip from any and all damages, claims,
chipKIT, chipKIT logo, CodeGuard, dsPICDEM,
suits, or expenses resulting from such use. No licenses are
dsPICDEM.net, dsPICworks, dsSPEAK, ECAN,
conveyed, implicitly or otherwise, under any Microchip
ECONOMONITOR, FanSense, HI-TIDE, In-Circuit Serial
intellectual property rights.
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

QUALITY MANAGEMENT SYSTEM Microchip received ISO/TS-16949:2009 certification for its worldwide
headquarters, design and wafer fabrication facilities in Chandler and
CERTIFIED BY DNV 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
== ISO/TS 16949 == 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.

DS00000840B-page 16  2002-2014 Microchip Technology Inc.


Worldwide Sales and Service
AMERICAS ASIA/PACIFIC ASIA/PACIFIC EUROPE
Corporate Office Asia Pacific Office India - Bangalore Austria - Wels
2355 West Chandler Blvd. Suites 3707-14, 37th Floor Tel: 91-80-3090-4444 Tel: 43-7242-2244-39
Chandler, AZ 85224-6199 Tower 6, The Gateway Fax: 91-80-3090-4123 Fax: 43-7242-2244-393
Tel: 480-792-7200 Harbour City, Kowloon Denmark - Copenhagen
India - New Delhi
Fax: 480-792-7277 Hong Kong Tel: 45-4450-2828
Tel: 91-11-4160-8631
Technical Support: Tel: 852-2943-5100 Fax: 45-4485-2829
Fax: 91-11-4160-8632
http://www.microchip.com/ Fax: 852-2401-3431
India - Pune France - Paris
support
Australia - Sydney Tel: 91-20-3019-1500 Tel: 33-1-69-53-63-20
Web Address:
Tel: 61-2-9868-6733 Fax: 33-1-69-30-90-79
www.microchip.com Japan - Osaka
Fax: 61-2-9868-6755 Germany - Dusseldorf
Atlanta Tel: 81-6-6152-7160
China - Beijing Tel: 49-2129-3766400
Duluth, GA Fax: 81-6-6152-9310
Tel: 86-10-8569-7000 Germany - Munich
Tel: 678-957-9614 Japan - Tokyo
Fax: 86-10-8528-2104 Tel: 49-89-627-144-0
Fax: 678-957-1455 Tel: 81-3-6880- 3770
China - Chengdu Fax: 49-89-627-144-44
Austin, TX Fax: 81-3-6880-3771
Tel: 86-28-8665-5511 Germany - Pforzheim
Tel: 512-257-3370 Korea - Daegu
Fax: 86-28-8665-7889 Tel: 49-7231-424750
Boston Tel: 82-53-744-4301
Westborough, MA China - Chongqing Fax: 82-53-744-4302 Italy - Milan
Tel: 774-760-0087 Tel: 86-23-8980-9588 Tel: 39-0331-742611
Korea - Seoul
Fax: 774-760-0088 Fax: 86-23-8980-9500 Fax: 39-0331-466781
Tel: 82-2-554-7200
Chicago China - Hangzhou Fax: 82-2-558-5932 or Italy - Venice
Itasca, IL Tel: 86-571-8792-8115 82-2-558-5934 Tel: 39-049-7625286
Tel: 630-285-0071 Fax: 86-571-8792-8116 Netherlands - Drunen
Malaysia - Kuala Lumpur
Fax: 630-285-0075 China - Hong Kong SAR Tel: 60-3-6201-9857 Tel: 31-416-690399
Cleveland Tel: 852-2943-5100 Fax: 60-3-6201-9859 Fax: 31-416-690340
Independence, OH Fax: 852-2401-3431 Poland - Warsaw
Malaysia - Penang
Tel: 216-447-0464 China - Nanjing Tel: 48-22-3325737
Tel: 60-4-227-8870
Fax: 216-447-0643 Tel: 86-25-8473-2460 Fax: 60-4-227-4068 Spain - Madrid
Dallas Fax: 86-25-8473-2470 Tel: 34-91-708-08-90
Philippines - Manila
Addison, TX China - Qingdao Fax: 34-91-708-08-91
Tel: 63-2-634-9065
Tel: 972-818-7423 Tel: 86-532-8502-7355 Fax: 63-2-634-9069 Sweden - Stockholm
Fax: 972-818-2924
Fax: 86-532-8502-7205 Tel: 46-8-5090-4654
Singapore
Detroit China - Shanghai Tel: 65-6334-8870 UK - Wokingham
Novi, MI Tel: 86-21-5407-5533 Fax: 65-6334-8850 Tel: 44-118-921-5800
Tel: 248-848-4000 Fax: 86-21-5407-5066
Taiwan - Hsin Chu Fax: 44-118-921-5820
Houston, TX
China - Shenyang Tel: 886-3-5778-366
Tel: 281-894-5983
Tel: 86-24-2334-2829 Fax: 886-3-5770-955
Indianapolis Fax: 86-24-2334-2393
Noblesville, IN Taiwan - Kaohsiung
China - Shenzhen Tel: 886-7-213-7830
Tel: 317-773-8323
Tel: 86-755-8864-2200
Fax: 317-773-5453 Taiwan - Taipei
Fax: 86-755-8203-1760 Tel: 886-2-2508-8600
Los Angeles
China - Wuhan Fax: 886-2-2508-0102
Mission Viejo, CA
Tel: 86-27-5980-5300 Thailand - Bangkok
Tel: 949-462-9523
Fax: 86-27-5980-5118 Tel: 66-2-694-1351
Fax: 949-462-9608
China - Xian Fax: 66-2-694-1350
New York, NY
Tel: 631-435-6000 Tel: 86-29-8833-7252
Fax: 86-29-8833-7256
San Jose, CA
Tel: 408-735-9110 China - Xiamen
Tel: 86-592-2388138
Canada - Toronto
Fax: 86-592-2388130
Tel: 905-673-0699
Fax: 905-673-6509 China - Zhuhai
Tel: 86-756-3210040
03/25/14
Fax: 86-756-3210049

 2002-2014 Microchip Technology Inc. DS00000840B-page 17

You might also like