Arduino NewPing Ultrasonic Sensor: Wiring, Code and Simulator

To build this Arduino NewPing Ultrasonic Sensor project you need an Arduino Uno and an HC-SR04 ultrasonic sensor. The NewPing library measures distance with an HC-SR04. Make the 4 connections in the wiring table, upload the Arduino C++ code, and change the distance on the sensor while it runs.

Open this circuit in the free Arduino Uno simulator

Parts list

QtyPartWhat it does
1Arduino Unothe microcontroller board
1HC-SR04 ultrasonic sensorA 10 µs pulse on TRIG, then pulseIn(ECHO, HIGH): 58 µs per cm. VCC to 5V, GND to GND.

Wiring

#FromTo
1Arduino Uno 5VHC-SR04 ultrasonic sensor VCC
2Arduino Uno GNDHC-SR04 ultrasonic sensor GND
3Arduino Uno pin 9HC-SR04 ultrasonic sensor TRIG
4Arduino Uno pin 10HC-SR04 ultrasonic sensor ECHO

Step by step

  1. Open the simulator. Open the BitForBytes Embedded Lab in your browser and start from the Arduino Uno. No install or account is needed.
  2. Add the parts. Add an HC-SR04 ultrasonic sensor from the parts palette.
  3. Wire 1. Connect Arduino Uno 5V to HC-SR04 ultrasonic sensor VCC.
  4. Wire 2. Connect Arduino Uno GND to HC-SR04 ultrasonic sensor GND.
  5. Wire 3. Connect Arduino Uno pin 9 to HC-SR04 ultrasonic sensor TRIG.
  6. Wire 4. Connect Arduino Uno pin 10 to HC-SR04 ultrasonic sensor ECHO.
  7. Paste the Arduino C++ code. Paste the Arduino C++ code below into the code editor.
  8. Run it. Press Run. Change the distance on the sensor while it runs.

Arduino C++ code

// NewPing: distance from an HC-SR04 (TRIG 9, ECHO 10) in centimetres.
#include <NewPing.h>

NewPing sonar(9, 10, 300);

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.print("Distance: ");
  Serial.print(sonar.ping_cm());
  Serial.println(" cm");
  delay(200);
}

What to try

Change the distance on the sensor while it runs.

Frequently asked questions

How do I wire the NewPing Ultrasonic Sensor project on an Arduino Uno?

Make 4 connections: Arduino Uno 5V to HC-SR04 ultrasonic sensor VCC; Arduino Uno GND to HC-SR04 ultrasonic sensor GND; Arduino Uno pin 9 to HC-SR04 ultrasonic sensor TRIG; Arduino Uno pin 10 to HC-SR04 ultrasonic sensor ECHO.

What parts do I need for this Arduino project?

An Arduino Uno and an HC-SR04 ultrasonic sensor.

Can I simulate this Arduino project online for free?

Yes. The BitForBytes Embedded Lab runs this exact circuit and Arduino C++ code in your browser for free, with no install and no hardware. The sketch is compiled with the real Arduino toolchain and runs on an emulated ATmega328P.

What does the code do?

The NewPing library measures distance with an HC-SR04.

More Arduino Uno projects