Skip to main content
ESPBoards

ESP32 KY-050 Ultrasonic Distance Sensor Module

The KY-050 is an ultrasonic distance sensor module capable of measuring distances ranging from 2 cm to 300 cm with a resolution of approximately 3 mm. It emits a 40 kHz ultrasonic pulse and measures the time taken for the echo to return, allowing for precise distance calculations.

⬇️ Jump to Code Examples

Arduino Core Image
ESP-IDF Image
ESPHome Image
PlatformIO Image
MicroPython Image

🔗 Quick Links

KY-050 Ultrasonic Distance Sensor Module Datasheet ButtonKY-050 Ultrasonic Distance Sensor Module Specs ButtonKY-050 Ultrasonic Distance Sensor Module Specs ButtonKY-050 Ultrasonic Distance Sensor Module Specs Button

ℹ️ About KY-050 Ultrasonic Distance Sensor Module

The KY-050 Ultrasonic Distance Sensor Module is designed for non-contact distance measurements. It operates by emitting an ultrasonic pulse and measuring the time it takes for the echo to return after reflecting off an object. This module is ideal for applications such as obstacle detection, distance measurement, and level sensing in various projects.

⚙️ KY-050 Sensor Technical Specifications

Below you can see the KY-050 Ultrasonic Distance Sensor Module Technical Specifications. The sensor is compatible with the ESP32, operating within a voltage range suitable for microcontrollers. For precise details about its features, specifications, and usage, refer to the sensor’s datasheet.

  • Type: module
  • Protocol: Digital
  • Operating Voltage: 5V
  • Measuring Range: 2 cm to 300 cm
  • Resolution: 3 mm
  • Ultrasonic Frequency: 40 kHz
  • Minimum Time Between Measurements: 50 µs
  • Dimensions: 45 mm x 20 mm x 15 mm

🔌 KY-050 Sensor Pinout

Below you can see the pinout for the KY-050 Ultrasonic Distance Sensor Module. The VCC pin is used to supply power to the sensor, and it typically requires 3.3V or 5V (refer to the datasheet for specific voltage requirements). The GND pin is the ground connection and must be connected to the ground of your ESP32!

  • VCC: Connects to the power supply, typically 5V.
  • Trig: Trigger input; connect to a digital output pin on the microcontroller.
  • Echo: Echo output; connect to a digital input pin on the microcontroller.
  • GND: Connects to the ground of the circuit.

🛠️ KY-050 Ultrasonic Distance Sensor Module Troubleshooting

This guide outlines a systematic approach to troubleshoot and resolve common problems with the . Start by confirming that the hardware connections are correct, as wiring mistakes are the most frequent cause of issues. If you are sure the connections are correct, follow the below steps to debug common issues.

❌ No Distance Reading

Issue: The sensor does not provide any distance measurements.

Solutions:

  • Ensure all connections are secure and correctly wired according to the pinout diagram.
  • Verify that the microcontroller's pins are properly configured in the code.
  • Check for proper power supply voltage (5V) to the module.
  • Ensure that the trigger pulse is at least 10µs long.

⚠️ Incorrect Distance Measurements

Issue: The sensor provides inaccurate or fluctuating distance readings.

Solutions:

  • Ensure there are no obstacles or reflective surfaces interfering with the ultrasonic signal.
  • Check for noise or interference on the power supply lines; consider adding decoupling capacitors if necessary.
  • Verify that the sensor is operating within its specified range (2 cm to 300 cm).

💻 Code Examples

Below you can find code examples of KY-050 Ultrasonic Distance Sensor Module with ESP32 in several frameworks:

If you encounter issues while using the KY-050 Ultrasonic Distance Sensor Module, check the Common Issues Troubleshooting Guide.

Arduino Core Image

ESP32 KY-050 Arduino IDE Code Example

Example in Arduino IDE

Fill in your main Arduino IDE sketch file with the following code to use the KY-050 Ultrasonic Distance Sensor Module:

#define echoPin 7 // Echo input pin
#define triggerPin 8 // Trigger output pin

// Required variables are defined
int maximumRange = 300;
int minimumRange = 2;
long distance;
long duration;

void setup() {
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
Serial.println("KY-050 Distance measurement");
}

void loop() {
// Distance measurement is started using the 10us trigger signal
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);

// Now wait at the echo input until the signal has been activated
// and then the time is measured to see how long it remains activated
duration = pulseIn(echoPin, HIGH);

// Now the distance is calculated using the recorded time
distance = duration / 58.2;

// Check whether the measured value is within the permissible distance
if (distance >= maximumRange || distance <= minimumRange) {
// If not, an error message is displayed.
Serial.println("Distance outside the measuring range");
Serial.println("-----------------------------------");
}
else {
// The calculated distance is output in the serial output
Serial.print("The distance is: ");
Serial.print(distance);
Serial.println(" cm");
Serial.println("-----------------------------------");
}
// Pause between the individual measurements
delay(500);
}

This Arduino code sets up the KY-050 ultrasonic distance sensor by defining the echo and trigger pins. It initializes these pins and starts the serial communication. In the loop, the code sends a 10µs pulse to the trigger pin to initiate the measurement. It then measures the duration of the high signal on the echo pin, which corresponds to the time taken for the ultrasonic pulse to travel to the object and back. The distance is calculated by dividing the duration by 58.2 to convert the time into centimeters. If the measured distance is within the sensor's range (2 cm to 300 cm), it is displayed in the serial monitor. Otherwise, an error message is printed. The measurement is repeated every 500 ms.

Connect your ESP32 to your computer via a USB cable, Ensure the correct Board and Port are selected under Tools, Click the "Upload" button in the Arduino IDE to compile and upload the code to your ESP32.

ESP-IDF Image

ESP32 KY-050 ESP-IDF Code Example
Example in Espressif IoT Framework (ESP-IDF)

If you're using ESP-IDF to work with the KY-050 Ultrasonic Distance Sensor Module, here's how you can set it up and read data from the sensor. Fill in this code in the main ESP-IDF file:

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "esp_timer.h"

#define TRIGGER_PIN GPIO_NUM_5
#define ECHO_PIN GPIO_NUM_18

void measure_distance(void *pvParameter) {
while (1) {
gpio_set_level(TRIGGER_PIN, 1);
ets_delay_us(10);
gpio_set_level(TRIGGER_PIN, 0);

while (gpio_get_level(ECHO_PIN) == 0);
int64_t start_time = esp_timer_get_time();
while (gpio_get_level(ECHO_PIN) == 1);
int64_t end_time = esp_timer_get_time();

int64_t duration = end_time - start_time;
float distance = duration / 58.2;

if (distance >= 2 && distance <= 300) {
printf("Distance: %.2f cm\n", distance);
} else {
printf("Out of range\n");
}
vTaskDelay(pdMS_TO_TICKS(500));
}
}

void app_main() {
gpio_config_t io_conf = {
.mode = GPIO_MODE_OUTPUT,
.pin_bit_mask = (1ULL << TRIGGER_PIN)
};
gpio_config(&io_conf);
io_conf.mode = GPIO_MODE_INPUT;
io_conf.pin_bit_mask = (1ULL << ECHO_PIN);
gpio_config(&io_conf);

printf("KY-050 Ultrasonic Distance Sensor Test\n");
xTaskCreate(measure_distance, "measure_distance", 2048, NULL, 5, NULL);
}

This ESP-IDF code configures GPIO5 as an output (Trigger) and GPIO18 as an input (Echo) for the KY-050 ultrasonic sensor. It sends a 10µs pulse to trigger the sensor and then measures the time taken for the echo to return using esp_timer_get_time(). The distance is calculated by dividing the duration by 58.2. If the measured value is within the valid range (2 cm to 300 cm), it is printed to the console. Otherwise, an out-of-range message is displayed. Measurements are taken every 500 ms.

Update the I2C pins (I2C_MASTER_SDA_IO and I2C_MASTER_SCL_IO) to match your ESP32 hardware setup, Use idf.py build to compile the project, Use idf.py flash to upload the code to your ESP32.

ESPHome Image

ESP32 KY-050 ESPHome Code Example

Example in ESPHome (Home Assistant)

Fill in this configuration in your ESPHome YAML configuration file (example.yml) to integrate the KY-050 Ultrasonic Distance Sensor Module

sensor:
- platform: ultrasonic
trigger_pin: GPIO5
echo_pin: GPIO18
name: "KY-050 Distance Sensor"
update_interval: 0.5s

This ESPHome configuration sets up the KY-050 ultrasonic sensor with GPIO5 as the trigger pin and GPIO18 as the echo pin. It measures the distance and updates the value every 500 milliseconds.

Upload this code to your ESP32 using the ESPHome dashboard or the esphome run command.

PlatformIO Image

ESP32 KY-050 PlatformIO Code Example

Example in PlatformIO Framework

For PlatformIO, make sure to configure the platformio.ini file with the appropriate environment and libraries, and then proceed with the code.

Configure platformio.ini

First, your platformio.ini should look like below. You might need to include some libraries as shown. Make sure to change the board to your ESP32:

[env:esp32]
platform = espressif32
board = esp32dev
framework = arduino

ESP32 KY-050 PlatformIO Example Code

Write this code in your PlatformIO project under the src/main.cpp file to use the KY-050 Ultrasonic Distance Sensor Module:

#include <Arduino.h>

#define TRIGGER_PIN 5
#define ECHO_PIN 18

void setup() {
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
Serial.begin(115200);
Serial.println("KY-050 Ultrasonic Distance Sensor Test");
}

void loop() {
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);

long duration = pulseIn(ECHO_PIN, HIGH);
float distance = duration / 58.2;

if (distance >= 2 && distance <= 300) {
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
} else {
Serial.println("Out of range");
}
delay(500);
}

This PlatformIO code sets up GPIO5 as the trigger pin and GPIO18 as the echo pin for the KY-050 ultrasonic sensor. It sends a 10µs pulse, measures the echo time, and calculates the distance. If the measured value is within the valid range (2 cm to 300 cm), it is printed to the serial monitor. Otherwise, an out-of-range message is displayed. The loop repeats every 500 ms.

Upload the code to your ESP32 using the PlatformIO "Upload" button in your IDE or the pio run --target upload command.

MicroPython Image

ESP32 KY-050 MicroPython Code Example

Example in Micro Python Framework

Fill in this script in your MicroPython main.py file (main.py) to integrate the KY-050 Ultrasonic Distance Sensor Module with your ESP32.

import machine
import time

TRIGGER_PIN = machine.Pin(5, machine.Pin.OUT)
ECHO_PIN = machine.Pin(18, machine.Pin.IN)

def measure_distance():
TRIGGER_PIN.off()
time.sleep_us(2)
TRIGGER_PIN.on()
time.sleep_us(10)
TRIGGER_PIN.off()

while ECHO_PIN.value() == 0:
start_time = time.ticks_us()
while ECHO_PIN.value() == 1:
end_time = time.ticks_us()

duration = end_time - start_time
distance = duration / 58.2
return distance

while True:
dist = measure_distance()
if 2 <= dist <= 300:
print("Distance:", dist, "cm")
else:
print("Out of range")
time.sleep(0.5)

This MicroPython script configures GPIO5 as an output (Trigger) and GPIO18 as an input (Echo) for the KY-050 ultrasonic sensor. It sends a 10µs pulse to trigger the sensor, measures the echo duration, and calculates the distance. If the distance is within the valid range (2 cm to 300 cm), it prints the value; otherwise, an out-of-range message is displayed. The measurement is repeated every 500 milliseconds.

Upload this code to your ESP32 using a MicroPython-compatible IDE, such as Thonny, uPyCraft, or tools like ampy.

Conclusion

We went through technical specifications of KY-050 Ultrasonic Distance Sensor Module, its pinout, connection with ESP32 and KY-050 Ultrasonic Distance Sensor Module code examples with Arduino IDE, ESP-IDF, ESPHome and PlatformIO.