PID for Arduino Line-following

I use the following code for a line-follower driven by two rear wheels and a castor wheel. The sensor array is a row of 8.
But the lMotorSpeed doesn't vary with the position of the line with respect to the sensor array. A black line on a white surface was used and black returns val_>500 and white val*<500._
Please help me find the fault. Kp Ki Kd values are not fully adjusted yet. :slight_smile:
_
```_
#define Kp 2
#define Ki 0.0004
#define Kd 1
#define MaxSpeed 255
#define baseSpeed 180

#define rMotor1 34
#define rMotor2 35
#define lMotor1 30
#define lMotor2 31
#define lMotorPWM 3
#define rMotorPWM 2

int rMotorSpeed,lMotorSpeed,error_value;
long sensors_average,integral;
int sensors_sum,position,proportional,derivative,last_proportional;
int set_point=13;

int val[8]={0};

int th=500;// less than th means W

void sensors_read(){
  val[0]=analogRead(A0);
  val[1]=analogRead(A1);
  val[2]=analogRead(A2);
  val[3]=analogRead(A3);
  val[4]=analogRead(A4);
  val[5]=analogRead(A5);
  val[6]=analogRead(A6);
  val[7]=analogRead(A7);
 
  for(int i=0;i<8;i++)
  {
    sensors_average+=val[i]i1000;
    sensors_sum+=int(val[i]);
   
 
  }
 
 
}
void pid_calc(){
    position=int(sensors_average/sensors_sum);
    proportional=position-set_point;
    integral=integral+proportional;
    derivative=proportional-last_proportional;
    last_proportional=proportional;
    //Serial.print(position); Serial.print(" || ");
    //delay(300);
   
    error_value = int(proportional * Kp + integral * Ki + derivative * Kd);
    //Serial.print(error_value);Serial.print("\n");
    //delay(300);
 
  }
 
void calc_turn()
  {
   
    rMotorSpeed=baseSpeed+error_value;
   
    lMotorSpeed=baseSpeed-error_value;
       
    if(rMotorSpeed>MaxSpeed)
      rMotorSpeed=MaxSpeed;
    if(lMotorSpeed>MaxSpeed)
      lMotorSpeed=MaxSpeed;
    if(rMotorSpeed<0)
      rMotorSpeed=0;
    if(lMotorSpeed<0)
      lMotorSpeed=0;
   
    Serial.print(rMotorSpeed); Serial.print(' ');
    Serial.print(lMotorSpeed);Serial.print("\n");
    //delay(300);
  }
 
void motor_drive(int rSpeed,int lSpeed)
{
    analogWrite(rMotorPWM,rSpeed);
    analogWrite(lMotorPWM,lSpeed);
    delay(50);

}

void setup()
{
 
  Serial.begin(9600);
  pinMode(lMotor1, OUTPUT); 
  pinMode(lMotor2, OUTPUT);     
  pinMode(rMotor1, OUTPUT); 
  pinMode(rMotor2, OUTPUT);
  digitalWrite(lMotor1,HIGH);
  digitalWrite(lMotor2,LOW);
  digitalWrite(rMotor2,HIGH);
  digitalWrite(rMotor1,LOW);
 
  pinMode(rMotorPWM, OUTPUT); 
  pinMode(lMotorPWM, OUTPUT); 
 
 
   
}

void loop()
{
  sensors_average=0;
  sensors_sum=0; 
  sensors_read();
 
  pid_calc();
  calc_turn();
  motor_drive(rMotorSpeed,lMotorSpeed);
 
 
 
}
_
```*_

AC_FOLLOWER_2_0.ino (3.37 KB)