Distance Measurement Using Sharp IR Sensor with Arduino UNO
This project demonstrates how to measure distance using a Sharp IR sensor with an Arduino UNO. The sensor will read the distance to an object and print the value to the Serial Monitor.
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 Uno 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 Uno
- Sharp IR Sensor
- Arduino Uno
- Jumper Wires
Wiring to the Arduino Uno
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 Uno 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
Copy and paste the provided code into the Arduino IDE.
Verify and upload the code to your Arduino board.
Example Code
Converting the nonlinear output to centimetres, with median filtering. Upload it with the board set to Arduino Uno 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 Uno
The Arduino Uno is built around the ATmega328P and runs on 5 V logic with 2 KB of SRAM and 32 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 Uno runs at 5 V, so most hobby sensor modules connect directly with no level shifting.
With only 2 KB of SRAM, avoid large buffers and prefer the F() macro for constant strings.
The single hardware UART is shared with the USB connection, so heavy Serial printing competes with uploads.
| Arduino Uno 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–A5 (six channels) | Determines how many analog sensors can share the board |
| PWM outputs | D3, D5, D6, D9, D10 and D11 | Needed for brightness, speed and tone control |
| I²C pins | A4 (SDA) and A5 (SCL) | Fixed by hardware — wiring copied from another board may not match |
| Interrupt pins | D2 and D3 only | Required for counting fast or asynchronous events |
| Serial | a single hardware UART shared with USB | 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 Uno 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 Uno I²C is on A4 (SDA) and A5 (SCL).
Taking It Further on the Arduino Uno
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 Uno specifically:
The Uno’s shield ecosystem is its real advantage. Once the circuit works on a breadboard, a prototyping shield turns it into something permanent that still stacks with a data-logging or Ethernet shield without rewiring.
Logging to an SD card via a shield is the natural next step, since the Uno has no onboard storage and no network. Timestamp each reading with a DS3231 real-time clock so the log survives power cuts with correct times.
Because SRAM is limited to 2 KB, keep logged strings short and write them out immediately rather than buffering. Building a long String in memory is the most common cause of an Uno sketch that runs for hours and then freezes.
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.