// * Composed by : I do not know
// * Coded By : https://code.google.com/p/rbots/source/browse/trunk/StarterKit/Lesson5_PiezoPlayMelody/Lesson5_PiezoPlayMelody.pde
// * Use BSD Clause 2 License for Distribution
// * Collection by GitHub User @abhishekghosh - https://github.com/AbhishekGhosh/Arduino-Buzzer-Tone-Codes
// * Program to choose between two melodies by using a potentiometer and a piezo buzzer.
// TONES //
// Defining the relationship between note, period & frequency.
// period is in microsecond so P = 1/f * (1E6)
#define c3 7634
#define d3 6803
#define e3 6061
#define f3 5714
#define g3 5102 // 196 Hz
#define a3 4545
#define b3 4049
#define c4 3816 // 261 Hz
#define d4 3401 // 294 Hz
#define e4 3030 // 329 Hz
#define f4 2865 // 349 Hz
#define g4 2551 // 392 Hz
#define a4 2272 // 440 Hz
#define a4s 2146
#define b4 2028 // 493 Hz
#define c5 1912 // 523 Hz
#define d5 1706
#define d5s 1608
#define e5 1517 // 659 Hz
#define f5 1433 // 698 Hz
#define g5 1276
#define a5 1136
#define a5s 1073
#define b5 1012
#define c6 955
#define R 0 // Define a special note, 'R', to represent a rest
//how manny strummings / min
long tempo = 160; // Set overall tempo
int pause = 1000; // Set length of pause between notes
int rest_count = 50; // Loop variable to increase Rest length (BLETCHEROUS HACK; See NOTES)
int melody1[] = { e4, b3, g3, d3, a3, e3 };
#define M_SIZE (sizeof(melody1)/sizeof(int))
// SETUP //
int speakerOut = 10; // Set up speaker on digital pin 7
int potPin = A0; // Set up potentiometer on analogue pin 0.
void setup() {
pinMode(speakerOut, OUTPUT);
//Serial.begin(9600); // Set serial out if we want debugging
}
// Initialize core variables
int toneM = 0;
int beat = 0;
long duration = 0;
// PLAY TONE //
// Pulse the speaker to play a tone for a particular duration
void playTone() {
long elapsed_time = 0;
if (toneM > 0) { // if this isn't a Rest beat, while the tone has
// played less long than 'duration', pulse speaker HIGH and LOW
while (elapsed_time < duration) {
digitalWrite(speakerOut,HIGH);
delayMicroseconds(toneM / 2);
// DOWN
digitalWrite(speakerOut, LOW);
delayMicroseconds(toneM / 2);
// Keep track of how long we pulsed
elapsed_time += (toneM);
//decrease freq by 10
toneM -= 5;
}
}
else { // Rest beat; loop times delay
for (int j = 0; j < rest_count; j++) { // See NOTE on rest_count
delayMicroseconds(duration);
}
}
}
void playChord() {
for(int i=0; i < M_SIZE; i++){
toneM = melody1[i];
beat = 1;
//beats every minute = tempo
//beats
duration = beat * (60000/160) * 1000; // Set up timing ms to us
playTone(); // A pause between notes
//delayMicroseconds(pause);
}
}
// LOOP //
void loop() {
playChord();
delay(1000); //delay ms
}