// https://wokwi.com/projects/413140270173388801
// Simulate line-following sensors with pots
// and return a weighted average of the position
// within the line.

// See https://github.com/pololu/qtr-sensors-arduino/blob/4a0d1c59842307164735f923f0eb99cbb2538428/QTRSensors.cpp#L644
// for Pololu's code
const int DEBUG = 0;
const int PotPins[] = {A0, A1, A2, A3, A4, A5, A6, A7};
const int NumPots = sizeof(PotPins) / sizeof(PotPins[0]);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
  static int lastLineVal = 0;
  int lineVal = readSensorLine();
  if ( lineVal != lastLineVal) {
    int delta = lineVal - lastLineVal;
    lastLineVal = lineVal;
    Serial.print("line:");
    Serial.print(lineVal);
    Serial.println();
  }
}

int16_t readSensorLine() {
  int ii = 1;
  uint32_t sum = 0, sumWeight = 0;
  static uint16_t retval = 0;
  for (auto & pin : PotPins ) {
    int val = analogRead(pin);
    sum += val;
    sumWeight += ii * 1000L * val;
    ++ii;
  }
  if (DEBUG) {
    char buff[50];
    snprintf(buff, 49, " %lu/%lu=%lu", sumWeight, sum, sum > 0 ? sumWeight / sum : 0 );
    Serial.println(buff);
    delay(500);
  }
  if (sum > 0) { // guard against /0
    retval = ( sumWeight / sum);
  } else {
    ;
    retval = 0; // indicate no reading, comment to hold last
  }
  return retval;
}