-
Notifications
You must be signed in to change notification settings - Fork 0
/
MotorControl.ino
77 lines (59 loc) · 1.44 KB
/
MotorControl.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
#define TRIG_PIN 9
#define ECHO_PIN 10
//Arduino PWM Speed Control:
int E1 = 5;
int M1 = 4;
int E2 = 6;
int M2 = 7;
bool branchDetected = false;
void setup()
{
Serial.begin(9600);
pinMode(M1, OUTPUT);
pinMode(M2, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop()
{
long duration;
int distance;
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
if (distance < 25 || branchDetected)
{
if (branchDetected == false)
{
for (int val = 255; val > 0; val -=20)
{
digitalWrite(M1,LOW);
analogWrite(E1, val); //PWM Speed Control
digitalWrite(M2, HIGH);
analogWrite(E2, val);
delay(100);
}
}
branchDetected = true;
Serial.println("Top detected");
digitalWrite(M1,HIGH);
analogWrite(E1, 120); //PWM Speed Control
digitalWrite(M2, LOW);
analogWrite(E2, 120);
}
else
{
digitalWrite(M1,LOW);
analogWrite(E1, 255); //PWM Speed Control
digitalWrite(M2, HIGH);
analogWrite(E2, 255);
}
delay(500);
}