For context, I am trying to create a line following robot using two motors and a Polulu QTR8 sensor array, I am a beginner to arduino but fancied the challenge. I will share my code, hopefully I can get some feedback and pointers on what I've done wrong.
#include<AFMotor.h> //Include Adafruit Motor Driver Shield Library
//create motor obejects
AF_DCMotor motor1(1, MOTOR12_1KHZ);
AF_DCMotor motor2(2, MOTOR12_1KHZ);
#define FIRST_SENSOR A0 // connect the sensor with analog pin A0
#define SECOND_SENSOR A1 // connect the sensor with analog pin A1
#define THIRD_SENSOR A2 // connect the sensor with analog pin A2
#define FOURTH_SENSOR A3 // connect the sensor with analog pin A3
#define FIFTH_SENSOR A4 // connect the sensor with analog pin A4
#define SIXTH_SENSOR A5 // connect the sensor with analog pin A5
void setup() {
pinMode(FIRST_SENSOR, INPUT); // initialize first sensor as an inut
pinMode(SECOND_SENSOR, INPUT); // initialize second sensor as as input
pinMode(THIRD_SENSOR, INPUT); // initialize third sensor as as input
pinMode(FOURTH_SENSOR, INPUT); // initialize fourth sensor as as input
pinMode(FIFTH_SENSOR, INPUT); // initialize fifth sensor as as input
pinMode(SIXTH_SENSOR, INPUT); // initialize sixth sensor as as input
}
void loop() {
if (analogRead(SECOND_SENSOR) <= 100 && !analogRead(FIRST_SENSOR) <= 100) //compare both sensor value to set the direction
{
motor1.run(FORWARD); // run motor1 clockwise
motor1.setSpeed(255); // set motor1 speed 50 percent
motor2.run(BACKWARD); // run motor2 clockwise
motor2.setSpeed(255); // set motor2 speed percent
}
else if (!analogRead(SECOND_SENSOR) >= 100 && !analogRead(FIRST_SENSOR) <= 100) //compare both sensor value to set the direction
{
motor1.run(FORWARD); // run motor1 clockwise
motor1.setSpeed(255); // set motor1 speed 100 percent
motor2.run(FORWARD); // run motor2 anti-clockwise
motor2.setSpeed(255); // set motor2 speed 100 percent
}
else if (analogRead(SECOND_SENSOR) >= 100 && !analogRead(FIRST_SENSOR) >= 100) //compare both sensor value to set the direction
{
// motor1.run(BACKWARD); // run motor1 anti-clockwise
//motor1.setSpeed(255); // set motor1 speed 100 percent
//motor2.run(BACKWARD); // run motor2 clockwise
//motor2.setSpeed(255); // set motor2 speed 100 percent
}
else if (!analogRead(SECOND_SENSOR) <= 100 && !analogRead(FIRST_SENSOR) >= 100) //compare both sensor value to set the direction
{
//stop all the motors
motor1.run(RELEASE);
motor2.run(RELEASE);
}
}