The Code:
/*
Arduino Christmas Song
Based on a project and code by Dipto Pratyaksa
Modified for Christmas 2023 by Meganano, on Dec 15, 2023.
*/
#include "pitches.h"
#define melodyPin 3
#define pirPin 7
int pirVal;
// 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(void) {
Serial.begin(9600);
pinMode(melodyPin, OUTPUT); // Buzzer
pinMode(pirPin, INPUT); // Sensor Pin
}
void sing() {
// iterate over the notes of the melody:
Serial.println(" 'Jingle Bells'");
int size = sizeof(melody) / sizeof(int);
for (int thisNote = 0; thisNote < size; thisNote++) {
int noteDuration = 1000 / tempo[thisNote];
buzz(melodyPin, melody[thisNote], noteDuration);
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
buzz(melodyPin, 0, noteDuration);
}
}
void buzz(int targetPin, long frequency, long length) {
long delayValue = 1000000 / frequency / 2; // calculate the delay value between transitions
long numCycles = frequency * length / 1000; // calculate the number of cycles for proper timing
for (long i = 0; i < numCycles; i++) { // for the calculated length of time...
digitalWrite(targetPin, HIGH); // write the buzzer pin high to push out the diaphram
delayMicroseconds(delayValue); // wait for the calculated delay value
digitalWrite(targetPin, LOW); // write the buzzer pin low to pull back the diaphram
delayMicroseconds(delayValue); // wait again or the calculated delay value
}
}
void loop() {
pirVal=digitalRead(pirPin);
Serial.print("PIR Reading: ");
Serial.println(pirVal);
if (pirVal == 1){
sing();
}
}