1#include <SoftwareSerial.h>
2#include <Servo.h>
3
4SoftwareSerial bluetooth(6, 7);
5
6Servo servo1;
7Servo servo2;
8
9int trigPin = A0;
10int echoPin = A1;
11int ledIndicator = 13;
12
13
14int motor1Pin1 = 8;
15int motor1Pin2 = 9;
16int motor2Pin1 = 10;
17int motor2Pin2 = 11;
18
19void setup() {
20 Serial.begin(9600);
21 bluetooth.begin(9600);
22 pinMode(trigPin, OUTPUT);
23 pinMode(echoPin, INPUT);
24 pinMode(ledIndicator, OUTPUT);
25
26 servo1.attach(5);
27 servo2.attach(4);
28 servo1.write(90);
29 servo2.write(90);
30
31 pinMode(motor1Pin1, OUTPUT);
32 pinMode(motor1Pin2, OUTPUT);
33 pinMode(motor2Pin1, OUTPUT);
34 pinMode(motor2Pin2, OUTPUT);
35}
36
37void loop() {
38 if (bluetooth.available()) {
39 char command = bluetooth.read();
40 Serial.println("Received command: " + String(command));
41 executeCommand(command);
42 }
43
44 long duration, distance;
45 digitalWrite(trigPin, LOW);
46 delayMicroseconds(2);
47 digitalWrite(trigPin, HIGH);
48 delayMicroseconds(10);
49 digitalWrite(trigPin, LOW);
50 duration = pulseIn(echoPin, HIGH);
51 distance = (duration / 2) / 29.1;
52
53 Serial.println("Distance: " + String(distance) + " cm");
54
55 if (distance < 20) {
56
57
58 }
59}
60
61void executeCommand(char command) {
62 switch (command) {
63 case 'F':
64 moveForward();
65 break;
66 case 'B':
67 moveBackward();
68 break;
69 case 'L':
70 moveLeft();
71 break;
72 case 'R':
73 moveRight();
74 break;
75 case 'S':
76 stopMotors();
77 break;
78 case 'U':
79 moveServosUp();
80 break;
81 case 'D':
82 moveServosDown();
83 break;
84 }
85}
86
87void moveForward() {
88 digitalWrite(motor1Pin1, HIGH);
89 digitalWrite(motor1Pin2, LOW);
90 digitalWrite(motor2Pin1, HIGH);
91 digitalWrite(motor2Pin2, LOW);
92 digitalWrite(ledIndicator, HIGH);
93}
94
95void moveBackward() {
96 digitalWrite(motor1Pin1, LOW);
97 digitalWrite(motor1Pin2, HIGH);
98 digitalWrite(motor2Pin1, LOW);
99 digitalWrite(motor2Pin2, HIGH);
100 digitalWrite(ledIndicator, HIGH);
101}
102
103void moveLeft() {
104 digitalWrite(motor1Pin1, LOW);
105 digitalWrite(motor1Pin2, HIGH);
106 digitalWrite(motor2Pin1, HIGH);
107 digitalWrite(motor2Pin2, LOW);
108 digitalWrite(ledIndicator, HIGH);
109}
110
111void moveRight() {
112 digitalWrite(motor1Pin1, HIGH);
113 digitalWrite(motor1Pin2, LOW);
114 digitalWrite(motor2Pin1, LOW);
115 digitalWrite(motor2Pin2, HIGH);
116 digitalWrite(ledIndicator, HIGH);
117}
118
119void stopMotors() {
120 digitalWrite(motor1Pin1, LOW);
121 digitalWrite(motor1Pin2, LOW);
122 digitalWrite(motor2Pin1, LOW);
123 digitalWrite(motor2Pin2, LOW);
124 digitalWrite(ledIndicator, LOW);
125}
126
127void moveServosUp() {
128 for (int angle = 90; angle >= 0; angle--) {
129 servo1.write(angle);
130 servo2.write(angle);
131 delay(10);
132 }
133}
134
135void moveServosDown() {
136 for (int angle = 0; angle <= 90; angle++) {
137 servo1.write(angle);
138 servo2.write(angle);
139 delay(10);
140 }
141}