How to Use Analog Comparators in PIC16F877A (Mode-4)
The following code demonstrate how to use analog comparator module in mode-4. In this mode reference is common for two comparators. You can map output-1 C1OUT and output-2 C2OUT on any 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
// Two Common Reference Comparators
#define CMP_MODE 4
// 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
Post a Comment