Welcome to Hackster!
Hackster is a community dedicated to learning hardware, from beginner to pro. Join us, it's free!
dhorton668
Published © CC BY-SA

Pardon Me for Interrupting

Learn the basics of programming timer interrupts on the ATmega328P.

IntermediateFull instructions provided2,034
Pardon Me for Interrupting

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
LED (generic)
LED (generic)
×1
Resistor 330 ohm
Resistor 330 ohm
×1

Hand tools and fabrication machines

Microchip ATmega328P data sheet

Story

Read more

Schematics

LED Connection

Wiring of an LED and current limiting resistor to pin 8 of the Arduino Uno.

Code

Final Sketch

Arduino
Interrupt blink and delay() blink.
/*
 * Flash an LED two different ways. One with delay() and one with timer interrupts.
 */

#define LED 9

void setup() {
  
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(LED, OUTPUT);

  // Disable interrupts while things are being set up.
  cli();

  // Set up Timer Control Registers. See ATmega328P data sheet section 15.11 (Remember, bits are numbered from zero.)
  TCCR1A = B00000000;  // All bits zero for "normal" port operation. 
  TCCR1B = B00001100;  // Bit 3 is Clear Timer on Compare match (CTC) and bits 0..2 specifies a divide by 256 prescaler.
  TIMSK1 = B00000010;  // Bit 1 will raise an interrupt on timer Output Compare Register A (OCR1A) match.
  OCR1A = 31250;       // Counter compare match value. 16MHz / prescaler * delay time (in seconds.)

  // Reenable the interrupts 
  sei();
}

void loop() {
  digitalWrite(LED, LOW);
  delay(500);
  digitalWrite(LED, HIGH);
  delay(500);
}

ISR(TIMER1_COMPA_vect)
{
  // Access pin 13 directly performing an exlusive or on Port B (digital pins 8 - 13).
  // Same as "digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN))"
  PORTB ^= B00100000;  // Toggle bit 5, which maps to pin13.
}

Credits

dhorton668
4 projects • 5 followers
Contact

Comments

Please log in or sign up to comment.