So im building a line follower robot 2 with 5 IR sensor. in my PID code error algorithm, it seems like there is a problem in giving the exact error even it shows detection in all sensors.
here is the code
float Kp=1,Ki=.5,Kd=1;
float error=0, P=0, I=0, D=0, PID_value=0;
float previous_error=0, previous_I=0;
int sensor[5]={0, 0, 0, 0, 0};
int initial_motor_speed=100;
void read_sensor_values(void);
void calculate_pid(void);
void motor_control(void);
void readings(void);
void setup()
{
pinMode(5,OUTPUT); //E1
pinMode(6,OUTPUT); //E2
pinMode(4,OUTPUT); //Left Motor Pin 1
pinMode(7,OUTPUT); //right Motor Pin 2
Serial.begin(9600); //Enable Serial Communications
}
void loop()
{
read_sensor_values();
readings();
}
void read_sensor_values()
{
sensor[0]=digitalRead(A0);
sensor[1]=digitalRead(A1);
sensor[2]=digitalRead(A2);
sensor[3]=digitalRead(A3);
sensor[4]=digitalRead(A4);
if((sensor[0]==0)&&(sensor[1]==0)&&(sensor[2]==0)&&(sensor[4]==0)&&(sensor[4]==0))
error=8; // 0 0 0 0 0
else if((sensor[0]==1)&&(sensor[1]==1)&&(sensor[2]==1)&&(sensor[4]==1)&&(sensor[4]==1))
error=9; // 1 1 1 1 1
else if((sensor[0]==0)&&(sensor[1]==0)&&(sensor[2]==0)&&(sensor[4]==0)&&(sensor[4]==1))
error=-4; // 0 0 0 0 1
else if((sensor[0]==0)&&(sensor[1]==0)&&(sensor[2]==0)&&(sensor[4]==1)&&(sensor[4]==1))
error=-3; // 0 0 0 1 1
else if((sensor[0]==0)&&(sensor[1]==0)&&(sensor[2]==0)&&(sensor[4]==1)&&(sensor[4]==0))
error=-2; //0 0 0 1 0
else if((sensor[0]==0)&&(sensor[1]==0)&&(sensor[2]==1)&&(sensor[4]==1)&&(sensor[4]==0))
error=-1; //0 0 1 1 0
else if((sensor[0]==0)&&(sensor[1]==0)&&(sensor[2]==1)&&(sensor[4]==0)&&(sensor[4]==0))
error=0; //0 0 1 0 0
else if((sensor[0]==0)&&(sensor[1]==1)&&(sensor[2]==1)&&(sensor[4]==0)&&(sensor[4]==0))
error=5;
else if((sensor[0]==0)&&(sensor[1]==1)&&(sensor[2]==0)&&(sensor[4]==0)&&(sensor[4]==0))
error=6;
else if((sensor[0]==1)&&(sensor[1]==1)&&(sensor[2]==0)&&(sensor[4]==0)&&(sensor[4]==0))
error=7;
else if((sensor[0]==1)&&(sensor[1]==0)&&(sensor[2]==0)&&(sensor[4]==0)&&(sensor[4]==0))
error=11;
}
void readings()
{
Serial.print(digitalRead(A0)),Serial.print(digitalRead(A1)),Serial.print(digitalRead(A2)),Serial.print(digitalRead(A3)),Serial.println(digitalRead(A4));
Serial.println(error);
Serial.println("-----");
delay(300);
}