-
Notifications
You must be signed in to change notification settings - Fork 0
/
Servo Motor Rotation
91 lines (84 loc) · 1.73 KB
/
Servo Motor Rotation
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
#include <Servo.h>
//Define horizontal and vertical servo motors
Servo servohori;
int servoh = 0;
int servohLimitHigh = 160;
int servohLimitLow = 60;
Servo servoverti;
int servov = 0;
int servovLimitHigh = 160;
int servovLimitLow = 60;
//Pin photoresistence
int ldrtopl = 2; //top left
int ldrtopr = 1; //top right
int ldrbotl = 3; // bottom left
int ldrbotr = 0; // bottom right
void setup ()
{
servohori.attach(10);
servohori.write(60);
servoverti.attach(9);
servoverti.write(60);
Serial.begin(9600);
delay(500);
}
void loop()
{
servoh = servohori.read();
servov = servoverti.read();
//Analog value of the photoresistor
int topl = analogRead(ldrtopl);
int topr = analogRead(ldrtopr);
int botl = analogRead(ldrbotl);
int botr = analogRead(ldrbotr);
// Let's calculate an average
int avgtop = (topl + topr) ; //average of top
int avgbot = (botl + botr) ; //average of bottom
int avgleft = (topl + botl) ; //average of left
int avgright = (topr + botr) ; //average of right
if (avgtop < avgbot)
{
servoverti.write(servov +1);
if (servov > servovLimitHigh)
{
servov = servovLimitHigh;
}
delay(10);
}
else if (avgbot < avgtop)
{
servoverti.write(servov -1);
if (servov < servovLimitLow)
{
servov = servovLimitLow;
}
delay(10);
}
else
{
servoverti.write(servov);
}
if (avgleft > avgright)
{
servohori.write(servoh +1);
if (servoh > servohLimitHigh)
{
servoh = servohLimitHigh;
}
delay(10);
}
else if (avgright > avgleft)
{
servohori.write(servoh -1);
if (servoh < servohLimitLow)
{
servoh = servohLimitLow;
}
delay(10);
}
else
{
servohori.write(servoh);
}
delay(50);
}