AVR Comparator C programming example
Topics:
Lets write simple example on using AVR comparator module. Program is written in C and compiled with AVR-GCC compiler(WinAVR). Program example illustrates the case when Positive Comparator input is connected to Internal voltage regulator 1.23V by setting ACGB bitin ACSR register. Also as negative comparator input is taken ADC3 input via Multiplexer. As indicator LED is connected to PORTD0 pin. If input voltage is lower than 0.23V then Diode is OFF and if voltage exceed 1.23V diode lights ON. Diode state is changed with ANA_COMP_vect interrupt service routine on ACO bit toggle in ACSR register.

Working program code:
// ***********************************************************
// Project: Analog Comparator example
// Author: winavr.scienceprog.com
// Module description: Analog comparator example with positive comparator
// input connected to Vref 1.23V. When compared voltage exceed 1.23V LED lighst on.
// When voltage drops bellow - LED turns OFF. Comparator inputis connected to ADC3 pin.
// ***********************************************************
#include <avr\io.h>
#include <avr\interrupt.h>
#define AINpin PA3
#define LED PD0
void Init(){DDRA&=~(1<<AINpin);//as input
PORTA&=~(1<<AINpin);//no Pull-up
DDRD|=(1<<LED); //Led pin as output
PORTD|=(1<<LED);//Initally LED is OFF
SFIOR|=(1<<ACME);//enable multiplexer
ADCSRA&=~(1<<ADEN);//make sure ADC is OFF
ADMUX|=(0<<MUX2)|(1<<MUX1)|(1<<MUX0); //select ADC3 as negative AIN
ACSR|=
(0<<ACD)| //Comparator ON
(1<<ACBG)| //Connect 1.23V reference to AIN0
(1<<ACIE)| //Comparator Interrupt enable
(0<<ACIC)| //input capture disabled
(0<<ACIS1)| //set interrupt on output toggle
(0<<ACIS0);
sei();//enable global interrupts
}
// Interrupt handler for ANA_COMP_vect
//
ISR(ANA_COMP_vect) {if bit_is_clear(ACSR, ACO)
PORTD&=~(1<<LED);//LED is ON
else PORTD|=(1<<LED);//LED is OFF
}
// ***********************************************************
// Main program
//
int main(void) {Init();
while(1) { // Infinite loop; interrupts do the rest}
}
Comments
a problem about of this example.
hi to alll of dear friends who have tested this simple example.
my question is that i have tested this in winavr, but it does not response.when it is executed only PD0 output go high forever and LED is off also.where's the problem of this simple example????? plz help me
Add new comment