I am trying to use the timer interrupt on an Arduion Uno.
Here is a imple example code for displaying a progressive digit on a lcd display, which is updated with timer interupt every second:
#include <LCD_I2C.h>
LCD_I2C lcd(0x27);
volatile bool timerFlag = false; // Timer-Flag (timer-Interrupt)
int displayWidth = 16; // display width
int digit = 0; // current digit
void setup() {
lcd.begin();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Initializing...");
noInterrupts();
TCCR1A = 0;
TCCR1B = (1 << CS12) | (1 << CS10); // set Prescaler to 1024
TCNT1 = 0;
OCR1A = 15624; // should be 1 second with a prescaler of 102
TIMSK1 |= (1 << OCIE1A); // Enable timer interrupt
interrupts();
}
ISR(TIMER1_COMPA_vect) {
timerFlag = true;
}
void loop() {
static int position = 0;
char displayString[17]; // +1 null termination
if (timerFlag) {
lcd.clear(); // clear display
// update digit and progress
digit = (digit + 1) % 10;
position = (position + 1) % (displayWidth + 1);
memset(displayString, ' ', displayWidth);
displayString[displayWidth] = '\0'; add null termination
displayString[position] = '0' + digit; // Character for the current digit
// Show updated progress on the display
lcd.setCursor(0, 1);
lcd.print(displayString);
timerFlag = false;
}
}
The values for setting up he inteupt timer 1 for 1 second is arround everywhere. BUt the updates generated by this code is clearly much slower than 1 second, it's more about 4 seconds. So i did a comparison with a delay based version of the same example:
#include <LCD_I2C.h>
LCD_I2C lcd(0x27);
int displayWidth = 16; // display width
void setup() {
lcd.begin();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Initializing...");
}
void loop() {
for (int digit = 0; digit < 10; digit++) {
char displayString[17]; // +1 null termination
int position = digit % (displayWidth + 1);
// Update progression
memset(displayString, ' ', displayWidth);
displayString[displayWidth] = '\0'; // add null termination
displayString[position] = '0' + digit; // Character for the current digit
// Show updated progress on the display
lcd.clear(); // Clear display
lcd.setCursor(0, 1);
lcd.print(displayString);
delay(1000);
}
}
This one works as expected and updates every second.
So what is wrong with my interrupt settings?