Hello!
I found a useful tutorial about using timers on arduino, and I tried to hack an example to make some tests.
This sketch, should work this way:
1- receive an external signal and trigger an external interrupt
2- the external interrupt function (tachSignal) sets timer1 to wait for a certain amount of time
3- when the ISR runs, it turns on an led and then sets timer1 for another time interval
4- when the ISR runs again, it turns off the led and reset timer1
here is the sketch:
// Arduino timer CTC interrupt example
// www.engblaze.com
// avr-libc library includes
#include <avr/io.h>
#include <avr/interrupt.h>
#define LEDPIN 2
int delayTicks = 100;
int outputTicks = 30;
int interruptIter = 0;
void setup()
{
attachInterrupt(0,tachSignal,FALLING);
pinMode(LEDPIN, OUTPUT);
// initialize Timer1
cli(); // disable global interrupts
TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0; // same for TCCR1B
// enable global interrupts:
sei();
}
void tachSignal(){
cli(); // disable global interrupts
// set compare match register to desired timer count:
OCR1A = delayTicks;
// turn on CTC mode:
TCCR1B |= (1 << WGM12);
// Set CS10 and CS12 bits for 1024 prescaler:
TCCR1B |= (1 << CS10);
TCCR1B |= (1 << CS12);
// enable timer compare interrupt:
TIMSK1 |= (1 << OCIE1A);
// enable global interrupts:
sei();
interruptIter = 0;
}
ISR(TIMER1_COMPA_vect)
{
if(interruptIter == 0){
digitalWrite(LEDPIN, HIGH);
cli(); // disable global interrupts
// set compare match register to desired timer count:
OCR1A = outputTicks;
// turn on CTC mode:
TCCR1B |= (1 << WGM12);
// Set CS10 and CS12 bits for 1024 prescaler:
TCCR1B |= (1 << CS10);
TCCR1B |= (1 << CS12);
// enable timer compare interrupt:
TIMSK1 |= (1 << OCIE1A);
// enable global interrupts:
sei();
interruptIter = 1;}else{
digitalWrite(LEDPIN, LOW);
cli(); // disable global interrupts
TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0; // same for TCCR1B
// enable global interrupts:
sei();}
}
void loop()
{
}
I'm not sure if this code is correct, I'm not sure about disabling interrupts within the interrupt routine.
Any advice is greatly appreciated!