2013-10-03 128 views
1

所以我正在學習如何控制一個Arduino的8x8 LED矩陣,但由於某種原因,我的代碼無法正常工作。我有8行(每個都附着在它自己的引腳上,從12到5)和4列(每個引腳都有自己的引腳,引腳0-3)現在都在工作。我想用我的LED製作一種蛇形設計,所以它會沿着對角線移動。代碼正在工作,然後我決定添加兩行代碼(我現在已經刪除),但仍然無法工作。發生的是所有的LED永久點亮,而不是一次一個。Arduino 8x8 LED矩陣不會關閉

編輯:我知道使用延遲一般不好,以及事實上我應該使用開關的情況下,但我覺得這很簡單,不必擔心它。

下面的代碼:

int pinnum = 13; 
int lastpin = 0; 
int col = 0; 
int k; 

void setup() { //runs once 
// initialize pins as outputs 
    for(int pinnum; pinnum >= lastpin; pinnum--) 
    { 
    pinMode(pinnum, OUTPUT); 
    } 
    for(int i = 5; i <= 13; i++) //starts with all of them off 
    { 
    digitalWrite(i,LOW); 
    } 
    for(int i = 0; i <= 4; i++) //starts with all of them off 
    { 
    digitalWrite(i, HIGH); 
    } 

}// END SETUP 

void loop() { 

pinon(12); 
togglecol(); 
delay(1000); 

pinon(11); 
togglecol(); 
delay(1000); 

pinon(10); 
togglecol(); 
delay(1000); 

pinon(9); 
togglecol(); 
delay(1000); 

pinon(8); 
togglecol(); 
delay(1000); 

pinon(7); 
togglecol(); 
delay(1000); 

pinon(6); 
togglecol(); 
delay(1000); 

pinon(5); 
togglecol(); 
delay(1000); 
} 

void togglecol() 
{ 
if(col % 4 == 1) //column = 1, pin 3 
{ 
    digitalWrite(0, HIGH); 
    digitalWrite(1, HIGH); 
    digitalWrite(2, HIGH); 
    digitalWrite(3, LOW); 
} 
else if(col % 4 == 2) //COLUMN = 2, PIN 2 
{ 
    digitalWrite(0, HIGH); 
    digitalWrite(1, HIGH); 
    digitalWrite(2, LOW); 
    digitalWrite(3, HIGH); 
} 
else if(col % 4 == 3) //COLUMN = 3, PIN 1 
{ 
    digitalWrite(0, HIGH); 
    digitalWrite(1, LOW); 
    digitalWrite(2, HIGH); 
    digitalWrite(3, HIGH); 
} 
else if(col % 4 == 0) // COLUMN 3, PIN 0 
{ 
    digitalWrite(0, LOW); 
    digitalWrite(1, HIGH); 
    digitalWrite(2, HIGH); 
    digitalWrite(3, HIGH); 
} 
col++; 
} //END TOGGLECOL 



void pinon(int pin) 
{ 
    for(k = 5; k <= 13; k++) //turning all rows off 
    { 
    digitalWrite(k, LOW); 
    } 
    digitalWrite(pin, HIGH); //activating correct row again 
}//END PINON` 

回答

1

所以我認爲至少有一個錯誤就在這裏

void setup() { //runs once 
// initialize pins as outputs 
    for(int pinnum; pinnum >= lastpin; pinnum--) 
    { 
    pinMode(pinnum, OUTPUT); 
    } 

高於此設置pinnum = 13但隨後在你的循環,你說for(int pinnum...

這會將pinnum重新初始化爲0,這樣您的for循環就不會被執行。

您可以在這裏測試此therory http://www.compileonline.com/compile_cpp_online.php

只需複製並粘貼以下和命中編譯看出差別

//Working for loop 

#include <iostream> 

using namespace std; 

int main() 
{ 
    cout << "Hello World" << endl; 
    int a = 10; 

    for(a; a>0; a--){ 
     cout << a << endl;  
    } 
    return 0; 
} 

然後嘗試

//For loop like yours 
#include <iostream> 

using namespace std; 

int main() 
{ 
    cout << "Hello World" << endl; 
    int a = 10; 

    for(int a; a>0; a--){ 
     cout << a << endl;   
    } 
    return 0; 
}