Unit B · Things that move, things that show
What we are making: a distance meter. Point it at a wall, walk backwards, and watch the number climb.
The HC-SR04 has two openings. One is a tiny loudspeaker, the other a tiny microphone. The board shouts — at a pitch far too high for you to hear — and then counts how long the echo takes to come back.
Sound travels about 340 metres a second, which works out at roughly 58 microseconds per centimetre there and back. So the program divides the echo time by 58 and gets centimetres. That is the whole trick, and it is why the number 58 is in your code.
"TOO CLOSE" when cm is under 10.| What you see | Why | What to do |
|---|---|---|
| Always reads 0 | Trig and Echo are swapped. | Trig to 9, Echo to 10. This is the answer nine times out of ten. |
| Wild numbers that jump about | Nothing in range, or a soft surface. | Point it squarely at a wall to check the sensor itself is fine. |
| Reads once, then freezes | pulseIn is waiting for an echo. | Move something into range and it recovers on its own. |
| Works on a wall, not on a person | Clothing absorbs the sound. | A real limitation, not a fault. Design around it. |
In this session