Line position from sensor values. (NOT a pololu board).

Hi, I'm working on a reflective sensor array at the moment which uses three RGB leds and three sensors, which I call l, m and r in my sketch for a line following vehicle.

analogRead nets the following readings (examples):

175, 33, 184  (middle of line, 33 is the black line value)
29, 134, 177 (right of the line)
179, 104, 24 (left of the line)

these are readings for the l m and r sensors respectively. I want to map these readings to
either errors, such as positive for right of line and negative for left of line. Currently I have a few else if statements, but i'm sure there is an easier way to do this. I want to use the error values for PID in another function.

here's what the relevant snippet of the sketch looks like.

void detect() {
	const int bval = 50;
	if (l >= bval && m >= bval && r <= bval) {
		error = 2;
	}
	else if (l >= bval && m <= bval && r <= bval) {
		error = 1;
	}
	else if (l <= bval && m <= bval && r <= bval) {
		error = 0;
	}
	else if (l <= bval && m <= bval && r >= bval) {
		error = -1;
	}
	else if (l <= bval && m >= bval && r >= bval) {
		error = -2;
	}
}

I don't think there is a very easy way. I can't see an easy relation between the error and the sensors. But you could make the code a bit simpler and faster by making 1 variable to check instead of 3 each time.

I also took the liberty to change all variable names. One letter variables are only good for a small scope like a for loop. Not to be a global variable. A name should tell what it is. So better a longer name that explains what it is the a short cryptic. So changed them to sensorValues and sensorThreshold. sensorValues is an array. See Gammon Tip 1.

Also added error code 100 as a out of bound error code.

int8_t detect(){
  int8_t error = 0;
  //check all sensors to see if they are light or dark
  for(byte 1 = 0; i < 3; i++){
    error <<= 1;
    error |= (sensorValues[i] > sensorThreshold);
  }
  
  //Make that correspond with error number
  if(error == 0b110)
    error = 2;
  else if(error == 0b100)
    error = 1;
  else if(error == 0b000)
    error = 0;
  else if(error == 0b001)
    error = -1;
  else if(error == 0b011)
    error = -2;
  else
    error = 100; //out of bound
  
  return error;
}

Thank you. This works very well!