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

The following code demonstrate how to use analog comparator module in mode-5. In this mode positive input of the two comparators are combine. The default output of each comparator can be monitor on C1OUT on RA4 pin and C2OUT on RA5 pin. You can also map theses outputs 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

// Two Common Reference Comparators with Outputs
#define CMP_MODE    5
// default comparators o/p signals
sbit C1OUT_Dir at TRISA.B4;
sbit C2OUT_Dir at TRISA.B5;
sbit C1OUT_Out at PORTA.B4;
sbit C2OUT_Out at PORTA.B5;
// 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
C1OUT_Dir = 0;
C2OUT_Dir = 0;
CMP1_Dir = 0;
CMP2_Dir = 0;
// init value
C1OUT_Out = 0;
C2OUT_Out = 0;
CMP1_Out = 0;
CMP2_Out = 0;
CMP_Setting();
while(1)
{
// default signals, availble in mode 1, 3 and 5
C1OUT_Out = CMCON.C1OUT;
C2OUT_Out = CMCON.C2OUT;
// 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)