Klack 发表于 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, 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, HIGH);
      Serial.println(sensorReading);
    }
    else {
      digitalWrite(ledPins, LOW);
    }
}
}
-------------------------------------------------------------------------------------------------------------------------------------------------------
以上语句及变量在该程序中的具体含义,求解
——————————————————————————————-
以上程序仅仅只是通过改变电流大小来控制各个小灯的简单程序,但本人有几处地方不是太明确,求助

Klack 发表于 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, 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, HIGH);
      Serial.println(sensorReading);
    }
    // turn off all pins higher than the ledLevel:
    else {
      digitalWrite(ledPins, LOW);
    }
}
}

Be1ieve 发表于 2015-3-31 18:53:23

ledCount表示所用的led有幾顆,與後面的ledPins[]數量對應

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

Klack 发表于 2015-4-1 13:18:12

非常感谢,懂了,谢谢帮忙{:soso_e179:}{:soso_e100:}
页: [1]
查看完整版本: 关于可调试灯光程序的问题