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