Skip to content

Instantly share code, notes, and snippets.

@arselzer
Created June 22, 2015 09:12
Show Gist options
  • Save arselzer/9e2f34a86cd06d042af9 to your computer and use it in GitHub Desktop.
Save arselzer/9e2f34a86cd06d042af9 to your computer and use it in GitHub Desktop.
#include <math.h>
#define a 1915
#define d 1700
#define e 1519
#define f 1432
#define g 1275
#define a 1136
#define b 1014
#define C 956
char notes[] = "cdefgabC";
int tones[] = {1915, 1700, 1519, 1432, 1275, 1136, 1014, 956}; // period / 2
int tempo = 50;
void setup() {
Serial.begin(9600);
pinMode(3, OUTPUT);
}
void playNote(char note, int duration) {
for (int i = 0; i < 8; i++) {
if (notes[i] == note) {
// play tone
int tone = tones[i];
for (long i = 0; i < duration * 1000L; i += tone * 2) {
digitalWrite(3, HIGH);
delayMicroseconds(tone);
digitalWrite(3, LOW);
delayMicroseconds(tone);
}
}
}
}
void playMelody(char melody[]) {
for (int i = 0; i < String(melody).length(); i++) {
//Serial.println(melody[i]);
if (melody[i] == ' ') {
delay(tempo);
}
else {
playNote(notes[i], tempo);
}
delay (tempo / 2);
}
}
int i = 0;
void loop() {
char melody[] = "aadeeefff ggaa C eeeaefedeC aabbccdd efgCaaabaaCaaaC ggeeffaaag ";
playMelody(melody);
i++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment