The concept:
Play a sine wave saved as a character array in PROGMEM through an 8-bit DAC connected to the PORTC pins on the Arduino Mega.
This works:
// File just defines an array and a size
#include "sine440.h"
int i = 0;
void setup() {
DDRC = B11111111;
}
void loop() {
PORTC = pgm_read_byte(&sine[i++]);
if(i >= sine_size){
i = i - sine_size;
}
delayMicroseconds(60);
}
The above code produces a sine wave of about 440 Hz, exactly what I wanted. Now, I'd like to move this into an interrupt routine, as follows:
This doesn't work
#include "sine440.h"
int i = 0;
void setup() {
DDRC = B11111111;
TCCR5B = (1 << WGM52) | (1 << CS50 );
OCR5A = 16000000/16000;
TIMSK5 = (1 << OCIE5A);
}
ISR(TIMER5_COMPA_vect){
PORTC = pgm_read_byte(&sine[i++]);
if(i >= sine_size){
i = i - sine_size;
}
}
void loop() {
}
The above code produces a sine wave of 1721 Hz. I know that this means it's iterating through the array too fast, but I don't know how to change it. In order for it to produce 440 Hz, it needs to be preforming 16,000 iterations per second, which is what I believe OCR5A = 16000000/16000;
does. But it doesn't appear that changing the value of OCR5A does anything at all. Giving it the max value of 65,535 still produces a 1721 Hz sine wave...
So what am I doing wrong here? How do I change the speed of this timer interrupt?
TCCR5A = 0
explicitly, maybe arduino has WGM51 or WGM50 set at startup for some reason.