Skip to content

Instantly share code, notes, and snippets.

@azjgard
Created January 12, 2022 03:41
Show Gist options
  • Save azjgard/82e5bf900ca34c80c4417ca7d074b45e to your computer and use it in GitHub Desktop.
Save azjgard/82e5bf900ca34c80c4417ca7d074b45e to your computer and use it in GitHub Desktop.
3-Tone Song Player
const int BUZZ_PIN = 3;
const int NUM_LED_PINS = 4;
const int LED_PINS[NUM_LED_PINS] = {13, 13, 12, 10};
const int SONG_DELAY = 1000;
const int TONES[4] = { 400, 600, 800, 1000 };
const unsigned long BEAT_LENGTH = 90000;
const int BEAT_DELAY = 175;
// Mary Had a Little Lamb (kind of)
const int SONG_NUM_NOTES = 29;
const int SONG[SONG_NUM_NOTES][2] = {
{1, 1},
{2, 1},
{3, 1},
{2, 1},
{1, 1},
{1, 1},
{1, 2},
{2, 1},
{2, 1},
{2, 2},
{2, 1},
{1, 1},
{0, 2},
{1, 1},
{2, 1},
{3, 1},
{2, 1},
{1, 1},
{1, 1},
{1, 1},
{1, 1},
{2, 1},
{2, 1},
{1, 1},
{2, 1},
{3, 4}
};
void setup() {
pinMode(BUZZ_PIN, OUTPUT);
for (int i = 0; i < NUM_LED_PINS; i++) {
pinMode(LED_PINS[i], OUTPUT);
}
}
void loop() {
for (int i = 0; i < SONG_NUM_NOTES; i++) {
playTone(SONG[i][0], SONG[i][1]);
}
delay(SONG_DELAY);
}
void playTone(int toneIndex, unsigned long duration) {
digitalWrite(LED_PINS[toneIndex], HIGH);
unsigned long beatEndTime = micros() + BEAT_LENGTH * duration;
while (micros() < beatEndTime) {
digitalWrite(BUZZ_PIN, HIGH);
delayMicroseconds(TONES[toneIndex]);
digitalWrite(BUZZ_PIN, LOW);
delayMicroseconds(TONES[toneIndex]);
}
digitalWrite(LED_PINS[toneIndex], LOW);
delay(BEAT_DELAY);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment