ESP32 KY-050 Ultrasonic Distance Sensor Module
Overview
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.
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.
Technical Specifications
Pinout Configuration
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.
Wiring with ESP32
VCC:
Connect to ESP325V
.GND:
Connect to ESP32GND
.Trig:
Connect to ESP32 digital output pin (e.g.,GPIO5
).Echo:
Connect to ESP32 digital input pin (e.g.,GPIO18
).
Troubleshooting Guide
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).
Debugging Tips
🔍 Serial Monitor
Use the Serial Monitor to check for error messages and verify the sensor's output. Add debug prints in your code to track the sensor's state.
⚡ Voltage Checks
Use a multimeter to verify voltage levels and check for continuity in your connections. Ensure the power supply is stable and within the sensor's requirements.
Additional Resources
Code Examples
Arduino Example
#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.
ESP-IDF Example
#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.
ESPHome Example
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.
PlatformIO Example
platformio.ini
[env:esp32]
platform = espressif32
board = esp32dev
framework = arduino
PlatformIO Example Code
#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.
MicroPython Example
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.
Conclusion
The ESP32 KY-050 Ultrasonic Distance Sensor Module is a powerful KY-0xx module sensor that offers excellent performance and reliability. With support for multiple development platforms including Arduino, ESP-IDF, ESPHome, PlatformIO, and MicroPython, it's a versatile choice for your IoT projects.
For optimal performance, ensure proper wiring and follow the recommended configuration for your chosen development platform.
Always verify power supply requirements and pin connections before powering up your project to avoid potential damage.