2013-05-07 57 views
0

所以代碼不能正常工作,有兩個LED不會關閉「highliten」問題。當我運行程序的其他部分時。我想在其他部分關閉它們。 :)Arduino,如果LED「卡住」

包括

byte ledPin[] = {8, 9, 10, 11, 12, 13}; //--------------------------------. 
int ledDelay;       // Del 1 
int direction = 1; 
int currentLED = 0; 
unsigned long changeTime; 
int potPin = 0; 


Servo myservo; // create servo object to control a servo 

int potpin = 0; // analog pin used to connect the potentiometer 
int val; // variable to read the value from the analog pin 
int va; 

void setup() 
{ 

    pinMode(4, OUTPUT); 
    pinMode(5, OUTPUT); 
    pinMode(6, INPUT); 
    myservo.attach(3); // attaches the servo on pin 9 to the servo object 
    Serial.begin(9600); 

    for (int x=0; x<6; x++) { 
    pinMode(ledPin[x], OUTPUT); } 
    changeTime = millis(); 
} 

void loop() { 
    int on = digitalRead(6); 
if (on == HIGH) 
{ 
    myservo.attach(3); 
// Here is the problem!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
     if va < 523) 
{ 
    digitalWrite(5, HIGH); 
} 
else if (va > 555) 
{ 
    digitalWrite(4, HIGH); 
} 

else 
{ 
    digitalWrite(4, LOW); 
    digitalWrite(5, LOW); 
} 
// Here is the problem!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
    digitalWrite(8, LOW); 
    digitalWrite(9, LOW); 
    digitalWrite(10, LOW); 
    digitalWrite(11, LOW); 
    digitalWrite(12, LOW); 
    digitalWrite(13, LOW); 
    va = analogRead(potPin);   // reads the value of the potentiometer (value between 0 and 1023) 
    val = map(va, 0, 1023, 0, 179);  // scale it to use it with the servo (value between 0 and 180) 
    myservo.write(val);     // sets the servo position according to the scaled value 
    delay(1);       // waits for the servo to get there 

} 
else 
{ 
    myservo.detach(); 
    digitalWrite(5, LOW); 
    digitalWrite(4, LOW); 
    ledDelay = analogRead(potPin)/4; 
    if ((millis() - changeTime) > ledDelay) 
    { 
    changeLED(); 
    changeTime = millis(); 
    } 
} 
} 

    void changeLED() { 
    for (int x=0; x<6; x++) 
    { 
    digitalWrite(ledPin[x], LOW); 
    } 
    digitalWrite(ledPin[currentLED], HIGH); 
    currentLED += direction; 
    if (currentLED == 6) {direction = -1;} 
    if (currentLED == 0) {direction = 1;} 
    } 

提前謝謝!

+0

我不會聲稱理解上述所有內容,但在我看來,在'if(currentLED == 6){direction = -1;}'最後的值應該是5,而不是6 。 – 2013-05-07 01:00:01

回答

2

就在草圖的最後,你有下面這行:

if (currentLED == 6) { direction = -1; } 

我認爲,實際上並沒有運行程序,這個問題就在這裏。在上一行中,您已經添加了一個值爲currentLED,並且您正在檢查是否已經排除了ledPin陣列的末尾。您改變方向,但不要將當前LED位置重置回ledPin範圍內。

下一次changeLED被稱爲它試圖調用digitalWrite(ledPin[currentLED], HIGH);currentLED值爲6,這是ledPin陣列外部。在這一點上,Arduino可能會感到不安。

我想你只需要改變陳述來檢查currentLED == 5而不是6。這意味着下次調用changeLED時,最後一個LED將打開,並且currentLED的值將遞減(direction == -1),使其保持在ledPin範圍內。