Arduino 简明教程
Arduino - LED Bar Graph
此示例向您展示如何读取模拟针脚 0 上的模拟输入,将 analogRead() 中的值转换成电压,并将其打印到 Arduino 软件 (IDE) 的串口监视器中。
Components Required
您将需要以下组件:
-
1 × Breadboard
-
1 × Arduino Uno R3
-
1 × 5k 欧姆可变电阻器(电位计)
-
2 × Jumper
-
8 × LED 或您可以使用(如以下图像中所示的 LED 条形图显示器)
10 Segment LED Bar Graph
这些 10 段条形图 LED 有多种用途。它们占用空间小、连接简单,无论是用于原型设计还是成品都很容易使用。从本质上说,它们是 10 个单独的蓝色 LED 组合在一起,每个 LED 都具有一个单独的阳极和阴极连接。
它们还有黄色、红色和绿色。
Note − 这些条形图上的引脚分配可能与数据表上列出的不同。将设备旋转 180 度将更正更改,使引脚 11 成为第一引脚。
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);
}
}
}