-
Notifications
You must be signed in to change notification settings - Fork 0
/
Line_Follower_Robot.ino
105 lines (91 loc) · 2.68 KB
/
Line_Follower_Robot.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
94
95
96
97
98
99
100
101
102
103
104
105
#define IR_SENSOR_RIGHT 8
#define IR_SENSOR_LEFT 9
#define MOTOR_SPEED 180
//Right motor
int enableRightMotor=3;
int rightMotorPin1=4;
int rightMotorPin2=5;
//Left motor
int enableLeftMotor=7;
int leftMotorPin1=2;
int leftMotorPin2=6;
void setup()
{
//The problem with TT gear motors is that, at very low pwm value it does not even rotate.
//If we increase the PWM value then it rotates faster and our robot is not controlled in that speed and goes out of line.
//For that we need to increase the frequency of analogWrite.
//Below line is important to change the frequency of PWM signal on pin D5 and D6
//Because of this, motor runs in controlled manner (lower speed) at high PWM value.
//This sets frequecny as 7812.5 hz.
TCCR0B = TCCR0B & B11111000 | B00000010 ;
// put your setup code here, to run once:
pinMode(enableRightMotor, OUTPUT);
pinMode(rightMotorPin1, OUTPUT);
pinMode(rightMotorPin2, OUTPUT);
pinMode(enableLeftMotor, OUTPUT);
pinMode(leftMotorPin1, OUTPUT);
pinMode(leftMotorPin2, OUTPUT);
pinMode(IR_SENSOR_RIGHT, INPUT);
pinMode(IR_SENSOR_LEFT, INPUT);
rotateMotor(0,0);
}
void loop()
{
int rightIRSensorValue = digitalRead(IR_SENSOR_RIGHT);
int leftIRSensorValue = digitalRead(IR_SENSOR_LEFT);
//If none of the sensors detects black line, then go straight
if (rightIRSensorValue == LOW && leftIRSensorValue == LOW)
{
rotateMotor(MOTOR_SPEED, MOTOR_SPEED);
}
//If right sensor detects black line, then turn right
else if (rightIRSensorValue == HIGH && leftIRSensorValue == LOW )
{
rotateMotor(-MOTOR_SPEED, MOTOR_SPEED);
}
//If left sensor detects black line, then turn left
else if (rightIRSensorValue == LOW && leftIRSensorValue == HIGH )
{
rotateMotor(MOTOR_SPEED, -MOTOR_SPEED);
}
//If both the sensors detect black line, then stop
else
{
rotateMotor(0, 0);
}
}
void rotateMotor(int rightMotorSpeed, int leftMotorSpeed)
{
if (rightMotorSpeed < 0)
{
digitalWrite(rightMotorPin1,LOW);
digitalWrite(rightMotorPin2,HIGH);
}
else if (rightMotorSpeed > 0)
{
digitalWrite(rightMotorPin1,HIGH);
digitalWrite(rightMotorPin2,LOW);
}
else
{
digitalWrite(rightMotorPin1,LOW);
digitalWrite(rightMotorPin2,LOW);
}
if (leftMotorSpeed < 0)
{
digitalWrite(leftMotorPin1,LOW);
digitalWrite(leftMotorPin2,HIGH);
}
else if (leftMotorSpeed > 0)
{
digitalWrite(leftMotorPin1,HIGH);
digitalWrite(leftMotorPin2,LOW);
}
else
{
digitalWrite(leftMotorPin1,LOW);
digitalWrite(leftMotorPin2,LOW);
}
analogWrite(enableRightMotor, abs(rightMotorSpeed));
analogWrite(enableLeftMotor, abs(leftMotorSpeed));
}