Try It Yourself / Exercise: Fix the Broken Sensor

Try It Yourself / Exercise: Fix the Broken Sensor

animation
sensors

Try It Yourself

Trace the signal and voltage limits before changing the code. Then test the fix with a known distance.

Exercise: Fix the Broken Sensor

Trace the broken sensor path and test one possible fault at a time.

Tip

Scenario: This ESP32 + HC-SR04 ultrasonic sensor code compiles but returns random garbage. Find and fix the mistake.

#define TRIG_PIN 5
#define ECHO_PIN 18

void setup() {
  Serial.begin(115200);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
}

void loop() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  long duration = pulseIn(ECHO_PIN, HIGH);
  float distance = duration * 0.034 / 2;

  Serial.println(distance);
  delay(100);
}

Hint: The code compiles and the logic looks correct, but readings are garbage. Check the HC-SR04 datasheet – what voltage does the ECHO pin output?

Problem: HC-SR04 ECHO pin outputs 5V logic, but ESP32 GPIO18 is only 3.3V tolerant. This overvoltage causes erratic readings and gradual damage.

Solution: Add a voltage divider on the ECHO pin:

Hardware fix:

  • HC-SR04 ECHO outputs 5V.
  • ESP32 GPIO18 accepts 3.3V max.
  • Add a divider: ECHO -> 1k R1 -> GPIO18 -> 2k R2 -> GND.
  • Approximate output: 5V * 2k / (1k + 2k) = 3.33V.
  • The code can stay the same after the signal is made safe.

Alternative fix: Use HC-SR04P (3.3V version) or add a bidirectional level shifter.

Back to the chapter