Arduino_SharpIR icon indicating copy to clipboard operation
Arduino_SharpIR copied to clipboard

GP2Y0A02YK0F voltage to cm is not linear

Open peterwallhead opened this issue 1 year ago • 0 comments

SOLVED

This caught me out.

The datasheet for this SharpIR sensor shows a non-linear mapping between the output voltage and distance, but this package uses an average linear mapping calculation. This causes lines that should be straight to become curved in scan plots.

image

I solved this by not using this package, but instead by writing 2 semi-linear maps that use data directly from the analogRead() which gives me a lot more accurate results:

int getDistance(int sensorPin, int numberOfSamplesToCollect, int samplingRate) {
  int distance = 0;
  int distancesSum = 0;

  for (int i = 0; i < numberOfSamplesToCollect; i++) {
    int analogSensorReading = analogRead(sensorPin);

    if(analogSensorReading > 200) {
      distance = map(analogSensorReading, 544, 200, 15, 60);
    } else {
      distance = map(analogSensorReading, 175, 81, 70, 150);
    }

    distancesSum += distance;

    delay(samplingRate);
  }

  int averageDistance = distancesSum / numberOfSamplesToCollect;

  return averageDistance;
}

peterwallhead avatar Sep 27 '24 10:09 peterwallhead