Ultrasonic distance on pins 12 and 11, on an Arduino Uno
An HC-SR04 with TRIG on pin 12 and ECHO on pin 11: the SR04 library times the echo and prints the distance in centimeters once a second. The whole build, an Arduino Uno and 1 more part, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Beginner Runs in your browser. Free, and no account needed.
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// Ultrasonic distance: an HC-SR04 with TRIG on pin 12 and ECHO on pin 11.
//
// HC-SR04 VCC -> 5V HC-SR04 TRIG -> pin 12
// HC-SR04 ECHO -> pin 11 HC-SR04 GND -> GND
//
// The sensor sends eight pulses of 40 kHz sound when TRIG goes high for 10
// microseconds, then holds ECHO high until the sound comes back. Sound travels
// about 343 meters a second, so every 58 microseconds of echo is one
// centimeter there and back. The SR04 library does the timing and the sum.
//
// Note the order in the constructor: echo first, then trigger.
//
// Drag the slider on the sensor to move the obstacle nearer or farther.
#include "SR04.h"
const int TRIG_PIN = 12;
const int ECHO_PIN = 11;
SR04 sonar = SR04(ECHO_PIN, TRIG_PIN);
void setup() {
Serial.begin(9600);
Serial.println("Mokxi Uno: HC-SR04 on pins 12 (TRIG) and 11 (ECHO)");
}
void loop() {
long cm = sonar.Distance();
if (cm == 0) {
Serial.println("nothing in range");
} else {
Serial.print(cm);
Serial.println(" cm");
}
delay(1000);
}
Parts list
3 parts, plus the jumper wires. Every one is in the editor's parts bin.
- 1 × Arduino Uno R3
- 1 × Half breadboard
- 1 × Ultrasonic ranger
How it is wired
4 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- Ground: Arduino Uno R3 pin GND; Ultrasonic ranger pin GND
- Arduino Uno R3 pin 12; Ultrasonic ranger pin TRIG
- Arduino Uno R3 pin 11; Ultrasonic ranger pin ECHO
- Arduino Uno R3 pin 5V; Ultrasonic ranger pin VCC
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.