-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharduino_code.ino
More file actions
59 lines (52 loc) · 1.15 KB
/
arduino_code.ino
File metadata and controls
59 lines (52 loc) · 1.15 KB
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
#include <Servo.h>
#define TRIGGER_PIN 9
#define TRIGGER_ECHO 10
#define BUZZER_PIN 8
#define SERVO_PIN 3
long duration;
int distance;
int port = 9600;
Servo myServo;
void setup() {
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(TRIGGER_ECHO, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
Serial.begin(port);
myServo.attach(SERVO_PIN);
}
void loop() {
for (int i = 15; i <= 165; i++) {
moveServoAndDistance(i);
}
for (int i = 165; i > 15; i--) {
moveServoAndDistance(i);
}
}
void updateBuzzer() {
if (distance > 0 && distance <= 40) {
int frequency = map(distance, 0, 40, 2000, 100);
tone(BUZZER_PIN, frequency, 100);
} else {
noTone(BUZZER_PIN);
}
}
int calculateDistance() {
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
duration = pulseIn(TRIGGER_ECHO, HIGH);
distance = duration * 0.034 / 2;
return distance;
}
void moveServoAndDistance(int angle) {
myServo.write(angle);
delay(30);
distance = calculateDistance();
updateBuzzer();
Serial.print(angle);
Serial.print(",");
Serial.print(distance);
Serial.print(".");
}