课程表

Arduino 基础

Arduino 函数库

Arduino 进阶

Arduino 项目

Arduino 传感器

Arduino 电机控制

Arduino 声音

工具箱
速查手册

Arduino LED条形图

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

此示例显示如何读取模拟引脚0处的模拟输入,将值从analogRead()转换为电压,并将其输出到Arduino软件(IDE)的串行监视器。

 

必需的组件

您将需要以下组件 -

  • 1 × Breadboard 面包板
  • 1 × Arduino Uno R3
  • 1 × 5k ohm variable resistor (potentiometer) 5k欧姆可变电阻器(电位器)
  • 2 × Jumper 跳线
  • 8 × LED(LED条形图显示如下图所示)
 

程序

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

 

连接面包板
 

 

电路图

 

草图

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

 

Sketch

 

10段LED条形图

LED条形图

 

这些10段条形图LED有许多用途。 具有紧凑的占地面积,简单的连接,它们易于原型或成品。 基本上,它们是容纳在一起的10个单独的蓝色LED,每个具有单独的阳极和阴极连接。

它们也有黄色,红色和绿色的颜色。

注意 - 这些条形图上的引脚可能与数据表中列出的内容不同。 将装置旋转180度将校正变化,使得销11成为第一销。

 

Arduino代码

  1. /*
  2. LED bar graph
  3. Turns on a series of LEDs based on the value of an analog sensor.
  4. This is a simple way to make a bar graph display.
  5. Though this graph uses 8LEDs, you can use any number by
  6. changing the LED count and the pins in the array.
  7. This method can be used to control any series of digital
  8. outputs that depends on an analog input.
  9. */
  10.  
  11. // these constants won't change:
  12. const int analogPin = A0; // the pin that the potentiometer is attached to
  13. const int ledCount = 8; // the number of LEDs in the bar graph
  14. int ledPins[] = {2, 3, 4, 5, 6, 7, 8, 9}; // an array of pin numbers to which LEDs are attached
  15.  
  16. void setup() {
  17. // loop over the pin array and set them all to output:
  18. for (int thisLed = 0; thisLed < ledCount; thisLed++) {
  19. pinMode(ledPins[thisLed], OUTPUT);
  20. }
  21. }
  22.  
  23. void loop() {
  24. // read the potentiometer:
  25. int sensorReading = analogRead(analogPin);
  26. // map the result to a range from 0 to the number of LEDs:
  27. int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);
  28. // loop over the LED array:
  29. for (int thisLed = 0; thisLed < ledCount; thisLed++) {
  30. // if the array element's index is less than ledLevel,
  31. // turn the pin for this element on:
  32. if (thisLed < ledLevel) {
  33. digitalWrite(ledPins[thisLed], HIGH);
  34. }else { // turn off all pins higher than the ledLevel:
  35. digitalWrite(ledPins[thisLed], LOW);
  36. }
  37. }
  38. }

 

代码说明

草图的工作方式如下:首先,您阅读输入。 将输入值映射到输出范围,在这种情况下为十个LED。 然后,您设置一个 for-loop 以迭代输出。 如果系列中的输出数量低于映射的输入范围,则将其打开。 如果没有,你把它关闭。

 

结果

当模拟读数的值增加时,您将看到LED逐个打开,而当读数减少时,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号