Blink LED by polling or interrupt

Environment

  • Ubuntu 16.04
  • Pololu 3pi Robot (ATmega328P)

Polling

#include <avr/io.h>

int main(void) {
    DDRD = 0b00000010;      // Set to one => output
    PORTD &= 0b11111101;    // Port D pin 1 set to off

	for(;;) {
        // blink
        PORTD ^= 0b00000010;  // Toggle the pins on/off

        // wait
        uint64_t i = 0;
        for (i = 0; i < 150000; i++);
	}
}

Interrupt

#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdbool.h>
#include <util/atomic.h> 

volatile bool update = false;

ISR(TIMER1_OVF_vect) {
	update = true;
}

int main(void) {
    DDRD = 0b00000010;      // Direction for Port D pin 1
    PORTD &= 0b11111101;    // Port D pin 1 set to off

    TCCR1B |= 0b00000100;   // divide by 64; 32bit counter  //_BV(CS10);
	TIMSK1 |= _BV(TOIE1);

	sei(); // Turn interrupts on.

	for(;;) {
		if (update) {
            // blink
            PORTD ^= 0b00000010;  // Toggle the pins on/off
			update = false;
		}
	}
}

Reference