-
Notifications
You must be signed in to change notification settings - Fork 2
/
CowardRobot.ino
76 lines (51 loc) · 1.32 KB
/
CowardRobot.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
//Coward Robot
//by Niam Moltta
//this coward Starts reversing when it founds something close.
#define E1 10 // Enable Pin for motor 1
#define I2 8 // Control pin 1 for motor 1
#define I1 9 // Control pin 2 for motor 1
const int Ping = A0; //Ultrasonic sensor
void setup() {
Serial.begin(9600);
pinMode(E1, OUTPUT);
pinMode(I1, OUTPUT);
pinMode(I2, OUTPUT);
}
void loop() {
//analogWrite(E1, 255); // Run in half speed
long duration, inches, cm;
pinMode(Ping, OUTPUT);
digitalWrite(Ping, LOW);
delayMicroseconds(2);
digitalWrite(Ping, HIGH);
delayMicroseconds(5);
digitalWrite(Ping, LOW);
pinMode(Ping, INPUT);
duration = pulseIn(Ping, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
// Serial monitor
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(15);
if (cm <= 30) {
delay(1000);
digitalWrite(E1, HIGH);
digitalWrite(I1, LOW); //ccw
digitalWrite(I2, HIGH);
}
else {
digitalWrite(E1, HIGH); //cw
digitalWrite(I1, HIGH);
digitalWrite(I2, LOW);
}
}
long microsecondsToInches(long microseconds) {
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds) {
return microseconds / 29 / 2;
}