To celebrate the early spirit of Christmas, I wanted to make the buzzer play a Christmas tune. The tune plays by pressing the button ( switch ). I added , also, a Knob ( potentiometer) to control the volume of the tune. I struggled a lot with the Knob , I thought that the way I connected it was right because I used the example specified for the buzzer and knob but it turned out that their is a different way to connect it when a button is involved. Also the the code was difficult to figure out but once that was sorted I was finally able to finish this project since connecting the buzzer to the button was very simple and fun to build.
Finally I hope you enjoy this project, it was fun to make:
#define buzzer 9 #define button 7 #include "pitches.h" #define melodyPin 9 // Jingle Bells int melody[] = { NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_G5, NOTE_C5, NOTE_D5, NOTE_E5, NOTE_F5, NOTE_F5, NOTE_F5, NOTE_F5, NOTE_F5, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_D5, NOTE_D5, NOTE_E5, NOTE_D5, NOTE_G5 }; int tempo[] = { 8, 8, 4, 8, 8, 4, 8, 8, 8, 8, 2, 8, 8, 8, 8, 8, 8, 8, 16, 16, 8, 8, 8, 8, 4, 4 }; void setup() {// put your setup code here, to run once: pinMode ( button, INPUT); Serial.begin (9600); } void loop() { if ( digitalRead ( button) == HIGH) { Serial.println(" 'Jingle Bells'"); int size = sizeof(melody) / sizeof(int); for (int thisNote = 0; thisNote < size; thisNote++) { // to calculate the note duration, take one second // divided by the note type. //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc. int noteDuration = 1000 / tempo[thisNote]; tone(melodyPin, melody[thisNote], noteDuration); // to distinguish the notes, set a minimum time between them. // the note's duration + 30% seems to work well: int pauseBetweenNotes = noteDuration * 1.30; delay(pauseBetweenNotes); // stop the tone playing: tone (melodyPin, 0, noteDuration); } int knobValue = analogRead (A0); byte pwm = map(knobValue, 0, 1023, 0, 255); Serial.print ( knobValue); Serial.print ( "-"); Serial. println ( pwm); analogWrite( tone, pwm); delay (1); } else { noTone (buzzer); } }