Distance meter with an ultrasonic sensorTinkerPieCircuit tutorial 18 of 24 · Intermediate · 20 minutes
Measure distance with an HC-SR04 ultrasonic sensor and show it as a bar on the LED matrix.
Open this circuit in TinkerPieCircuit (free, runs in your browser)
What you will learn
- How an ultrasonic sensor measures distance with sound
- Reading centimetres with readDistance()
- Using a for loop to draw a bar graph
Parts
Steps
Wire the sensor
VCC to
5V, GND toGND, TRIG toP10, ECHO toP11.Read the distance
readDistance(P10, P11)sends a sound pulse and returns the distance in cm.Draw a bar
Closer objects light more columns of the on-board LED matrix. A for loop turns the columns on.
Move the object
Press ▶ Start and drag the slider on the sensor. Below 15 cm the buzzer beeps.
The code
function loop() {
const cm = readDistance(P10, P11);
Serial.println("distance = " + cm + " cm");
matrixClear();
const cols = constrain(Math.round(map(cm, 5, 100, 6, 0)), 0, 6);
for (let x = 0; x < cols; x++) {
for (let y = 0; y < 5; y++) {
matrixSet(x, y, 'cyan');
}
}
if (cm < 15) {
tone(BUZZER, 880);
} else {
noTone(BUZZER);
}
delay(100);
}
Copy this into the Code tab. It is Arduino-style JavaScript. The real board uses the same pin names (S1, P10…) in TinkerPie Studio.
How it works
The sensor sends a burst of sound and times the echo. Sound travels about 29 µs per centimetre, so distance = time ÷ 58 (there and back). In the simulator readDistance() does that for you. On a real HC-SR04 the ECHO pin gives 5 V, so use a voltage divider on a 3.3 V board.
← Dot game on the LED matrix · All 24 circuit tutorials · Car parking sensor →