I and my brother started to build a line follower with one Line Finder sensor. This is our first Arduino project, please help us to improve the code. Is it okay? It’s very important for my brother.
Parameters:
ArduinoATMega2560
Pololu tb6612fng
2 DC motos 5V
1 Line Finder Sensor
I uploaded the Schematic and the Code.
Code:
Code: Select all
#define M1 44 //Pin4 : Motor1 direction of rotation (Left Motor)
#define EN1 5 //Pin5 : Motor1 speed (PWM)
#define EN2 6 //Pin6 : Motor2 speed (PWM)
#define M2 46 //Pin7 : Motor2 direction of rotation (Right Motor)
int LineFinder = 52; // sensor input is connected to digital
int Motor = 80; // Initial motor speed
int limit = 820; // Line detection limit
void setup() //settings
{
pinMode(EN1, OUTPUT); //Motor1 speed lab: output
pinMode(EN2, OUTPUT); //Motor2 speed lab: output
pinMode(M1, OUTPUT); // Motor1 direction of rotation lab: output
pinMode(M2, OUTPUT); // Motor2 direction of rotation lab: output
}
void loop() //Main program - infinite loop
{
LineFinder = digitalRead (52); // voltage measurement of sensor (0 - 1023 value between)
// If the sensor is above the pale floor: forward
if (LineFinder>Limit)
{
MotorLeft(Motor-2); //Left motor: forward
MotorRight(Motor); //Right motor: forward
}
// If the sensor is above the line: Turn left
else if (LineFinder>Limit)
{
MotorLeft(0); //Left motor: stop
MotorRight(Motor); //Right motor: forward
}
// Forward (the sensor is above the line: crossroads)
else if (LineFinder>Limit)
{
MotorLeft(Motor-2); //Left motor: forward
MotorRight(Motor); //Right motor: forward
}
delay(50); // Wait 50ms
}
void MotorLeft(int speed)
{
if (speed>0) //Forward
{
digitalWrite(M1,HIGH); //M1 direction (forward)
analogWrite(EN1,speed*255/100); //M1 speed(PWM)
}
else //Reverse
{
digitalWrite(M1,LOW); //M1 direction (reverse)
analogWrite(EN1,abs(speed)*255/100); //M1 speed(PWM)
}
}
void MotorRight(int speed)
{
if (speed>0) //Forward
{
digitalWrite(M2,HIGH); //M2 diretion (forward)
analogWrite(EN2,speed*255/100); //M2 speed(PWM)
}
else //Reverse
{
digitalWrite(M2,LOW); //M2 direction (reverse)
analogWrite(EN2,abs(speed)*255/100); //M2 speed(PWM)
}
}