-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ultrasonic_Sensor_Alarm.ino
77 lines (64 loc) · 1.89 KB
/
Ultrasonic_Sensor_Alarm.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//Copyright Notice: Code from Anonymous User's comment from Krepak's tutorial Ultrasonic Security System on the Arduino Project Hub.
//The comment begins by saying, "Code needs some slight amendments as below."
//I have modified this code by changing the values of the variables to match the pinout diagram used in Krepak's tutorial.
//This code is licensed under CC BY-SA 3.0.
//This program detects when an object is close to an ultrasonic sensor.
//It buzzes when an object is very close, and lights the LEDs in different ways depending on the distance.
//This program is used in the following video: https://youtu.be/9YJtSkO6SYA
//Comments and code shared by esTech (https://youtube.com/@estech321)
//and on the website https://estech321.github.io
#define trigPin 7
#define echoPin 6
#define LEDlampRed 9
#define LEDlampYellow 10
#define LEDlampGreen 11
#define soundbuzzer 3
int sound = 500;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LEDlampRed, OUTPUT);
pinMode(LEDlampYellow, OUTPUT);
pinMode(LEDlampGreen, OUTPUT);
pinMode(soundbuzzer, OUTPUT);
}
void loop() {
long durationindigit, distanceincm;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
durationindigit = pulseIn(echoPin, HIGH);
distanceincm = (durationindigit/5) / 29.1;
if (distanceincm < 50) {
digitalWrite(LEDlampGreen, HIGH);
}
else {
digitalWrite(LEDlampGreen, LOW);
}
if (distanceincm < 20) {
digitalWrite(LEDlampYellow, HIGH);
}
else {
digitalWrite(LEDlampYellow,LOW);
}
if (distanceincm < 5) {
digitalWrite(LEDlampRed, HIGH);
sound = 1000;
}
else {
digitalWrite(LEDlampRed,LOW);
}
if (distanceincm > 5 || distanceincm <= 0){
Serial.println("Outside the permissible range of distances");
noTone(soundbuzzer);
}
else {
Serial.print(distanceincm);
Serial.println(" cm");
tone(soundbuzzer, sound);
}
delay(300);
}