Distance Sharp IR Sensor
The Distance Sharp IR Sensor project demonstrates how to use an Arduino Mega with a Sharp IR distance sensor to measure distance accurately. This sensor provides analog voltage output corresponding to the distance of an object from the sensor. This project will show you how to read the analog output from the IR sensor, convert it into distance in centimeters, and display the distance readings on the Serial Monitor of Arduino IDE.
How It Works
A Sharp distance sensor such as the GP2Y0A21YK0F measures distance by triangulation, not by timing. An infrared LED emits a narrow beam; the reflected spot lands on a position-sensitive detector inside the package, and where it lands depends on how far away the object is. A closer object shifts the spot further across the detector.
This is a genuinely different principle from the obstacle sensors that merely report reflection, and it is why the Sharp part returns a usable distance rather than a yes/no. It is also why the output is highly nonlinear: voltage rises steeply as an object approaches, then flattens out with distance.
The GP2Y0A21YK0F is specified from 10 cm to 80 cm. Below 10 cm the curve folds back — the voltage falls again — so a reading of 2 V could mean either 10 cm or 4 cm. Any practical sketch must either guarantee nothing comes closer than 10 cm or combine the sensor with something that resolves the ambiguity.
The Arduino Mega 2560 samples with a 10-bit ADC, so analogRead() returns 0–1023 across 5 V. A common approximation for converting the reading is distance ≈ 27.86 × V^-1.15, valid across the specified range.
Components Needed
- Arduino Mega 2560
- Sharp IR Distance Sensor
- Jumper Wires
- Arduino Mega 2560
- Power Supply
Wiring to the Arduino Mega 2560
Connect the yellow output wire to A0, red to 5 V and black to ground. Both supply and output sit comfortably within the 5 V domain of this board.
A 10 µF capacitor across VCC and GND at the sensor is specified by Sharp and is not optional in practice. The emitter draws current in sharp pulses, and without local decoupling those pulses appear as noise on the output.
Mount the sensor so its beam is unobstructed and perpendicular to the expected target. Angled surfaces deflect the reflection away from the detector and read as "far away" or as nothing at all.
| Sensor wire | Arduino Mega 2560 pin | Function |
|---|---|---|
| Yellow (Vo) | A0 | Analog output, nonlinear with distance |
| Red (VCC) | 5V | Supply — the sensor expects 4.5–5.5 V |
| Black (GND) | GND | Common ground |
Build and Upload
Open Arduino IDE and create a new sketch.
Copy and paste the provided Arduino code into the sketch.
Upload the code to the Arduino Mega.
Open the serial monitor in Arduino IDE to view distance readings in centimeters.
Example Code
Converting the nonlinear output to centimetres, with median filtering. Upload it with the board set to Arduino Mega 2560 and open the Serial Monitor at 9600 baud.
const int SENSOR_PIN = A0;
const float VREF = 5.0;
const int ADC_MAX = 1023;
// Median of 5 rejects the occasional wild sample these sensors produce
int readMedian() {
int s[5];
for (int i = 0; i < 5; i++) { s[i] = analogRead(SENSOR_PIN); delay(5); }
for (int i = 0; i < 4; i++)
for (int j = i + 1; j < 5; j++)
if (s[j] < s[i]) { int t = s[i]; s[i] = s[j]; s[j] = t; }
return s[2];
}
void setup() { Serial.begin(9600); }
void loop() {
float volts = readMedian() * VREF / ADC_MAX;
if (volts < 0.4) { // below ~0.4 V the target is out of range
Serial.println("out of range (> 80 cm)");
} else {
float cm = 27.86 * pow(volts, -1.15); // Sharp GP2Y0A21 approximation
if (cm < 10.0) {
Serial.println("too close — reading ambiguous (< 10 cm)");
} else {
Serial.print("Distance: ");
Serial.print(cm, 1);
Serial.println(" cm");
}
}
delay(200);
}
Applications
A sharp infrared distance sensor turns up in a wide range of projects. These are the uses where it is the right choice rather than a compromise:
- Robot navigation where ultrasonic sensors struggle with soft or angled surfaces
- Queue and people counting at fixed range
- Liquid and material level sensing in hoppers and tanks
- Automatic door and barrier triggers
- Collision avoidance on small vehicles, paired with a wider-angle sensor
Working with the Arduino Mega 2560
The Arduino Mega 2560 is built around the ATmega2560 and runs on 5 V logic with 8 KB of SRAM and 256 KB of program flash. These details change how this circuit is wired and what the sketch can do, so they are worth stating plainly before you build.
The Mega’s 8 KB of SRAM is four times the Uno’s, so larger buffers and lookup tables are practical.
I²C lives on D20/D21 rather than A4/A5 — wiring copied from an Uno tutorial will not work unchanged.
Four hardware UARTs mean a serial sensor can have its own port instead of fighting SoftwareSerial.
| Arduino Mega 2560 characteristic | Value | Why it matters here |
|---|---|---|
| Logic voltage | 5 V | Matches most hobby modules directly |
| ADC resolution | 10-bit (0–1023) | Sets how finely an analog reading can be resolved |
| Analog inputs | A0–A15 (sixteen channels) | Determines how many analog sensors can share the board |
| PWM outputs | D2–D13 and D44–D46 | Needed for brightness, speed and tone control |
| I²C pins | D20 (SDA) and D21 (SCL) | Fixed by hardware — wiring copied from another board may not match |
| Interrupt pins | D2, D3, D18, D19, D20 and D21 | Required for counting fast or asynchronous events |
| Serial | four independent hardware UARTs | Monitor runs at 9600 baud by default |
Troubleshooting
Most problems with this module fall into a handful of categories. Work through these before suspecting the part itself:
- Distance readings fall as an object gets very close — you are in the fold-back region below 10 cm. Mechanically prevent anything approaching that close.
- The output is noisy — the 10 µF decoupling capacitor is missing. Fit it directly at the sensor.
- Dark objects read as further away — IR absorption reduces the returned signal. Expect reduced range on matte black.
- Readings jump wildly — use the median filter shown rather than a plain average; these sensors emit occasional spurious samples that an average smears across good data.
- Code written for an ESP board gives odd analog values — the Arduino Mega 2560 uses a 10-bit ADC returning 0–1023; rescale any constant taken from a 12-bit example.
- An I²C sensor is not found after copying wiring from another Arduino — on the Arduino Mega 2560 I²C is on D20 (SDA) and D21 (SCL).
Taking It Further on the Arduino Mega 2560
Once the basic reading works, where you go next depends very much on which board you are using. These are the directions that suit the Arduino Mega 2560 specifically:
The Mega’s sixteen analog inputs make it the right board when several of these sensors must run at once. Where an Uno would need an external multiplexer, the Mega simply reads A0 through A15 directly.
Four hardware UARTs mean a GPS, a serial display and a debug console can coexist without SoftwareSerial, which is unreliable above 38400 baud and blocks interrupts while it transmits.
With 8 KB of SRAM there is room to buffer readings and do real processing — a rolling average over several hundred samples, or holding a full display frame in memory, both of which are impractical on an Uno.
Notes and Practical Limits
Sharp sell several models with different ranges — the GP2Y0A41SK0F covers 4–30 cm and the GP2Y0A02YK0F covers 20–150 cm. The conversion constants differ for each, so check which part you have before trusting a formula found online.
Where ultrasonic and infrared both fit, they fail differently: ultrasonic struggles with soft fabric and angled surfaces, infrared struggles with dark and shiny ones. Projects that must be reliable often carry both.