//Include the necessary libraries
#include <Ultrasonic.h>
#include <Tone.h>
//Define the pins for the ultrasonic sensor, buzzer and LED
#define trigPin 7
#define echoPin 8
#define buzzerPin 9
#define ledPin 13
//Create an instance of the Ultrasonic and Tone libraries
Ultrasonic ultrasonic(trigPin, echoPin);
Tone buzzer;
//Create a variable to store the distance value
int distance;
//Create a variable to keep track of whether the song has been played or not
bool songPlayed = false;
//Create a variable to keep track of the time the song has been playing
unsigned long songStartTime;
//Create an array to store the notes for the song
int song[14] = {NOTE_C4,NOTE_C4,NOTE_G4,NOTE_G4,NOTE_A4,NOTE_A4,NOTE_G4,NOTE_F4,NOTE_F4,NOTE_E4,NOTE_E4,NOTE_D4,NOTE_D4,NOTE_C4};
//Create an array to store the duration of the notes
int duration[14] = {4,4,4,4,4,4,4,4,4,4,4,4,4,4};
void setup() {
//Initialize the serial communication
Serial.begin(9600);
//Set the LED pin to output mode
pinMode(ledPin, OUTPUT);
//Turn on the red LED by default
digitalWrite(ledPin, HIGH);
}
void loop() {
//Get the distance value from the ultrasonic sensor
distance = ultrasonic.distanceRead(CM);
//Print the distance value to the serial monitor
Serial.println(distance);
//Check if the distance is less than 6 cm
if(distance < 6) {
//Turn off the red LED
digitalWrite(ledPin, LOW);
}
else {
//Turn on the red LED
digitalWrite(ledPin, HIGH);
}
// Check if the red LED is turned off
if(digitalRead(ledPin) == LOW) {
//Check if the song has not been played
if(!songPlayed) {
//Play the song note by note
for(int i=0; i<14; i++) {
buzzer.play(song[i], duration[i]*500);
delay(duration[i]*500);
}
//Mark the song as played and store the start time
songPlayed = true;
songStartTime = millis();
} else {
// Check if the song has been playing for 30 seconds
if (millis() -songStartTime >= 30000){
//stop playing the song
buzzer.stop();
songPlayed = false;
}
}
}
else {
//Reset songPlayed variable
songPlayed = false;
}
//Delay for 100 milliseconds
delay(100);
}
// #step #2, buzzer to start the music and make it fun