How to Use Analog Comparators in PIC16F877A (Mode-2)

The following code demonstrate how to use analog comparator module in mode-2. In this mode two independent comparators are used and individual comparator output can be maped on any output pin. 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

#define CMP_MODE    2
// user assign comparator o/p signals
sbit CMP1_Dir at TRISC.B0;
sbit CMP2_Dir at TRISC.B1;
sbit CMP1_Out at PORTC.B0;
sbit CMP2_Out at PORTC.B1;
// function proto-type
void CMP_Setting(void);
void main(void)
{
// set direction as output
CMP1_Dir = 0;
CMP2_Dir = 0;
// init value
CMP1_Out = 0;
CMP2_Out = 0;
CMP_Setting();
while(1)
{
// user assign comparators o/p signals
CMP1_Out = CMCON.C1OUT;
CMP2_Out = CMCON.C2OUT;
}
}
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

Popular posts from this blog

How to Program Parallel Slave Port (PSP) in PIC16F877A

How to Program Interrupts in PIC16F877A

How to Program SPI in PIC16F877A (Slave Mode)