1const int buzzer = 8;
2const int trig_pin = 9;
3const int echo_pin = 10;
4float timing = 0.0;
5float distance = 0.0;
6
7void setup()
8{
9 pinMode(echo_pin, INPUT);
10 pinMode(trig_pin, OUTPUT);
11 pinMode(buzzer, OUTPUT);
12
13 digitalWrite(trig_pin, LOW);
14 digitalWrite(buzzer, LOW);
15
16 Serial.begin(9600);
17}
18
19void loop()
20{
21 digitalWrite(trig_pin, LOW);
22 delay(2);
23
24 digitalWrite(trig_pin, HIGH);
25 delay(10);
26 digitalWrite(trig_pin, LOW);
27
28 timing = pulseIn(echo_pin, HIGH);
29 distance = (timing * 0.034) / 2;
30
31 Serial.print("Distance: ");
32 Serial.print(distance);
33 Serial.print("cm | ");
34 Serial.print(distance / 2.54);
35 Serial.println("in");
36
37
38 if (distance <= 50) {
39 tone(buzzer, 500);
40 } else {
41 noTone(buzzer);
42 }
43
44 delay(100);
45}