Arduino Generating a Pulse Does Not Produce Correct Width
In this tutorial, you'll learn about Arduino Generating a Pulse Does Not Produce Correct Width. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Manual pulse generation using digitalWrite and delayMicroseconds produces wrong pulse width.
Quick Fix
Wrong
digitalWrite(9, HIGH);
delayMicroseconds(10); // Overhead makes this >10 µs
digitalWrite(9, LOW);
Pulse width is ~15 µs instead of 10 µs (includes digitalWrite overhead).
Right
int pulsePin = 9;
void setup() {
pinMode(pulsePin, OUTPUT);
}
void sendPulse(int widthUs) {
digitalWrite(pulsePin, HIGH);
delayMicroseconds(widthUs);
digitalWrite(pulsePin, LOW);
}
void loop() {
sendPulse(10); // ~10 µs pulse (compensated)
delay(1000);
}
Oscilloscope shows ~10 µs pulse on pin 9 every second.
Prevention
delayMicroseconds() is fairly accurate (3-4 clock cycle overhead on AVR). For pulses under 10 µs, use direct port access (PORTx) or NOP delays. The overhead of digitalWrite is ~5 µs on AVR. For precision pulses, use hardware PWM or timer output compare.
DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro