[Home] [Downloads] [Search] [Help/forum]

Register forum user name Search FAQ

Gammon Forum

[Folder]  Entire forum
-> [Folder]  Electronics
. -> [Folder]  Microprocessors
. . -> [Subject]  Using the Arduino Analog Comparator

Using the Arduino Analog Comparator

Postings by administrators only.

[Refresh] Refresh page

Posted by Nick Gammon   Australia  (23,002 posts)  [Biography] bio   Forum Administrator
Date Sat 26 Jan 2013 10:09 PM (UTC)

Amended on Tue 03 Apr 2018 05:57 AM (UTC) by Nick Gammon

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;

  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.

- Nick Gammon

www.gammon.com.au, www.mushclient.com
[Go to top] top

The dates and times for posts above are shown in Universal Co-ordinated Time (UTC).

To show them in your local time you can join the forum, and then set the 'time correction' field in your profile to the number of hours difference between your location and UTC time.


Postings by administrators only.

[Refresh] Refresh page

Go to topic:           Search the forum

[Go to top] top

Quick links: MUSHclient. MUSHclient help. Forum shortcuts. Posting templates. Lua modules. Lua documentation.

Information and images on this site are licensed under the Creative Commons Attribution 3.0 Australia License unless stated otherwise.


Written by Nick Gammon - 5K   profile for Nick Gammon on Stack Exchange, a network of free, community-driven Q&A sites   Marriage equality

Comments to: Gammon Software support
[RH click to get RSS URL] Forum RSS feed ( https://gammon.com.au/rss/forum.xml )

[Best viewed with any browser - 2K]    [Hosted at HostDash]