8

I am trying to find some information on how to use the analog comparator on an Atmega328 to detect when an analog pin has reached a certain voltage (3.16 volts).

I cannot find any example code that says how to do this, although I have read that the analog comparator can compare the voltage on an analog pin with the voltage output by a PWM pin. I do not understand how this would work as the PWM pins do not output an analog voltage, but a pulse width modulated square wave. Is it possible to use the comparator to compare with a certain voltage this way?

I have tried polling with analogRead(), but it is too slow for my application.

3871968
  • 308
  • 1
  • 2
  • 10

2 Answers2

5

I have a page about the analog comparator that has code:

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 is for a fixed reference voltage, for example:

Reference voltage

Nick Gammon
  • 38,901
  • 13
  • 69
  • 125
1

You need a low-pass filter between the PWM output and the comparator input. This will allow you to produce an analog voltage from the PWM output, which can the be used as a reference voltage for the comparator.

Typically, a simple RC LPF is sufficient. Choose a large time constant relative to your PWM frequency (the Arduino defaults to 490Hz) so that you don't have ripple in your reference voltage.

uint128_t
  • 819
  • 5
  • 14