Skip to content
This repository was archived by the owner on Jun 24, 2026. It is now read-only.
This repository was archived by the owner on Jun 24, 2026. It is now read-only.

GP2Y0A02YK0F voltage to cm is not linear #9

Description

@peterwallhead

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;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions