ArduinoArduino UnoExact chip

Distance (HC-SR04)

An ultrasonic echo timed with pulseIn(). Set the distance in the inspector.

Distance (HC-SR04) in Argynix Lab

The code

sketch.inoC++
// HC-SR04: a 10 µs pulse on TRIG, then ECHO stays HIGH for the sound's round trip.
// 58 µs of echo is one centimetre. Select the sensor to set the distance.

const int TRIG = 3;
const int ECHO = 2;

void setup() {
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);
  long echo = pulseIn(ECHO, HIGH, 30000);
  Serial.print("distance:");
  Serial.println(echo / 58.2, 1);
  delay(200);
}