/* comparator.c Comparator on pin PD7/AIN1- with internal ref LED output */ // Arduino UNO R3 // AVR_ATmega328P #define F_CPU 16000000UL #include #include void init_ac( void ); int main(void) { DDRB |= ( 1 << PB5 ); // LED is output PORTB &= ~( 1 << PB5 ); // LED is off init_ac( ); sei(); // enable global interrupts while(1) { // all is done in ISR } return 0; // never reached } /* *********************************** */ /* INTERRUPTS */ /* *********************************** */ // Interrupt Service Routine attached to ANALOG_COMP vector ISR(ANALOG_COMP_vect) { // Bits in ACSR register: "ACD ACBG ACO ACI ACIE ACIC ACIS1 ACIS0" if( ( ACSR & ( 1 << ACO ))==0 ) PORTB |= ( 1 << PB5 ); // Comparator output "0" -> LED "1" on else PORTB &= ~( 1 << PB5 ); // LED "0" off } /* *********************************** */ /* FUNCTIONS */ /* *********************************** */ void init_ac( void ) { DDRD &= ~( 1 << PD7 ); // PD7/AIN1- "0" direction is input // Bits in DIDR1 register: "- - - - - - AIN1D AIN0D" DIDR1 |= ( 1 << AIN1D ); // Turn off the digital buffer at PD7/AIN1- // Bits in ACSR register: "ACD ACBG ACO ACI ACIE ACIC ACIS1 ACIS0" // ACSR &= ~( 1 << ACD ); // Comparator ON is default nothing has to be done ACSR |= ( 1 << ACBG ); // Set internal 1.1 V reference to AIN0+ ACSR |= ( 1 << ACIE ); // Comparator Interrupt enable // ACSR &= ~( 1 << ACIC ); // input capture disable is default nothing has to be done // ACSR &= ~( (1 << ACIS1) | (1 << ACIS0) ); // "------00" output toggle interrupt is default } /* *********************************** */ /* HARDWARE */ /* *********************************** */ /* Chip ATMega328 Arduino Uno R3 stackable header _______ Digital: _____/ \__ Analog: ______________ ______________ -|D00 >RXD A5|- | \/ | -|D01 -|D07 Vin|- +5V ---|07 VCC GND 22|--- Gnd | GND|- Gnd ---|08 GND AREF 21|--- Vin -|D08 GND|- Xtal |X|--|09 PB6/OSC1 AVCC 20|--- +5V -|D09~ +5V|- 16MHz |X|--|10 PB7/OSC2 SCK/PB5 19|-(D13)->- LED -|D10~ +3.3V|- -(D05)-|11 PD5/PWM MISO/PB4 18|-(D12)- -|D11~ Res|- -(D06)-|12 PD6/PWM PWM/MOSI/PB3 17|-(D11)- -|D12 IOREF|- pot ->-(D07)-|13 PD7 PWM/SS'/PB2 16|-(D10)- LED -<-|D13 LED --- | -(D08)-|14 PB0 PWM/PB1 15|-(D09)- -|GND | |______________________________| -|AREF | -|SCL | -|SDA | |________________| */