如何用analogWrite同步点亮四个LED灯

How to synchronously illuminate four LED lights with analogWrite

我正在使用 Arduino Uno 并想使用模拟写入方法同步点亮四个 LED,但它们是顺序点亮的。这是我的代码:

int brightness = 0;    
int fadeAmount = 5;    
boolean first = true;

void setup()  { 
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
} 
void loop()  {

  if (first) {
    // these should iluminate synchronously
    analogWrite(2, brightness);
    analogWrite(3, brightness);
    analogWrite(4, brightness);
    analogWrite(5, brightness);
  } else {
    // these should iluminate synchronously
    analogWrite(6, brightness);
    analogWrite(7, brightness);
    analogWrite(8, brightness);
    analogWrite(9, brightness);
  }

  brightness = brightness + fadeAmount;

  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;
    if (brightness == 0) {
      reverseFirst();
    }
  }           

  delay(5);                            
}

void reverseFirst(){
  if (first) {
    first = false;
  } else {
    first = true;
  }
}

analogWrite 仅在引脚 3、5、6、9、10、11 上有效,因为它们是 PWM 引脚。根据 analogWrite 源代码,所有其他引脚如果与 analogWrite 一起使用,将默认返回到 digitalWrite。

所以我怀疑您将无法对其他引脚进行适当的模拟控制,这可能就是为什么并非所有引脚都同时打开的原因。

如果亮度对您很重要,那么我建议您只使用真正的 PWM 引脚。如果您需要超过六个引脚,那么您可以获得模拟扩展器芯片,或者更简单的是,您可以查看 "ShiftPWM" 之类的东西。它是一个使用移位寄存器将脉冲有效地移位到其输出的库,允许您控制 LED 的亮度。请记住,它不再被维护。