Warning to KiCad Users: Avoid all links to kicad - pcb.org – Use kicad.org

Starting Electronics needs your help! Please make a donation to help cover our hosting and other costs. Click the donate button to send a donation of any amount.

Donations Received:

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
        if (ACSR & (1 << ACO)) {            // comparator output high?
            // flash LED if comparator output is high
            PORTD |=  (1 << PD5);			// switch PD5 LED on
            PORTD &= ~(1 << PD5);			// switch PD5 LED off
        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)

Books that may interest you:

C Programming with Arduino Book Ultimate Arduino MEGA 2560 Hardware Manual Ultimage Arduino Uno Hardware Manual

← Go back to Part 14