A couple of months ago I wrote analogComp, a library that can be used to manage the internal analog comparator of the Atmel microcontrollers. An analog comparator is essentially an op-amp used as a voltage comparator that sets to High its output when the voltage that is present on the non-inverting input is greater than the voltage of the inverting input. These inputs can be two external pins. The library supports a wide variety of MCUs and let the user manages a single comparison or to raise an interrupt every time a specific condition happens.
Just include the library in your sketches and then sets what the library has to use as inverting (AIN-) and non-inverting (AIN+) input of the analog comparator. Usually, AIN+ is connected to AIN0 pin and AIN- is connected to AIN1 pin. To know which pins are these, check the datasheet. I.e., for Atmega328è, pin AIN0 is D6 while AIN1 is D7. AIN+ can also be connected to the internal voltage reference while AIN- that also be connected to any of the analog input pins (with some limitations, see below).
The method setOn() is used to choose the inputs:
For AIN+ the following values are available: AIN0, INTERNAL_REFERENCE For AIN-: AIN1, A0..Ax (a specific analog input) AIN+ and AIN- are optional, if not specified, AIN0 and AIN1 will be used.
An interrupt can be hooked to a specific event:
where myFunction is the function to be called, and event can be CHANGE (when AIN+ begins greater than AIN- or AIN+ begins smaller than AIN-), RISING (when AIN+ begins greater than AIN-) and FALLING (when AIN+ begins smaller than AIN-). eventi is optional, CHANGE is the default value. We can also disable an interrupt previously set using :
The user can set a time to wait for AIN+ begins greater than AIN-:
timeout is optional, and it's the number of milliseconds to wait before to leave the instruction (default value is 5000). This method returns false (0) if the voltage on AIN- remains greater than the voltage on AIN+ for all the time specified by teimout, or true (1) if AIN+ has raised over AIN- during that period.
To shut down the analog comparator and disable the interrupt eventually set just call:
Supported microcontrollers Actually the library supports the following MCUs:
- Atmega48/88/168/328 (Arduino UNO)
- Atmega640/1280/1281/2560/2561 (Arduino MEGA)
- Atmega32U4 (Arduino Leonardo)
- Attiny2313/4313: due to the fact that these MCUs don't have an integrated ADC, it is only possible to use AIN1 for AIN-
- Atmega32U4: the AIN- of this MCU can be only connected to an analog input pin because the Atmega32U4 doesn't have the AIN1 pin
For more infos and to download the code, please go to this page