Arduino - LED 亮度变化

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

需要的组件

你将需要以下组件 -

  • 1×面包板
  • 1×Arduino Uno R3
  • 1×LED
  • 1×330Ω 电阻器
  • 2×跳线

程序

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

面包板上的组件

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

LED

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

电阻器

草图

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

草图

Arduino 代码

/*
   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);
}

代码注意

在将引脚 9 声明为 LED 引脚后,setup() 函数就没有任何其他作用了。你将在代码的主循环中使用的 analogWrite() 函数需要两个参数:1,告诉函数写入哪个引脚,2,指示出要写入的 PWM 值。

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

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

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

结果

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