// C++ code
//
int PIR = 0;
int Distance = 0;
long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}
void setup()
{
pinMode(15, INPUT);
pinMode(2, OUTPUT);
pinMode(6, OUTPUT);
}
void loop()
{
PIR = digitalRead(15);
delay(10); // Wait for 10 millisecond(s)
if (PIR == HIGH) {
digitalWrite(2, HIGH);
delay(1); // Wait for 1 millisecond(s)
} else {
digitalWrite(2, LOW);
}
Distance = 0.01723 * readUltrasonicDistance(5, 4);
if (Distance <= 100) {
tone(6, 880, 125); // play tone 69 (A5 = 880 Hz)
delay(125); // Wait for 125 millisecond(s)
} else {
noTone(6);
}
}