Arduino pulseIn Returns 0 Unexpectedly
DodaTech
Updated 2026-06-26
1 min read
In this tutorial, you'll learn about Arduino pulseIn Returns 0 Unexpectedly. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
pulseIn() returns 0 even though a pulse is present on the pin.
Quick Fix
Wrong
unsigned long duration = pulseIn(7, HIGH); // Returns 0 if no pulse within 1 sec
duration = 0 even with a valid pulse.
Right
int sensorPin = 7;
void setup() {
Serial.begin(9600);
pinMode(sensorPin, INPUT);
}
void loop() {
unsigned long duration = pulseIn(sensorPin, HIGH, 5000000); // 5 sec timeout
if (duration > 0) {
float distance = duration / 58.0; // HC-SR04 ultrasonic
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
} else {
Serial.println("Pulse timeout");
}
delay(100);
}
Distance: 10.34 cm (or "Pulse timeout" if no echo).
Prevention
pulseIn() has a default 1-second timeout. Set a custom timeout (in microseconds) as the third argument. Ensure the pin mode is INPUT (not INPUT_PULLUP). pulseIn() blocks until the pulse starts or timeout. For non-blocking operation, use interrupts or hardware timer capture.
DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.
FAQ
← Previous
Arduino millis() Overflow Causes Timing Failure
Next →
Arduino Interrupt-Based Pulse Measurement Missing Edges
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro