#include "pitches.h"
float noteToFreq(int note) {
return 220.0 * pow(2.0, note / 12.0);
}
// const int iterFrequency = 62500;
const int iterPeriod = 125;
const uint8_t buzzerPin = 8;
const uint8_t buttonPins[] = { 12, 11, 10, 9, 7, 6, 5, 4 };
const float freqs[] = {
noteToFreq(3), noteToFreq(5), noteToFreq(7), noteToFreq(8),
noteToFreq(10), noteToFreq(12), noteToFreq(14), noteToFreq(15)
};
const int numTones = sizeof(buttonPins) / sizeof(buttonPins[0]);
volatile unsigned long iter = 0;
int periods[numTones] = {};
void setup() {
pinMode(buzzerPin, OUTPUT);
for (int i = 0; i < numTones; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
periods[i] = round(1e6 / freqs[i] / iterPeriod);
}
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++;
float sum = 0;
for (int i = 0; i < numTones; i++) {
if (digitalRead(buttonPins[i]) == LOW) {
if (iter % periods[i] > round(periods[i] / 2)) {
sum++;
} else {
sum--;
}
}
}
sum /= (float)numTones;
sum++;
sum *= 127.0;
analogWrite(buzzerPin, sum);
// if (sum > 0) {
// digitalWrite(buzzerPin, HIGH);
// } else {
// digitalWrite(buzzerPin, LOW);
// }
}