-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathultrasonic_rgb_microservo_alarm.ino
92 lines (69 loc) · 1.41 KB
/
ultrasonic_rgb_microservo_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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <Servo.h>
// micro servo
Servo ms;
byte servoP = 2;
int pos = 0;
// ultrasonic
byte trigP = 7;
byte echoP = 6;
// buzzer
byte buzzerP = 5;
// rgb led
byte redP = 9;
byte greenP = 10;
byte blueP = 11;
void setup()
{
Serial.begin(9600);
ms.attach(servoP);
pinMode(trigP, OUTPUT);
pinMode(echoP, INPUT);
pinMode(buzzerP, OUTPUT);
pinMode(redP, OUTPUT);
pinMode(greenP, OUTPUT);
pinMode(blueP, OUTPUT);
}
void loop()
{
for (pos = 0; pos <= 180; pos ++) {
ms.write(pos);
delay(10);
detect();
}
for (pos = 180; pos >= 0; pos --) {
ms.write(pos);
delay(10);
detect();
}
delay(500);
}
void detect(){
digitalWrite(trigP, LOW);
delayMicroseconds(2);
digitalWrite(trigP, HIGH);
delayMicroseconds(10);
digitalWrite(trigP, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
long dur = pulseIn(echoP, HIGH);
// Convert the time into a distance (cm)
long distcm = (dur/2)/29.1;
if(distcm < 10){
tone(buzzerP, 440, 300);
analogWrite(redP, 255);
analogWrite(greenP, 0);
analogWrite(blueP, 0);
}
else if(distcm >= 10 && distcm <= 30){
noTone(buzzerP);
analogWrite(redP, 0);
analogWrite(greenP, 0);
analogWrite(blueP, 255);
}
else {
noTone(buzzerP);
analogWrite(redP, 0);
analogWrite(greenP, 255);
analogWrite(blueP, 0);
}
Serial.println(distcm);
}