#define PIN_LED 2
#define PIN_ECHO 13
#define PIN_ALARM 10
#define PIN_TRIGGER 12
#define FREQUENCY 988
unsigned long duration = 0;
double distance = 0.0;
void setup() {
// put your setup code here, to run once:
pinMode(PIN_LED, OUTPUT);
pinMode(PIN_ECHO, INPUT);
pinMode(PIN_TRIGGER, OUTPUT);
pinMode(PIN_ALARM, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(PIN_TRIGGER, LOW);
delayMicroseconds(2);
digitalWrite(PIN_TRIGGER, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIGGER, LOW);
delayMicroseconds(2);
duration = pulseIn(PIN_ECHO, HIGH);
distance = ( duration / 2 ) * 0.0343;
if (distance < 200) {
digitalWrite(PIN_LED, HIGH);
tone(PIN_ALARM, FREQUENCY);
delay(100);
digitalWrite(PIN_LED, LOW);
noTone(PIN_ALARM);
delay(100);
} else {
digitalWrite(PIN_LED, LOW);
noTone(PIN_ALARM);
}
}