// #include "pitches.h"
float noteToFreq(int note) {
return 220.0 * pow(2.0, note / 12.0);
}
// const int iterFrequency = 62500;
const int iterPeriod = 333;
const uint8_t buzzerPins[] = { 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 };
const int numTones = sizeof(buzzerPins) / sizeof(buzzerPins[0]);
volatile unsigned long iter = 0;
float freqs[numTones] = {};
int periods[numTones] = {};
bool buzzerStates[numTones] = {};
void setup() {
for (int i = 0; i < numTones; i++) {
pinMode(buzzerPins[i], OUTPUT);
freqs[i] = noteToFreq(i + 3);
periods[i] = round(1e6 / freqs[i] / iterPeriod);
buzzerStates[i] = false;
}
noInterrupts();
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
OCR1A = 249;
TCCR1B |= (1 << WGM12);
TCCR1B |= (1 << CS11);
TIMSK1 |= (1 << OCIE1A);
interrupts();
}
void loop() {
}
ISR(TIMER1_COMPA_vect) {
iter++;
for (int i = 0; i < numTones; i++) {
if (iter % periods[i] == 0 || iter % periods[i] == round(periods[i] / 2)) {
buzzerStates[i] = !buzzerStates[i];
digitalWrite(buzzerPins[i], buzzerStates[i]);
}
}
}