-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUltrasonicDistanceSensor.ino
94 lines (81 loc) · 1.51 KB
/
UltrasonicDistanceSensor.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
93
#include <Servo.h>
Servo wheelLeft;
Servo wheelRight;
#define WHEEL_SPEED 180
const int trigPin = 9;
const int echoPin = 8;
long duration;
int distanceCm, distanceInch;
void setup()
{
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
attachWheels();
Serial.begin(9600);
}
void loop()
{
delay(15);
if(isObstacleClose(2))
{
Serial.println("Too Close");
// delay(1000);
moveBackwards();
delay(1000);
moveRight();
delay(2000);
}
else
{
Serial.println("Nothing");
moveForward();
}
}
bool isObstacleClose(int distancetoDetected)
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distanceInch = duration*0.0133/2;
if(distanceInch <= distancetoDetected && distancetoDetected != 0){
return true;
}
return false;
}
void moveForward()
{
attachWheels();
wheelLeft.write(WHEEL_SPEED);
wheelRight.write(-WHEEL_SPEED);
}
void moveBackwards()
{
attachWheels();
wheelLeft.write(-WHEEL_SPEED);
wheelRight.write(WHEEL_SPEED);
}
void moveStop()
{
wheelLeft.detach();
wheelRight.detach();
}
void moveRight()
{
attachWheels();
wheelLeft.write(WHEEL_SPEED);
wheelRight.write(WHEEL_SPEED);
}
void moveLeft()
{
attachWheels();
wheelLeft.write(-WHEEL_SPEED);
wheelRight.write(-WHEEL_SPEED);
}
void attachWheels()
{
wheelLeft.attach(2);
wheelRight.attach(3);
}