In the past I used to use interrupts in my Arduino UNO projects and it worked fine for me.
Recently I have started using Arduino MEGA2560, and try to implement what I know about interrupts with this micro controller. For some reason it didn't work well for me. I am trying to blink an LED with the help of an Output-Compare associated pin, but it didn't work for me.
I was looking for a problem in my code, read all the relevant sections in the datasheets, even looked on similar examles from my previous projects and found nothing wrong.
Here is my code:
#include <Arduino.h>
#define TRIG_PIN 11
void setup() {
pinMode(TRIG_PIN, OUTPUT);
digitalWrite(TRIG_PIN, LOW);
TCCR1A = 0;
TCCR1A |= 1<<COM1A1; // OC1A output fall on compare match
TCCR1B |= 1<<CS10; // 1024 PS
TCCR1B |= 1<<CS12;
OCR1A = 0x7FFF; // TOP value for counting
TIMSK1 = 0;
TIMSK1 |= 1<<OCIE1A;
sei();
}
void loop() {
}
ISR(TIMER1_COMPA_vect){
}
I'll share the datasheets and the relevant pages so it will be much easier for you to help me:
The datasheets
Pg.75 / 13.3.2
Link between OC1A to PB5 (D11 on board)
Pg. 154-163
Description about each register I used:
TCCR1A
TCCR1B
OCR1A
TIMSK1
You got it all mixed up
There are two ways to control the pin from the timer - through an interrupt and through a change on compare match.
If you were going to control the pin by interrupt, you need to write something in the interrupt handler. If you want to use compare match, you have to configure the timer bits responsible for the Waveform Generation, see Table 17.2 in the datasheet
If you choose row 15 from the 17-2 - the only way to select TOP will be to set OCR1A, as i think it is not you want.
If you want blink the led with custom freq, I would advise you to choose CTC for the timer and "toggle on match" for the pin
Actually, I want the frequency to be constant, but the duty cycle to be change. I want the TCNT to count all the way to 0xFFFF, and change the ON time for the LED within this range
I maybe wrote it the wrong way before..
Decide what frequency you want. The base clock is 16 MHz so without a prescale the blink rate would be 244.140625 Hz.
With a prescale of 8 you get about 30 Hz.
With a prescale of 64 you get about 3.8 Hz.
With a prescale of 256 you get about 0.95 Hz.
That sounds about right. About one second.
So select a "Fast PWM" WGM. WGM14 will get what you want. Set ICR1 to 0xFFFF to set TOP. Set OCR1A for the duty cycle. Set COM1A1 to put pin OC1A in Normal PWM mode.