Using the Arduino Analog Comparator

Posted by Nick Gammon on Sat 26 Jan 2013 10:09 PM — 1 posts, 61,448 views.

Australia Forum Administrator #0
The Atmega328 chip has a built-in analog comparator. That is, it can trigger an interrupt when an incoming voltage passes a threshold.

The incoming voltage is on the AIN0 (positive) pin which is pin 12 on the actual chip, and D6 on the Arduino board. The reference voltage (negative) pin is pin 13 on the chip, and D7 on the Arduino.

Example setup:



This is faster than doing an ADC (analog to digital) comparison because it is comparing to a single voltage, not attempting to do a full conversion (which can take something like 104 µs).

An example sketch follows:


volatile boolean triggered;

ISR (ANALOG_COMP_vect)
  {
  triggered = true;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

void loop ()
  {
  if (triggered)
    {
    Serial.println ("Triggered!"); 
    triggered = false;
    }
  
  }  // end of loop


This simple example triggers on a falling edge (you can choose toggle, rising or falling) and sets a flag in the interrupt service routine.