目录

Arduino - 褪色LED( Fading LED)

此示例演示了如何使用analogWrite()函数淡化LED。 AnalogWrite使用脉冲宽度调制(PWM),在打开和关闭之间以不同的比率非常快速地打开和关闭数字引脚,以产生衰落效果。

组件的要求 (Components Required)

您将需要以下组件 -

  • 1 × Breadboard
  • 1×Arduino Uno R3
  • 1×LED
  • 1×330Ω电阻器
  • 2 × Jumper

过程 (Procedure)

按照电路图并连接面包板上的组件,如下图所示。

面包板上的组件

Note - 要找出LED的极性,请仔细查看。 两个腿中较短的一个朝向灯泡的平坦边缘指示负端子。

LED

像电阻器这样的元件需要将它们的端子弯成90°角,以便正确地安装面包板插座。 您也可以缩短端子。

电阻器

草图 (Sketch)

在您的计算机上打开Arduino IDE软件。 用Arduino语言编码将控制你的电路。 单击“新建”打开新草图文件。

草图

Arduino代码 (Arduino Code)

/*
   Fade
   This example shows how to fade an LED on pin 9 using the analogWrite() function.
   The analogWrite() function uses PWM, so if you want to change the pin you're using, be
   sure to use another PWM capable pin. On most Arduino, the PWM pins are identified with
   a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.
*/
int led = 9; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
// the setup routine runs once when you press reset:
void setup() {
   // declare pin 9 to be an output:
   pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
   // set the brightness of pin 9:
   analogWrite(led, brightness);
   // change the brightness for next time through the loop:
   brightness = brightness + fadeAmount;
   // reverse the direction of the fading at the ends of the fade:
   if (brightness == 0 || brightness == 255) {
      fadeAmount = -fadeAmount ;
   }
   // wait for 30 milliseconds to see the dimming effect
   delay(300);
}

Code to Note

在将引脚9声明为LED引脚后,代码的setup()函数无关。 您将在代码的主循环中使用的analogWrite()函数需要两个参数:一,告诉函数写入哪个引脚,另一个指示要写入的PWM值。

为了关闭和打开LED,逐渐将PWM值从0(一直关闭)增加到255(一直开启),然后再回到0,以完成循环。 在上面给出的草图中,使用称为亮度的变量设置PWM值。 每次循环时,它都会增加变量fadeAmount的值。

如果亮度处于其值的任一极端(0或255),则fadeAmount将更改为负值。 换句话说,如果fadeAmount为5,则将其设置为-5。 如果是-5,则将其设置为5.下一次循环时,此更改也会导致亮度改变方向。

analogWrite()可以非常快速地改变PWM值,因此草图末尾的延迟控制着衰落的速度。 尝试更改延迟的值,看看它如何改变衰落效果。

结果 (Result)

您应该看到LED亮度逐渐变化。

↑回到顶部↑
WIKI教程 @2018