显示部分-灯条

它由一连串的LED组成,用像电位器一样的模拟输出实现。你也可以用10位LED数码管来实现。这个示例展示了如何控制一连串的LED。

硬件需求

Arduino板子

LED灯条或者10位条形数码管

电位器

10个220欧电阻

连接线

面包板

电路

原理图

代码<

// 常量是不会改变的
const int analogPin = A0;   // 定义电位器引脚
const int ledCount = 10;    // 定义LED的数量

int ledPins[] = {
2, 3, 4, 5, 6, 7, 8, 9, 10, 11
};   // 批量定义LED引脚


void setup() {
// 用循环的语法设置所有引脚为输出
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
pinMode(ledPins[thisLed], OUTPUT);
}
}

void loop() {
// 读取电位器
int sensorReading = analogRead(analogPin);
// 用map函数映射电位器范围和LED数量:
int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);

// 设置LED的循环
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
// 如果数组元素的索引值小于LED层次,
// 就点亮这层的LED:
if (thisLed < ledLevel) {
digitalWrite(ledPins[thisLed], HIGH);
}
// 如果数组元素的索引值大于LED层次,就设置为关闭状态。:
else {
digitalWrite(ledPins[thisLed], LOW);
}
}
} 
0
分享到:

评论0

请先

本站资料配套硬件销售店铺:天猫店ultirobot.tmall.com 、三冠淘宝店zhongbest.taobao.com
没有账号? 忘记密码?