# Pic Lab, PIC16, Experiment #7, The comparator module

The task: To learn how to use the comparator

Tools: PIC16f628a, proteus

First of all, let’s take a look at the register CMCON.

C2OUT: The output bit of the comparator 2
If C2INV = 0:
1 = C2 VIN+ > C2 VIN-
0 = C2 VIN+ < C2 VIN-

When C2INV = 1:
1 = C2 VIN+ < C2 VIN-
0 = C2 VIN+ > C2 VINbit
C1OUT: The output bit of the comparator 1
If C1INV = 0:
1 = C1 VIN+ > C1 VIN-
0 = C1 VIN+ < C1 VIN- When
C1INV = 1:
1 = C1 VIN+ < C1 VIN-
0 = C1 VIN+ > C1 VIN
C2INV: An inversion of the output bit of comparator #2
1 = C2 an output bit is inverted
0 = C2 an output bit is not inverted
C1INV: An inversion of the output bit of the comparator #1
1 = C1 the output bit is inverted
0 = C1 the output bit is not inverted
CIS: The input pin of the comparator for some of modes
if CM<2:0>: = 001
Then:
1 = C1 VIN- connected to RA3
0 = C1 VIN- connected to RA0
If CM<2:0> = 010
Then:
1 = C1 VIN- connected RA3
C2 VIN- connected RA2
0 = C1 VIN- connected to RA0
C2 VIN- connected RA1
CM<2:0>: Modes of comparator operation

All modes are represented in the picture below (taken from the datasheet):

For this experiment we need just one compartor, so lets put CM = 101

#include <htc.h>
#define _XTAL_FREQ 4000000
#define LED RB0
__CONFIG(WDTDIS & UNPROTECT & MCLREN & LVPDIS & HS);

void main(void) {
CMCON = 0b10000101;
TRISA = 0xFF;
TRISB = 0x00;
PORTB = 0;

for (;;) { LED = C2OUT;}

}

There is a reference voltage equal to 2V at the RA1 pin, and the RA2 pin has a sinewave with 5V amplitude. And then we have a output of comparator:

The sources are here