C Example: Comparators

From Mech
Jump to navigationJump to search


Program to implement an analog comparator.

First include header file with definitions for specific PIC. Set fuses. HS is type of external clock, low voltage protection (LVP) is off, and the watchdog timer (WDT) is off. External clock frequency of 20 MHz is specified.

  #include <18f4520.h>
  #use delay(clock=20000000)

Begin main body of program.

  void main(void) {

Setup the comparators C1 and C2. A0 is C1- and A3 is C1+. If C1+ > C1- C1 will output high (C1OUT = 1 = 5V). If C1- > C1+ C1 will output low. A second comparator (C2) has been set up, but is not being utilized. See the header file 18F4520.h for all possible constants used in the setup_comparator() function.


Setup an infinite loop using a while statement.

     while(TRUE) {

Check the output of the comparator and light an LED accordingly.


Associated Circuitry