Electrical – Line follower robot using PID control

arduinorobotics

I'm using Arduino UNO for a pid line follower robot. The robot works great, but when it detects a T line, it deviates from the line. So I try to set the condition if all the sensors see black and then see white, deviate to left, that's what my intention. But the problem is with the if condition is never executed, it nevers see that all sensors are all black and then white. here is my code

void loop()
{
// convert analog signals into digital ones

    for (int i = 0 ; i < 5; i++)
      {

        if (sensors[i] > 900)
        {
          sensor[i] = 1;

        }
        else
        {
          sensor[i] = 0;
        }
      }

      for (int i = 0 ; i < 5; i++)
      {
        Serial.print(sensor[i]);
        Serial.print("\t");
      }
      Serial.println();


      if ((sensor[0] == 0) && (sensor[2] == 0) && (sensor[3] == 0) && (sensor[4] == 0))
      {
         if ((sensor[0] == 1)  && (sensor[2] == 1) && (sensor[3] == 1) && (sensor[4] == 1))
        {
          set_motors(0, 255);
          bLine = true;
          Serial.print("black");
        }
   }

Best Answer

Within your main loop, you assign values to the sensor[] array here:

if (sensors[i] > 900)
{
  sensor[i] = 1;
}
else
{
  sensor[i] = 0;
}

and then check the values here:

if ((sensor[0] == 0) && (sensor[2] == 0) && (sensor[3] == 0) && (sensor[4] == 0))
{
    if ((sensor[0] == 1)  && (sensor[2] == 1) && (sensor[3] == 1) && (sensor[4] == 1))
    {
      set_motors(0, 255);
      bLine = true;
      Serial.print("black");
    }
}

If you enter the first if statement (i.e., if all of the sensor[] elements are 0), then how would you ever enter the second if statement? You need some way to update the sensor values between the two. For example:

if ((sensor[0] == 0) && (sensor[2] == 0) && (sensor[3] == 0) && (sensor[4] == 0))
{
    delay(50); // adjust delay depending on robot speed

    // check all of the sensors again
    for (int i = 0 ; i < 5; i++)
    {
        if (sensors[i] > 900)
        {
            sensor[i] = 1;
        }
        else
        {
            sensor[i] = 0;
        }
    }

    if ((sensor[0] == 1)  && (sensor[2] == 1) && (sensor[3] == 1) && (sensor[4] == 1))
    {
        set_motors(0, 255);
        bLine = true;
        Serial.print("black");
    }
}