Skip to main content

Ultrasonic Distance Sensor

The HC-SR04 measures distances using ultrasound and outputs them in centimeters (cm).

Ultrasonic distance HC-SR04

Technical Information

  • Dimensions: 45mm x 20mm x 17mm
  • Supply voltage of 5V with a current consumption of less than 2mA
  • Up to 50 measurements per second possible

Ultrasonic sensor setup

Programming (Arduino)

Code

This code outputs the measured distance in centimeters to the Serial Monitor.

int trig = 1;  // Trig pin of the sensor is connected to pin 1.
int echo = 2; // Echo pin of the sensor is connected to pin 2.

// Define variables
unsigned int time = 0;
unsigned int distance = 0;

void setup() {
Serial.begin(9600); // Starts the Serial Monitor
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
}

void loop() {
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
distance = time / 58;
Serial.println(distance);
}

Programming (Blockly)

In Blockly, the sensor can be read using the following block:

Select the port to which you have connected the sensor from the dropdown menu. The trigger and echo pins will then be automatically adjusted.