tutorialspinouttools
Sensors · ESP32-C3

Sharp GP2Y0A21 on OLED: IR Distance

Free ESP32 & Arduino tutorial · wiring, code & parts · gokul.builds

Overview & Wiring

What it is: The Sharp GP2Y0A21YK0F is an analog infrared distance sensor with a 10–80 cm range. It uses triangulation, so it's immune to surface colour and works where ultrasonic struggles (soft, angled targets). How it works: An IR LED and a position-sensitive detector triangulate the reflection; the sensor outputs an analog voltage that falls as distance grows (a non-linear curve). This sketch converts the voltage to centimetres with the standard power-law fit. Wiring: GP2Y0A21 VO -> GPIO0 (analog, yellow wire) GP2Y0A21 VCC -> 5V (red wire — needs 5V) GP2Y0A21 GND -> GND (black wire) OLED VCC=3V3, GND=GND, SDA=GPIO4, SCL=GPIO5 Libraries: only "Adafruit SSD1306" and "Adafruit GFX Library". On screen / Serial: distance in cm. Move a book toward and away between 10 and 80 cm. Gotchas: Below ~10 cm the reading folds back and becomes ambiguous — keep targets beyond 10 cm. The output peaks around 3.1 V (safe for the 3.3 V ADC). Readings are noisy; the sketch averages several samples. Use the JST 3-pin cable that comes with the sensor.

Circuit Diagram

Sharp GP2Y0A21 on OLED: IR Distance wiring diagram for ESP32-C3

Parts You Need

ESP32-C3 SuperMiniBuy →
0.96" SSD1306 OLEDBuy →

Source Code (Arduino / ESP32)

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <math.h>

Adafruit_SSD1306 display(128, 64, &Wire, -1);

#define IRD 0                 // VO on GPIO0 (ADC)

void setup() {
  Serial.begin(115200);
  Wire.begin(4, 5);
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
}

void loop() {
  long sum = 0;
  for (int i = 0; i < 16; i++) sum += analogReadMilliVolts(IRD); // average
  float volts = (sum / 16.0) / 1000.0;

  float cm = 27.86 * pow(volts, -1.15);        // Sharp GP2Y0A21 fit (10-80 cm)
  if (cm > 80) cm = 80;
  if (cm < 10) cm = 10;

  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.println("GP2Y0A21 IR");
  display.setTextSize(3);
  display.setCursor(0, 22);
  display.printf("%.0f", cm);
  display.setTextSize(1);
  display.setCursor(0, 54); display.print("cm");
  display.display();

  Serial.printf("Distance: %.1f cm  (%.2f V)\n", cm, volts);
  delay(200);
}
Browse all tutorials ESP32-C3 pinout Calculators