PID Line follower with only 2 on/off IR sensors

Hi guys,

I'm trying to program a line follower robot using PID. The problem is that the robot only has 2 IR sensors which returns 0 or 1. 0 : The sensor detects a line and 1 : no line.

This is the sensor : Me Line Follower | Makeblock Education

Is it possible to use a PID with such basic sensors?

Here's what I tried, without success.

// Param :
//  cT : Current time, basically millis()

void followLineTask(unsigned long cT) {
  static unsigned long lastTime = 0;
  const int rate = 10;

  const float kp = 2;
  const float ki = 0; // I am aware the values are 0
  const float kd = 0;

  static int lastError = 0;
  static int errorSum = 0;

  static int leftSpeed = speed;
  static int rightSpeed = -speed;

  static int error = 0;

  error = line.readSensors();
  
  switch (error) {
    case S1_IN_S2_IN:
      error = 0;
      leftSpeed = speed;
      rightSpeed = -speed;
      break;
    case S1_IN_S2_OUT:
      error = -1;
      break;
    case S1_OUT_S2_IN:
      error = 1;
      break;
    case S1_OUT_S2_OUT:
      error = lastError;
      break;
  }

  // Don't correct to frequently.
  if (cT - lastTime < rate) return;

  lastTime = cT;

  // integral part
  errorSum += error;  

  float pid = kp * error + ki * errorSum + kd * (error - lastError);
  pid = constrain (pid, -maxVariation, maxVariation );

  leftSpeed = constrain (leftSpeed + pid, -255, 255);
  rightSpeed = constrain (rightSpeed + pid, -255, 255);
  
  // Setting the target PWM (speed).
  encRight.setTarPWM(rightSpeed);
  encLeft.setTarPWM(leftSpeed); 

  // for differential part
  lastError = error;
}

Thanks

Not really, because "proportional error" is either 0 or 1.

This ridiculously simple line follower, which just uses two photodiodes and a comparator, rather than a computer, to make the steering decision, works reasonably well.

The idea behind PID is that the correction applied is to first order proportional to the error.

Can both sensors be on the line at the same time?

Yes, both sensors are on the line at the same time.

Since the proportional part is somewhat not possible (1 or 0). I think only the integral part is logically useful. I'm might also be wrong.

While searching the web, I've stumbled on this answer on Reddit.

From the reddit answer, I could simulate a proportional value by checking the time spent outside the line. I will need to sum the error let say for 10 ms and do the PID from this value. The set point is 0.

Is it a possible solution?

Try it and let us know if it works.

You can certainly average binary 1/0 values over time to get an intermediate number, but whether that would work for proportional steering is not immediately clear.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.