Skip to content

Instantly share code, notes, and snippets.

@szczys
Created December 3, 2011 22:56
Show Gist options
  • Save szczys/1428418 to your computer and use it in GitHub Desktop.
Save szczys/1428418 to your computer and use it in GitHub Desktop.
ATmega168 Analog Comparator example
/*
AVR ATmega168 Analog Comparator Demonstration
by Mike Szczys
I'm using a voltage divider with a photoresistor on
PC6 and a voltage divider with equal values on PC7
to yield a 2.5V reference signal.
The analog comparator is set to throw an interrupt
whenever there is a zero crossing. I then check the
ACO bit to see if I should turn on LEDs on Port B or
not.
jumptuck.com
*/
#include <avr/io.h>
#include <avr/interrupt.h>
void initComparator(void){
cli();
ACSR |= (1<<ACIE); //Enable analog comparator interrupt
sei();
}
void initIO(void){
DDRB = 0xFF; //PortB as Outputs
PORTB = 0xFF; //All outputs high
}
int main(void){
initIO(); //Initialize I/O
initComparator(); //Initialize the analog comparator
while(1){ }
}
ISR (ANALOG_COMP_vect) {
//Check for rising or falling edge
if (ACSR & (1<<ACO)) PORTB = 0x00;
else PORTB = 0xFF;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment