Arduino Interrupt-Based Pulse Measurement Missing Edges
DodaTech
Updated 2026-06-26
1 min read
In this tutorial, you'll learn about Arduino Interrupt. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Using interrupts to measure pulse width misses some edges.
Quick Fix
Wrong
volatile unsigned long start, width;
void isr() {
start = micros(); // Missing edge detection!
}
ISR only captures one edge โ cannot measure pulse width.
Right
volatile unsigned long riseTime = 0;
volatile unsigned long width = 0;
volatile byte state = 0;
void pulseISR() {
if (digitalRead(2) == HIGH) {
riseTime = micros(); // Rising edge
} else {
width = micros() - riseTime; // Falling edge
state = 1;
}
}
void setup() {
Serial.begin(9600);
pinMode(2, INPUT);
attachInterrupt(digitalPinToInterrupt(2), pulseISR, CHANGE);
}
void loop() {
if (state) {
state = 0;
Serial.print("Pulse width: ");
Serial.print(width);
Serial.println(" us");
}
}
Pulse width: 1500 us (measured by interrupt edge capture).
Prevention
Use CHANGE mode to capture both edges. In the ISR, check the current pin state to determine rising or falling. Use micros() for timestamps (volatile unsigned long). Process the measurement in loop(), not ISR. On AVR, keep ISRs under 10 ยตs.
DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.
FAQ
โ Previous
Arduino pulseIn Returns 0 Unexpectedly
Next โ
Arduino Generating a Pulse Does Not Produce Correct Width
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro