极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 9500|回复: 3

关于可调试灯光程序的问题

[复制链接]
发表于 2015-3-31 14:04:42 | 显示全部楼层 |阅读模式
const int analogPin = A0;  
const int ledCount = 10;

int ledPins[] = {
  2, 3, 4, 5, 6, 7,8,9,10,11 };  


void setup() {
  Serial.begin(9600);
  for (int thisLed = 0; thisLed < ledCount; thisLed++) {
    pinMode(ledPins[thisLed], OUTPUT);
  }
}

void loop() {
  int sensorReading = analogRead(analogPin);
  int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);

  for (int thisLed = 0; thisLed < ledCount; thisLed++) {
    if (thisLed < ledLevel) {
      digitalWrite(ledPins[thisLed], HIGH);
      Serial.println(sensorReading);
    }
    else {
      digitalWrite(ledPins[thisLed], LOW);
    }
  }
}
-------------------------------------------------------------------------------------------------------------------------------------------------------
以上语句及变量在该程序中的具体含义,求解
——————————————————————————————-
以上程序仅仅只是通过改变电流大小来控制各个小灯的简单程序,但本人有几处地方不是太明确,求助
回复

使用道具 举报

 楼主| 发表于 2015-3-31 14:06:00 | 显示全部楼层
const int analogPin = A0;   // the pin that the potentiometer is attached to
const int ledCount = 10;   // the number of LEDs in the bar graph

int ledPins[] = {
  2, 3, 4, 5, 6, 7,8,9,10,11 };   // an array of pin numbers to which LEDs are attached


void setup() {
  Serial.begin(9600);
  // 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);
      Serial.println(sensorReading);
    }
    // turn off all pins higher than the ledLevel:
    else {
      digitalWrite(ledPins[thisLed], LOW);
    }
  }
}

回复 支持 反对

使用道具 举报

发表于 2015-3-31 18:53:23 | 显示全部楼层
ledCount表示所用的led有幾顆,與後面的ledPins[]數量對應

map(sensorReading, 0, 1023, 0, ledCount)這句是等比例縮放sensorReading
analogRead()的範圍0~1023,要轉換成0~ledCount,也就是0~10
回复 支持 反对

使用道具 举报

 楼主| 发表于 2015-4-1 13:18:12 | 显示全部楼层
非常感谢,懂了,谢谢帮忙{:soso_e179:}{:soso_e100:}
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|联系我们|极客工坊

GMT+8, 2026-6-8 14:38 , Processed in 0.036183 second(s), 18 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表