Short pulse generation with Arduino Uno Part 2: GPIO register access pulse width
When you use the following code to generate digital pulses with the Arduino Uno (cli()
and sei()
and to disable and enalbe interrupts in order to ensure consistent pulse width), you can generate the shortest possible pulses, limited by the Atmega328p’s 16MHz clock frequency:
#define PORT11 PORTB
#define PIN11 3
#define PIN11_MASK (1 << PIN11)
void loop() {
cli(); // Disable interrupts
PORT11 |= PIN11_MASK; // Turn pin 11 on
PORT11 &= ~PIN11_MASK; // Turn pin 11 off
sei(); // Enable interrupts again
delay(10); // Wait 10ms
}
Based on the 16 MHz clock frequency of the ATMega328p, this generates pulses exactly almost exactly 125ns
in lengh. This is equivalent to two clock cycles of the 16 MHz
master clock.
Full example
#include <Arduino.h>
#include <avr/io.h>
#define PORT11 PORTB
#define PIN11 3
#define PIN11_MASK (1 << PIN11)
void setup() {
pinMode(11, OUTPUT);
}
void loop() {
cli();
PORT11 |= PIN11_MASK;
PORT11 &= ~PIN11_MASK;
sei();
delay(10);
}