Labs / Electronic modules

GraftSense: An Infrared Distance Measurement Sensor Module Based on GP2Y0A21YK (Open Version)

Author: Li Zisheng · Source: FreakStudio open documentation, v1.1 · License: CC BY 4.0 · Driver code (sensors/gp2y0a21yk_driver): MIT License

Contents
GP2Y0A21YK
GP2Y0A21YK-Based V1.0.0 A1N

I. Module Introduction

GP2Y0A21YK-based infrared ranging sensor module that adopts Sharp's GP2Y0A21YK infrared ranging sensor solution. Based on the reflective triangulation ranging principle, it can realize non-contact distance detection within 10~80cm, and output analog voltage signals corresponding to the distance; the module is equipped with power filter and indicator circuit, powered by 4.5~5.5V, built-in signal processing circuit, featuring strong anti-interference ability, fast response, compact size and easy installation, which is suitable for short-distance ranging scenarios such as robot obstacle avoidance, proximity detection and smart cars.

II. Introduction to Main Chips

GP2Y0A21YK is an infrared triangular ranging sensor from Sharp, featuring analog voltage output, a ranging range of 10-80cm, and a power supply of 3-5V, which is commonly used for short-distance detection.

2.1 Chip Overview

GP2Y0A21YK0F 10 80cm

GP2Y0A21YK0F is an analog-output infrared ranging sensor from Sharp, which adopts the triangulation method with a ranging range of 10-80cm, has a built-in PSD and infrared emitting diode, operates on a supply voltage of 4.5-5.5V, draws a typical current of 30mA, measures 29.5×13×13.5mm in dimensions, outputs a voltage signal corresponding to the measured distance, can be used as a proximity sensor, is suitable for scenarios such as sweeping robots and non-contact switches, and complies with the RoHS standard.

2.2 Pin Definition

GP2Y0A21YK0F 16.3mm 13.5mm 21.5mm S3B-PH 2.2

GP2Y0A21YK0F adopts a 3-pin JST connector, with pin definitions as follows: ① Vo is the analog distance output terminal, ② GND is the power ground, ③ Vcc is the power supply terminal. The module's housing is made of conductive ABS material, the lens is made of visible light filtering acrylic resin, and the overall dimensions are 29.5×13×13.5mm.

2.3 Functional Block Diagram

GP2Y0A21YK0F

Driven by LED drive circuit, the infrared LED emits infrared light, which is reflected by the target and then received by the PSD position-sensitive detector. After being processed by the signal processing circuit, oscillation circuit and output circuit, the signal outputs an analog voltage signal corresponding to the distance from the Vo pin. The voltage regulator inside the module provides stable power supply for the ranging IC.

2.4 Performance Parameters

GP2Y0A21YK 4.5 5.5V

GP2Y0A21YK0F has a recommended power supply voltage of 4.5–5.5V, a withstand voltage range of -0.3V to + 7V, and an operating temperature range of -10°C to + 60°C; its typical operating current is 30mA, the ranging range is 10–80cm, the typical output voltage is 0.4V at 80cm, and the typical output voltage difference between 10cm and 80cm is 1.9V. All the above data are measured under the conditions of 25°C, 5V power supply, and white paper with 90% reflectivity.

2.5 Reference Circuit

None.

2.6 Chip Configuration

None.

GP2Y0A21YK 38.3ms 9.6ms 5.0ms

GP2Y0A21YK0F takes approximately 38.3ms±9.6ms for the module's first measurement after power-on, during which the output is unstable; the first valid data output requires an additional waiting period of up to 5.0ms, and subsequent measurements will continuously update the output voltage signal according to the cycle.

2.8 PCB Routing Precautions

None.

III. Circuit Engineering

3.1 Circuit Source Engineering

To obtain the source code of the circuit, please follow the official account [Freak Embedded]

3.2 Module Usage Instructions

The schematic diagram of this module is shown below:

SCH_Schematic1_Infrared Distance Sensor Module Based on GP2Y0A21YK_v1.0.0_2026-05-08.pdf 2.1 MB

GP2Y0A21YK-Based V1.0.0

This module uses analog output AIN: This pin can convert the 10~80cm distance signal detected by GP2Y0A21YK into a linear analog voltage signal corresponding to the distance, which can be directly connected to the main controller's ADC port to read the voltage value and convert it to the actual distance, suitable for short-distance ranging scenarios such as robot obstacle avoidance, proximity detection, and intelligent cars.

3.3 Application Experiment

Here, we use the GraftPort-RP2040 development board for testing. The infrared ranging sensor module based on GP2Y0A21YK communicates with the main controller via the AIN interface.

Here, we first use the HY2.0-4P connection cable to connect the module to the GraftPort-RP2040 development board's AIN0 interface:

GP2Y0A21YK HY2.0-4P GraftPort-RP2040

development board pins

Module Pins

Description

Pin 26

AIN

Sensor Protocol Signal Line

Pin 19

NC

-

Here, we need to search for the relevant driver packages on uPyPI: https://upypi.net/zh/

106 gp2y0a21yk_driver

Enter gp2y0a21yk_driver to search, and the following will be displayed:

gp2y0a21yk_driver 1.0.8 GP2Y0A21YK0F 2026 05 08

Click to copy the local installation command:

gp2y0a21yk_driver GP2Y0A21YK0F 1.0.0

Import the module driver library code via the mip tool. Below are the usage commands for the mpremote tool:

mpremote mip install https://upypi.net/pkgs/gp2y0a21yk_driver/1.0.0

Import the infrared ranging sensor module based on GP2Y0A21YK - MicroPython driver code, then copy the following main.py code into our project:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-
# @Time    : 2026/04/22 14:15
# @Author  : hogeiha
# @File    : main.py
# @Description : GP2Y0A21YK0F infrared distance sensor reading example
# @License : MIT


# ======================================== Import Modules =========================================

import time
from gp2y0a21yk import GP2Y0A21YK


# ======================================== Global Variables ============================================

# Pico ADC pin connected to the sensor analog output
DISTANCE_ADC_PIN = 26

# Pico ADC reference voltage
ADC_REF_VOLTAGE = 3.3

# Number of samples to average
AVERAGE_COUNT = 5

# Data reading interval (milliseconds)
PRINT_INTERVAL = 500

# Near-distance threshold (cm)
CLOSE_THRESHOLD_CM = 20

# Far-distance threshold (cm)
FAR_THRESHOLD_CM = 40


# ======================================== Functions ============================================


# ======================================== Custom Classes ============================================


# ======================================== Initialization configuration ===========================================

# Wait for the system and sensor power to stabilize
time.sleep(3)

# Print the program function prompt
print("FreakStudio: GP2Y0A21YK distance sensor")

# Create the GP2Y0A21YK0F sensor object
sensor = GP2Y0A21YK(distance_pin=DISTANCE_ADC_PIN)

# Set the ADC reference voltage
sensor.set_ref_voltage(ADC_REF_VOLTAGE)

# Set the number of samples to average
sensor.set_averaging(AVERAGE_COUNT)

# Enable sensor reading
sensor.set_enabled(True)

# Initialize the last print timestamp
last_print_time = time.ticks_ms()


# ========================================  Main Program  ============================================

try:
    while True:

        # Get the current timestamp
        current_time = time.ticks_ms()

        # Read and print sensor data at the set interval
        if time.ticks_diff(current_time, last_print_time) >= PRINT_INTERVAL:

            # Read the raw ADC value
            raw = sensor.get_distance_raw()

            # Read the sensor output voltage
            voltage = sensor.get_distance_volt()

            # Read the estimated distance
            distance = sensor.get_distance_centimeter()

            # Print the measurement results
            print(
                "Raw: {}, Voltage: {:.1f} mV, Distance: {} cm".format(
                    raw,
                    voltage,
                    distance,
                )
            )

            # Check whether the object is closer than the near-distance threshold
            if sensor.is_closer(CLOSE_THRESHOLD_CM):
                print("Object is close")

            # Check whether the object is farther than the far-distance threshold
            if sensor.is_farther(FAR_THRESHOLD_CM):
                print("Object is far")

            # Update the last print timestamp
            last_print_time = current_time

        # Sleep briefly to reduce CPU usage
        time.sleep_ms(10)

except KeyboardInterrupt:
    print("Program interrupted by user")
except OSError as e:
    print("Hardware communication error: %s" % str(e))
except Exception as e:
    print("Unknown error: %s" % str(e))
finally:
    print("Cleaning up resources...")
    sensor.deinit()
    del sensor
    print("Program exited")

Burn the code, open the terminal, and the output is as follows:

GP2Y0A21YK 43098 5985 2184.0 273.2 12 80

Blocking infrared rays with an object enables distance measurement:

GP2Y0A21YK R60 R80

GP2Y0A21YK The infrared distance sensor works properly, capable of stably outputting raw values, voltage and distance data; when an object approaches or moves away, the distance reading updates in real time with the position change, the "Object is close/far" status switches synchronously, and the detection response is normal when the infrared ray is blocked by a hand.

IV. Drivers

gp2y0a21yk_driver-1.0.0.zip 11 KB

None.

VI. Revision History

Document Version

Date of Revision

Modifier

Modify Content

v1.0

2026-05-08

Zero High-Luck

Initialize the document

v1.1

2026-06-03

Xin Ruili

Sorting completed.

VII. Relevant Materials

7.1 Chip Datasheet

GP2Y0A21YK.pdf 365 KB

7.2 Unique Icons for PCB Silk Screen

GP2Y0A21YK 7.2
7.2 GP2Y0A21YK