//timer interrupts
//by Amanda Ghassaei adapted by T.Nilsson July 2019 :)
//June 2012
//https://www.instructables.com/id/Arduino-Timer-Interrupts/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
*/
// ATMEGA2560 has 4 16 bit timers: 1,3,4 and 5
//storage variables
boolean toggle4 = LOW;
void setup(){
//set pins as outputs
pinMode(13, OUTPUT);
pinMode(2, INPUT_PULLUP);
cli();//stop interrupts
//set timer3 interrupt at 6KHz
TCCR3A = 0;// set entire TCCR1A register to 0
TCCR3B = 0;// same for TCCR1B
TCNT3 = 0;//initialize counter value to 0
// set compare match register for 6000hz increments
//OCR3A = 2665; //((16*10^6) / (6000)) - 1. = 2665
OCR3A = 5332; // this will equal 3khz
// turn on CTC mode
TCCR3B |= (1 << WGM32);
// Set CSn2, CSn1 and CSn0 bits for prescaler. (Uncomment the one you need)
TCCR3B |= (1 << CS30); // No prescaler
//TCCR3B |= (1 << CS31); // CLK/8
//TCCR3B |= (1 << CS31)| (1<< CS30); // CLK/64
//TCCR3B |= (1 << CS32); // CLK/256
//TCCR3B |= (1 << CS32) | (1<< CS30); // CLK/1024
// enable timer compare interrupt
TIMSK3 |= (1 << OCIE3A);
sei();//allow interrupts
}//end setup
ISR(TIMER3_COMPA_vect){//timer1 interrupt 1Hz toggles pin 13 (LED)
//generates pulse wave of frequency 1Hz/2 = 0.5kHz (takes two cycles for full wave- toggle high then toggle low)
digitalWrite(13,toggle4);
toggle4 = !toggle4;
}
void loop(){
//Serial.println(digitalRead(2));
if (digitalRead(2) == 0) {
//TIMSK3 |= 1 << OCIE3A; // set the bit - enables the interrupt
//TIMSK3 &= ~(1 << OCIE3A); // Clear the bit - disables the interrupt
TIMSK3 ^= 1 << OCIE3A; // toggle
}
}