1
2
3
4
5#include <Servo.h>
6#include <NewPing.h>
7
8Servo myservo;
9
10
11const int trigPin = 9;
12const int echoPin = 10;
13const int red = 11;
14const int buzz = 12;
15const int serv0 = 8;
16
17NewPing sonar (trigPin, echoPin, 300);
18
19int pos = 0;
20
21void setup() {
22 myservo.attach(serv0);
23 Serial.begin(9600);
24 pinMode(red, OUTPUT);
25 pinMode(buzz, OUTPUT);
26}
27
28void loop() {
29 long duration, inches, cm;
30 for (pos = pos; pos <= 180; pos += 5) {
31 myservo.write(pos);
32 delay(10);
33 int cm = sonar.ping_cm();
34 Serial.print(cm);
35 Serial.print("cm");
36 Serial.println();
37
38 delay(15);
39
40 if (cm < 20)
41 {
42 analogWrite(red, 125);
43 if (cm < 10) {
44 digitalWrite(red, HIGH);
45 digitalWrite(buzz, HIGH);
46 }
47 else digitalWrite(buzz, LOW);
48
49 }
50 else
51 { digitalWrite(buzz, LOW);
52 digitalWrite(red, LOW);
53 }
54 }
55
56 for (pos = 180; pos >= 0; pos -= 5) {
57 myservo.write(pos);
58 delay(10);
59 int cm = sonar.ping_cm();
60
61 Serial.print(cm);
62 Serial.print("cm");
63 Serial.println();
64
65 delay(15 );
66 if (cm < 20)
67 {
68 analogWrite(red, 125);
69 if (cm < 10)
70 {
71
72 digitalWrite(red, HIGH);
73 digitalWrite(buzz, HIGH);
74 }
75 else digitalWrite(buzz, LOW);
76
77 }
78 else
79 { digitalWrite(buzz, LOW);
80 digitalWrite(red, LOW);
81 }
82 }
83
84
85 delay(100);
86}
87