How to Use Analog Comparators in PIC16F877A (Mode-1)
The following code demonstrate how to use analog comparator module in mode-1. In this mode comparator-1 can be used and comparator-2 will be off. The default output of the comparator-1 can be monitor on C1OUT on RA4 pin. You can also map this output on general purpose IOs. The code is written in “mikroC PRO for PIC v.6.6.3” IDE and simulation is done with Proteus 8.0 SP0. At the end of code, you can find complete project files for download.
Code in mikroC
// One Independent Comparator with Output
#define CMP_MODE 1
// default comparators o/p signals
sbit C1OUT_Dir at TRISA.B4;
sbit C1OUT_Out at PORTA.B4;
// user assign comparator o/p signals
sbit CMP1_Dir at TRISC.B0;
sbit CMP1_Out at PORTC.B0;
// function proto-type
void CMP_Setting(void);
void main(void)
{
// set direction as output
C1OUT_Dir = 0;
CMP1_Dir = 0;
// init value
C1OUT_Out = 0;
CMP1_Out = 0;
CMP_Setting();
while(1)
{
C1OUT_Out = CMCON.C1OUT;
// user assign comparators o/p signals
CMP1_Out = CMCON.C1OUT;
}
}
void CMP_Setting(void)
{
//Comparators Reset
#if CMP_MODE == 0
CMCON.CM2 = 0;
CMCON.CM1 = 0;
CMCON.CM0 = 0;
// One Independent Comparator with Output
#elif CMP_MODE == 1
CMCON.CM2 = 0;
CMCON.CM1 = 0;
CMCON.CM0 = 1;
// Two Independent Comparators
#elif CMP_MODE == 2
CMCON.CM2 = 0;
CMCON.CM1 = 1;
CMCON.CM0 = 0;
// Two Independent Comparators with Outputs
#elif CMP_MODE == 3
CMCON.CM2 = 0;
CMCON.CM1 = 1;
CMCON.CM0 = 1;
// Two Common Reference Comparators
#elif CMP_MODE == 4
CMCON.CM2 = 1;
CMCON.CM1 = 0;
CMCON.CM0 = 0;
// Two Common Reference Comparators with Outputs
#elif CMP_MODE == 5
CMCON.CM2 = 1;
CMCON.CM1 = 0;
CMCON.CM0 = 1;
// Four Inputs Multiplexed to Two Comparators
#elif CMP_MODE == 6
CMCON.CM2 = 1;
CMCON.CM1 = 1;
CMCON.CM0 = 0;
// Comparators Off
#elif CMP_MODE == 7
CMCON.CM2 = 1;
CMCON.CM1 = 1;
CMCON.CM0 = 1;
#endif
// Comparator Input Switch bit
// 1 = C1 VIN- connects to RA3/AN3
// C2 VIN- connects to RA2/AN2
// 0 = C1 VIN- connects to RA0/AN0
// C2 VIN- connects to RA1/AN1
CMCON.CIS = 0;
// Comparator 1 Output Inversion bit
// 1 = C1 output inverted
// 0 = C1 output not inverted
CMCON.C1INV = 0;
// Comparator 2 Output Inversion bit
// 1 = C2 output inverted
// 0 = C2 output not inverted
CMCON.C2INV = 0;
}
Download Files
For download “mikroC PRO for PIC” project and “Proteus 8.0” simulation files, click here.
Comments
Post a Comment