Skip to content

Instantly share code, notes, and snippets.

@aviad
Created May 17, 2016 05:52
Show Gist options
  • Save aviad/d5d5a7470443a5d586bc896a19d4dcfb to your computer and use it in GitHub Desktop.
Save aviad/d5d5a7470443a5d586bc896a19d4dcfb to your computer and use it in GitHub Desktop.
#include <TimerOne.h>
// This example uses the timer interrupt to blink an LED
// and also demonstrates how to share a variable between
// the interrupt and the main program.
const int led = LED_BUILTIN; // the pin with a LED
void setup(void)
{
pinMode(led, OUTPUT);
Timer1.initialize(500000); // a timer of 500000 microseconds - should be 0.5 seconds
Timer1.attachInterrupt(blinkLED); // blinkLED to run every 1.00 seconds
Serial.begin(9600);
}
// The interrupt will blink the LED, and keep
// track of how many times it has blinked.
int ledState = LOW;
volatile unsigned long blinkCount = 0; // use volatile for shared variables
void blinkLED(void)
{
if (ledState == LOW) {
ledState = HIGH;
blinkCount = blinkCount + 1; // increase when LED turns on
} else {
ledState = LOW;
}
digitalWrite(led, ledState);
}
// The main program will print the blink count
// to the Arduino Serial Monitor
void loop(void)
{
unsigned long blinkCopy; // holds a copy of the blinkCount
// to read a variable which the interrupt code writes, we
// must temporarily disable interrupts, to be sure it will
// not change while we are reading. To minimize the time
// with interrupts off, just quickly make a copy, and then
// use the copy while allowing the interrupt to keep working.
noInterrupts();
blinkCopy = blinkCount;
interrupts();
Serial.println("blinkCount = " + String(blinkCopy) + " @ " + String(micros()) + "us");
delay(50);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment