This sensor is used for distance measurement via ultrasound. If a signal (falling edge) is entered at the trigger input, a distance measurement is carried out and output as a PWM-TTL signal at the echo output.

Technical specifications

Measurable distance 2cm-300cm
Measurement resolution 3mm
min. time between measurements 50µs

principle of operation

This module shows how the distance to an object can be measured without contact using an ultrasonic loudspeaker and a microphone. The principle is based on the fact that the speed of sound in the air remains almost constant at constant temperature - at 20 ° C it is 343.2 m / s.

From this fact, the distance measurement can be converted into a time measurement, which can then easily be taken over by microcontrollers.

In the sensor module presented here, the ultrasonic loudspeaker sends eight 40KHz signals, which are then reflected by an object and picked up by the microphone. Ultrasound is used because it is outside the audible range of the human ear (roughly 20Hz-22,000Hz).

The transmission of the ultrasonic signal is started when a 10µs long start signal (ActiveHigh) is received at the "Trigger input pin". After transmission, the signal is activated at the "Echo output signal pin" (ActiveHigh). If the reflected signal is now picked up again at the microphone, the echo signal is deactivated again after the detection. The time between activation and deactivation of the echo signal can be measured and converted into the distance, as this also corresponds to the time how long the ultrasonic signal needed to overcome the distance between loudspeaker-> reflective wall -> microphone in the air. The conversion is then carried out by approximating a constant air speed - the distance is then half of the distance covered.

pin assignment

Code example Arduino

Pin assignment Arduino

Arduino Sensor
Pin 7 Echo
5V + V
Mass GND
Pin 8 Trigger

The example program activates the distance measurement according to the above principle and measures the time with the help of the Arduino function pulseIn how long the ultrasonic signal is in the air. This time is then used as the basis for converting the distance - the result is then output in the serial output. If the signal is outside the measuring range, a corresponding error message is issued.

#define Echo_EingangsPin 7 // Echo input pin
#define Trigger_AusgangsPin 8 // Trigger output pin
 
// Required variables are defined
int maximumRange = 300;
int minimumRange = 2;
long distance;
long duration;
 
void setup () {
 pinMode (Trigger_AusgangsPin, OUTPUT);
 pinMode (Echo_EingangsPin, INPUT);
 Serial.begin (9600);
}
 
void loop () {
 
 // Distance measurement is started by means of the 10us long trigger signal
 digitalWrite (Trigger_AusgangsPin, HIGH);
 delayMicroseconds (10);
 digitalWrite (Trigger_AusgangsPin, LOW);
  
 // Now we wait at the echo input until the signal has been activated
 // and then the time measured how long it remains activated
 Duration = pulseIn (Echo_EingangsPin, 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 output.
      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);
}

Sample program download

KY050-Arduino.zip

Code example Raspberry Pi

Pin assignment Raspberry Pi

Raspberry Pi Sensor
5V [pin 2] + V
Ground [pin 6] GND
Sensor KY-051
Trigger B1
Echo B2
Raspberry Pi KY-051
3.3V [pin 1] Vcca
5V [pin 2] Vccb
Ground [pin 6] GND
Raspberry Pi KY-051
GPIO 17 [pin 11] A1
Gpio 27 [pin 13] A2

Programming example in the Python programming language

5V voltage level, therefore the following must be observed

The Raspberry Pi works with its ARM processor core, unlike the Atmel Atmega-based Arduino, with a 3.3V voltage level instead of 5V - this sensor only works with the higher voltage level. If you were to operate the sensor on the Raspberry Pi without any restrictions, this could cause permanent damage to the inputs of the Raspberry Pi.

For such cases, this sensor kit set has a voltage translator with the KY-051, which adjusts the voltage level and thus ensures safe operation. With this sensor, this must be connected between the Rasperry Pi and the sensor.

For more information, see the information page for KY-051 .

The example program activates the distance measurement according to the above principle and uses a kind of stopwatch to measure the time how long the ultrasonic signal is in the air. This stop watch is implemented by reading the current system time from time.time () when the echo signal is switched over; the difference between the switch-on time and the switch-off time is the time sought and how long the signal is traveling. This time is then used as the basis for converting the distance - the result is then output in the cosnole. If the signal is outside the measuring range, a corresponding error message is issued.

# coding = utf-8
# Required modules are inserted and configured
import time
import RPi.GPIO as GPIO
GPIO.setmode (GPIO.BCM)
 
# The respective input / output pins can be selected here
Trigger_AusgangsPin = 17
Echo_EingangsPin = 27
 
# The pause between the individual measurements can be set here in seconds
sleeptime = 0.8
 
# The input / output pins are configured here
GPIO.setup (Trigger_AusgangsPin, GPIO.OUT)
GPIO.setup (Echo_EingangsPin, GPIO.IN)
GPIO.output (Trigger_AusgangsPin, False)
 
# Main program loop
try:
    while True:
        # Distance measurement is started by means of the 10us long trigger signal
        GPIO.output (Trigger_AusgangsPin, True)
        time.sleep (0.00001)
        GPIO.output (Trigger_AusgangsPin, False)
 
        # The stopwatch is started here
        Switch-on time = time.time ()
        while GPIO.input (Echo_EingangsPin) == 0:
            Switch-on time = time.time () # The current time is saved until the signal is activated
 
        while GPIO.input (Echo_EingangsPin) == 1:
            Switch-off time = time.time () # The last time when the signal was active is recorded
 
        # The difference between the two times gives the duration you are looking for
        Duration = switch-off time - switch-on time
        # This can now be used to calculate the distance based on the speed of sound
        Distance = (duration * 34300) / 2
 
        # Check whether the measured value is within the permissible distance
        if distance <2 or (round (distance)> 300):
            # If not, an error message is issued
            print ("distance outside the measuring range")
            print ("------------------------------")
        else:
            # The space is formatted to two places behind the comma
            Distance = format ((duration * 34300) / 2, '.2f')
            # The calculated distance is output on the console
            print ("The distance is:"), distance, ("cm")
            print ("------------------------------")
 
        # Pause between the individual measurements
        time.sleep (sleeptime)
 
# Clean up after the program has ended
except KeyboardInterrupt:
    GPIO.cleanup ()

Sample program download

KY050-RPi.zip

To start with the command:

sudo python3 KY050.py

Code example Micro: Bit

Pin assignment Micro: Bit:

Micro: bit Sensor
3V + V
Ground [External and Micro: Bit] GND
Sensor KY-051
Trigger B1
Echo B2
Micro: bit KY-051
3V Vcca
5V [Ext.] Vccb
Ground [External and Micro: Bit] GND
Micro: bit KY-051
Pin 2 A1
Pin 1 A2

This is a MakeCode example for Micro: Bit which essentially does the same as the examples of the other two variants. However, this example is closer to the example of the Raspberry Pi than the example of the Arduino.

An additional library is required for the following code example:

pxt-sonar by Microsoft | published under the MIT License

You have to add this library to your IDE before using the code.

You do this by going to Extensions in your IDE and looking for the library with the following URL https: //github.com/microsoft/pxt-sonar.git and then adding it.

Sample program download

microbit-KY-050.zip