使用 Arduino Uno 生成短脉冲 第 2 部分:GPIO 寄存器访问脉冲宽度
当你使用以下代码在 Arduino Uno 上生成数字脉冲(cli() 和 sei() 用于禁用和启用中断以确保一致的脉冲宽度)时,你可以生成最短的脉冲,受 Atmega328p 的 16MHz 时钟频率限制:
gpio_pulse.ino
#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
}基于 ATMega328p 的 16 MHz 时钟频率,这生成几乎正好 125ns 长度的脉冲。这相当于 16 MHz 主时钟的两个时钟周期。

完整示例
full_example.ino
#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);
}Check out similar posts by category:
Arduino, Electronics
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow