C Example: Comparators

From Mech
Jump to: navigation, search

Contents

Code

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>
  #fuses HS,NOWDT,NOPROTECT,NOLVP
  #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_comparator(A0_A3_A1_A2);

Setup an infinite loop using a while statement.

     while(TRUE) {

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

        if(C1OUT){
           output_low(PIN_D0);}
        else{
           output_high(PIN_D0);}
     }
  }

Associated Circuitry

Personal tools