风筝
发表于: 2016-6-19 22:48:44 | 显示全部楼层

LED亮度渐变(Fade)

本示例展示了使用analogWrite() 来实现LED亮度的渐变。AnalogWrite采用脉冲宽度调制(PWM),以开关之间的不同比例快速打开和关闭一个数字引脚,来打造出渐变效果。


所需硬件

-    Arduino或者Genuino开发板

-    LED

-    220欧电阻

-    导线

-    实验电路板


电路连接方式

将LED的阳极(较长的正极管脚)通过一个220欧电阻连接到开发板的数字输出9脚。将阴极(较短的负极管脚)直接连接到地。

simplefade_bb.png


原理图

simplefade_pin9_schem.png


代码

在声明9脚作为ledPin之后,代码的Setup()函数就不需要做什么了。


代码主循环中的analogWrite()函数需要两个参数:一个是要函数说明操作哪个引脚,一个说明向PWM写多少值。


为了使LED的熄灭和点亮出现渐变的效果,需要逐渐将PWM值从0(一直熄灭)增加255(一直点亮),然后再回到0完成循环。在下面的模板例程中,PWM值使用brightness变量来设置。循环每执行一次,变量fadeAmount的值增加。


如果brightness值处于是在任一极端(0或255),则fadeAmount改变为它的符号。换句话说,如果fadeAmount是5,那么它会被设为-5。如果它是-5,那么它会被设为5。下个循环时,也会更改fadeAmount的符号。


analogWrite()可以非常快速的改变PWM值,因此在模板例程最后的延迟控制渐变的速度。试着改变延迟值,看看它是如何影响渐变效果的。

  1. /*
  2. Fade

  3. This example shows how to fade an LED on pin 9
  4. using the analogWrite() function.

  5. The analogWrite() function uses PWM, so if
  6. you want to change the pin you're using, be
  7. sure to use another PWM capable pin. On most
  8. Arduino, the PWM pins are identified with
  9. a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.

  10. This example code is in the public domain.
  11. */

  12. int led = 9;           // the PWM pin the LED is attached to
  13. int brightness = 0;    // how bright the LED is
  14. int fadeAmount = 5;    // how many points to fade the LED by

  15. // the setup routine runs once when you press reset:
  16. void setup() {
  17.   // declare pin 9 to be an output:
  18.   pinMode(led, OUTPUT);
  19. }

  20. // the loop routine runs over and over again forever:
  21. void loop() {
  22.   // set the brightness of pin 9:
  23.   analogWrite(led, brightness);

  24.   // change the brightness for next time through the loop:
  25.   brightness = brightness + fadeAmount;

  26.   // reverse the direction of the fading at the ends of the fade:
  27.   if (brightness == 0 || brightness == 255) {
  28.     fadeAmount = -fadeAmount ;
  29.   }
  30.   // wait for 30 milliseconds to see the dimming effect
  31.   delay(30);
  32. }
复制代码
跳转到指定楼层
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题 700 | 回复: 1483



手机版|

GMT+8, 2024-5-10 22:28 , Processed in 0.037500 second(s), 6 queries , Gzip On, MemCache On. Powered by Discuz! X3.5

YiBoard一板网 © 2015-2022 地址:河北省石家庄市长安区高营大街 ( 冀ICP备18020117号 )

快速回复 返回顶部 返回列表