Starting Electronics Needs Your Help!
It is that time of the year when we need to pay for web hosting and buy new components and equipment for new tutorials. You can help by making a donation. Contribute to this website by clicking the Donate button. The total will be updated once daily. (You may need to clear your browser cache to see the updates.)

Target Amount: $2000
Amount Raised: $1224

Donations Received

Top Donor: C.C. $100

X

Using the ATtiny2313 Comparator

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.

This video shows the circuit operating.

Can't see the video? View on YouTube →

Circuit Diagram

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).

ATtiny2313 comparator circuit

The location of the two comparator pins is shown in this image.

Comparator input pins

C Source Code

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
        }            
    }
}

Atmel Studio Project

The Atmel Studio 6 project with source and output files can be downloaded here:

comparator.zip (14.5kB)

Amazon.com

Amazon.co.uk

← Go back to Part 14