目录

Arduino - LED条形图( LED Bar Graph)

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

组件的要求 (Components Required)

您将需要以下组件 -

  • 1 × Breadboard
  • 1×Arduino Uno R3
  • 1×5k欧姆可变电阻(电位器)
  • 2 × Jumper
  • 8×LED或您可以使用(LED条形图显示如下图所示)

过程 (Procedure)

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

酒吧面包板

连接到酒吧面包板

草图 (Sketch)

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

草图

10段LED条形图

LED条形图

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

它们还有黄色,红色和绿色可供选择。

Note - 这些条形图上的引脚可能与数据表中列出的不同。 将设备旋转180度将纠正更改,使引脚11成为第一个引脚。

Arduino代码 (Arduino Code)

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

Code to Note

草图的工作方式如下:首先,您阅读输入。 将输入值映射到输出范围,在本例中为10个LED。 然后设置for-loop以迭代输出。 如果系列中的输出数字低于映射的输入范围,则将其打开。 如果没有,请将其关闭。

结果 (Result)

当模拟读数值增加时,您会看到LED逐一亮起,当读数减小时,LED逐一关闭。

↑回到顶部↑
WIKI教程 @2018