Created on: 3 June 2013
Part 15 of the ATtiny2313 Tutorial
The comparator in the ATtiny2313 is used to compare a changing voltage with a fixed reference voltage. When the changing voltage exceeds the reference voltage, an LED is flashed.
A fixed reference voltage is applied to the comparator negative pin (AIN1, PB1, pin 13) by using a two resistor voltage divider consisting of R3 and R4. This applies half the supply voltage to the comparator negative pin.
A potentiometer applies a voltage that can be changed to the comparator positive pin (AIN0, PB0, pin 12).
The location of the two comparator pins is shown in this image.
The code simply checks the ACO flag in the ACSR register to see if the output of the comparator is high. If the comparator output is high, the LED is flashed on and off. If the output of the comparator is low, the LED is switched off.
The comparator output will be high when the voltage on AIN0 (comparator + input) is higher than the voltage on AIN1 (comparator - input).
#define F_CPU 1000000UL #include <avr/io.h> #include <util/delay.h> int main(void) { DDRD |= (1 << PD5); // LED on PD5 while(1) { if (ACSR & (1 << ACO)) { // comparator output high? // flash LED if comparator output is high PORTD |= (1 << PD5); // switch PD5 LED on _delay_ms(50); PORTD &= ~(1 << PD5); // switch PD5 LED off _delay_ms(50); } else { // comparator output low, so switch LED off PORTD &= ~(1 << PD5); // switch PD5 LED off } } }
The Atmel Studio 6 project with source and output files can be downloaded here:
comparator.zip (14.5kB)