课程表

Arduino 基础

Arduino 函数库

Arduino 进阶

Arduino 项目

Arduino 传感器

Arduino 电机控制

Arduino 声音

工具箱
速查手册

Arduino 熄灭的LED

当前位置:免费教程 » 程序设计 » Arduino

这个例子演示了在熄灭LED时使用analogWrite()函数。 AnalogWrite使用脉冲宽度调制(PWM),以非常快速地打开和关闭数字引脚,开/关之间具有不同的比率,以创建衰减效果。

必需的组件

您将需要以下组件 - 

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

程序

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

 

电路图

注意 − 要了解LED的极性,请仔细查看。 两个腿中较短的,朝向灯泡的平边缘指示负端子。

LED

 

像电阻器这样的组件需要将其端子弯曲成90°角,以便正确安装面包板插座。 您也可以将端子切短。

 

电阻

草图

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

 

Sketch

Arduino代码

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

 

代码说明

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

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

如果亮度在其值的任一极值(0或255),则fadeAmount变为其负值。换句话说,如果fadeAmount是5,那么它被设置为-5。如果它是-5,那么它被设置为5.下一次通过循环,这个改变也导致亮度改变方向。

analogWrite()可以非常快速地改变PWM值,因此草图结束时的延迟控制淡入淡出的速度。尝试改变延迟的值,看看它如何改变衰落效果。

 

结果

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

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号