#include "pitches.h"
const int ledPin = 27;
const int trigPin = 17;
const int echoPin = 5;
const int buzzerPin = 22;
long duration, distance;
int melody[] = {
NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
4, 8, 8, 4, 4, 4, 4, 4
};
void setup() {
Serial.begin(115200);
//pinMode(ledPin, OUTPUT); // Initialize serial communication at 9600 baud rate
pinMode(ledPin, OUTPUT); // Set the ledPin as an OUTPUT
pinMode(trigPin, OUTPUT); // Set the trigPin as an Output
pinMode(echoPin, INPUT); // Set the echoPin as an Input
pinMode(buzzerPin, OUTPUT);
}
void loop() {
// Clear the trigPin by setting it LOW
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distance = (duration/2) /29.1; // Speed of sound wave go and back
// Print the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(1000);
if (distance < 150) {
digitalWrite(ledPin, HIGH); // turn on ledPin
Serial.println("Owww! D:");
delay(1000);
noTone(buzzerPin);
}else {
digitalWrite(ledPin, LOW);
Serial.println("Hoorayy! :D");
for (int thisNote = 0; thisNote < 8; 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 / noteDurations[thisNote];
tone(buzzerPin, 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:
noTone(buzzerPin);
}
}
}