Distance and tilt (HC-SR04, MPU6050)
9 min read
Two sensors appear in many projects. One measures how far away something is, and the other knows which way up it is.
Ultrasonic distance sensor
It works like a bat. It sends a burst of sound too high to hear, then times the echo.
- Send a 10 µs pulse on TRIG.
- Measure how long ECHO stays HIGH.
- Divide that time by 58 to get centimetres.
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
long us = pulseIn(ECHO, HIGH, 30000);
long cm = us / 58;Useful range is about 2 cm to 4 m. If nothing comes back, the time-out gives 0, so treat 0 as no reading. Soft cloth and steep angles give poor echoes.
This sensor runs on 5 V, so ECHO also gives 5 V. On an ESP32, use a 1 kΩ and 2 kΩ divider on ECHO to protect the pin. On a Nano it can connect directly.
Tilt and motion sensor (MPU6050)
This small board has an accelerometer, which feels gravity and movement, and a gyroscope, which measures turning. It talks over I2C using two wires.
- Nano: SDA goes to A4 and SCL goes to A5.
- ESP32: SDA goes to D21 and SCL goes to D22.
Its usual address is 0x68. Many parts can share these two wires, as long as each has its own address.
Getting clean values
- Keep the board still at start-up, so it can measure its zero.
- Fix the sensor firmly, because vibration looks like movement.
- Average a few readings to smooth them.
If nothing responds, run an I2C scanner sketch. It prints the address of every device it finds.
Quick quiz
1. An echo takes 580 µs. How far away is the object?
2. Why add a divider on ECHO with an ESP32?
3. How many signal wires does I2C use?