# Pid line follower robot using line sensor and arduino

I’m trying to do a line following but the problem is there is a T junction in the track. I figured out that I have to reverse one direction of the motor backward and the other is forward, but the library of ada fruit doesn’t respond to negative speeds, how would I modify the pid code so it reverses the direction of motors when it finds a T junction.

``````void loop()
{
unsigned int sensors[5];
int position = qtrrc.readLine(sensors); //get calibrated readings along with the line position, refer to the QTR Sensors Arduino Library for more details on line position.
int error = 2500 - position;

int motorSpeed = Kp * error + Kd * (error - lastError);
lastError = error;

int leftMotorSpeed = M1_maksimum_speed + motorSpeed;
int rightMotorSpeed = M1_maksimum_speed - motorSpeed;

// set motor speeds using the two motor speed variables above
set_motors(leftMotorSpeed, rightMotorSpeed);
}

void set_motors(int motor1speed, int motor2speed)
{
if (motor1speed > M1_maksimum_speed ) motor1speed = M1_maksimum_speed;
if (motor2speed > M2_maksimum_speed ) motor2speed = M2_maksimum_speed;
if (motor1speed < 0) motor1speed = 0;
if (motor2speed < 0) motor2speed = 0;
motor1.setSpeed(motor1speed);
motor2.setSpeed(motor2speed);
motor1.run(FORWARD);
motor2.run(FORWARD);
}
``````

Hello.

I suspect your robot will likely need some additional logic for deciding which way to turn at the T-junction. Simply using PID could result in different outcomes depending on what slight angle your robot is at when it reaches the junction.

Could you post more information about your system? What library are you using? It looks like your set_motors() function is limiting the motor1speed and motor2speed variables to positive values only (e.g. `if (motor1speed < 0) motor1speed = 0;` and `if (motor2speed < 0) motor2speed = 0;`); is this intentional?

Brandon