2017-04-07 116 views
-5

我解釋我的問題:我試圖解決一個數組有問題,我有一個程序在OOP中完成,其中有一個類叫做lights。我想要的是做一個數組與內部的PIN碼,並將其設置爲輸出。我做了一針一針,這很容易做到,但現在我想用一個for循環和一個數組來做到這一點 我不知道如何構建一個構造函數和處理這個數組與白色針數字在其中。數組,構造函數和實例

//---------------------------------------------------------------------------------- 
class lights{ 

    int pins[5]; //array for 5 elements 
    int i; 

    public: 
    lights(int ledPins[]){ 

    for(i=0; i<5; i++){  //pins are set up as output 
     pinMode(pins[i],OUTPUT); 
    } 

    }//end constructor 


    void attempt(){      //metodo para pobrar si se enciende los leds 

    for(i=0; i<5; i++){ 
     digitalWrite(pins[i],HIGH); 
     Serial.println(pins[i]); 
    } 
    }//end attempt 
};//end class 
//--------------------------------------------------------------------------------------------------------------------- 


int MyPins[] = {5,6,7,8,9};  //I declare what it is inside 

lights lit(MyPins);     //I create an objet with my array as parameters 

void setup(){ 
    Serial.begin(9600); 
} 

void loop(){ 

    lit.attempt(); 

} 
+3

Java和C++是兩種截然不同的語言。選一個。 –

+0

@OusmaneMahyDiaw OP已經標記了java和C++的問題,這是山姆所指的 – Ishnark

回答

0

你不需要把所有東西都放到一個類中。我認爲使用燈光課是矯枉過正的。

根據我的經驗,一個函數用於處理光引腳,它們都將引腳枚舉。

除非您有大量的引腳設置,否則循環可能不值得。展開循環可能會提高程序的效率:

pinMode(5,OUTPUT); 
pinMode(6,OUTPUT); 
pinMode(7,OUTPUT); 
pinMode(8,OUTPUT); 
pinMode(9,OUTPUT); 

初始化通常只發生一次,因此優化通常不受保證。

如果需要使用類,我建議一個類模型單燈。

每盞燈都有一個關聯的引腳。

您可以用燈(如數組)的容器:

class Light 
{ 
    public: 
    Light(unsigned int pin) 
     : m_pin(pin), 
     m_is_on(false) 
    { ; } 

    void initialize(); // Sets up the appropriate pin 
    void on(); // Turns on the light 
    void off(); // Turns off the light 
    void blink(unsigned int rate, unsigned int duration); 

    private: 
    unsigned int m_pin; 
    bool   m_is_on; 
}; 

Light display[] = {Light(5), Light(6), Light(7), Light(8), Light(9)}; 
const unsigned int light_quantity = 
    sizeof(display)/sizeof(display[0]); 

的優勢,這種模式是你的程序可以在方面,而不是擔心引腳。

0

您的代碼不工作,因爲你只是編寫代碼但沒有做的算法來設計應用程序第一...

花點時間看看你寫的軟件... 你逝去給構造函數一個數組,但是你在哪裏使用這些信息?無處...

lights(int ledPins[]){ 

    for(i=0; i<5; i++){  //pins are set up as output 
     pinMode(pins[i],OUTPUT); 
    } 

    }//end constructor 

和你在Arduino的設置爲輸出引腳{0 to 4},而不是{5 to 9}你想象,在那之後的方法只設置爲高電平引腳可能甚至不有LED指示燈:)

(你應該有通過的方式使用的睡眠和玩關閉打開的LED,所以你可以看到他們是如何閃爍)

-1

我解決了這個問題:只有兩個線不翼而飛。我糾正了真正的構造函數

public: 
    lights(int ledPins[]){ 
    for(i=0; i<5; i++){  
     pines[i] = ledPines[i]; 
    for(i=0; i<5; i++){  //pins are set up as output 
     pinMode(pins[i],OUTPUT); 
    } 

    }//end constructor