//31 Hz to 65535 Hz
#include <MusicBuzzer.h>
#include <pitches.h>
const int BUZZER_PIN = 8; // declaring the Buzzer pin
const int trigPin = 10;
const int echoPin = 9;
const int adjustPin = A0;
long duration, defautltTriggerDistance;
int distanceCm, distanceInch;
boolean play = false;
const int buttonTones[] = {
NOTE_C4, NOTE_D4, NOTE_E4, NOTE_F4,
NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5
};
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
//Serial.begin(115200);
pinMode(BUZZER_PIN, OUTPUT); //addigning pin to Output mode
music.init(BUZZER_PIN);
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin,LOW);
delayMicroseconds(2);
pinMode(echoPin, INPUT);
delay(6000);
defautltTriggerDistance = 24;
}
void loop() {
ExamineSensor();
}
void RunBuzzerSound(){
// put your main code here, to run repeatedly:
tone(BUZZER_PIN, 4000); // Send 1KHz sound signal...
delay(1000); //pause...for 1 sec
noTone(BUZZER_PIN); //// Stop sound...
//delay(1000); //// ...for 1sec
tone(BUZZER_PIN, 1000); // Send 1KHz sound signal...
delay(1000); //pause...for 1 sec
noTone(BUZZER_PIN); //// Stop sound...
delay(100); //// ...for 1ms
}
void RunSiren()
{
tone(BUZZER_PIN, buttonTones[6]);
delay(1000); //pause...for 1 sec
noTone(BUZZER_PIN); //// Stop sound...
tone(BUZZER_PIN, buttonTones[0]);
delay(1000); //pause...for 1 sec
noTone(BUZZER_PIN); //// Stop sound...
delay(100);
}
void RunSiren2()
{
tone(BUZZER_PIN, buttonTones[6],1000);
//delay(10000); //pause...for 1 sec
tone(BUZZER_PIN, buttonTones[0],1000);
//delay(10000); //pause...for 1 sec
noTone(BUZZER_PIN); //// Stop sound...
delay(100);
}
void RunMusicSound()
{
music.takeonme(); //YOU'VE BEEN RICK ROLLED
delay(2000);
}
void ExamineSensor()
{
int sensorValue = 0;
sensorValue = analogRead(A0);
long triggerDist = map(sensorValue,0,1024,0,60); // max distance that will trigger alarm (1 to tiggerDist will sound alarm)
long activeTriggerDist = defautltTriggerDistance;
bool alarmTriggered = false;
if(defautltTriggerDistance != triggerDist)
{
activeTriggerDist = triggerDist;
}
digitalWrite(trigPin, HIGH);//Take ultrasonic Measurement
delayMicroseconds(10); //
digitalWrite(trigPin, LOW);//
duration = pulseIn(echoPin, HIGH); //Read ultrasonic result
distanceInch = duration * 0.0133 / 2; //sensor distance from object in inches
String stringDistanceInch = (String) distanceInch;
String stringtriggerDist = (String) activeTriggerDist;
Serial.println("Current Distance (Inches): " + stringDistanceInch);
Serial.println("Trigger Distance (Inches): " + stringtriggerDist);
if (distanceInch < activeTriggerDist && distanceInch > 0) {
//RunMusicSound();
int ranSound = 0;
while(ranSound < 4)
{
RunSiren();
alarmTriggered = true;
ranSound++;
delay(500);
}
}
Serial.println("Alarm Triggered: " + (String) alarmTriggered);
if(alarmTriggered)
{
delay(60000); //wait 1 min
}
else{
delay(1000); //wait 1 sec
}
}