2016-07-28 77 views
-2

我的arduino在一段时间后停止工作。 这里是我的代码:Arduino在一段时间后不工作

//Pin.h is my header file 

#ifndef Pin_h 
#define Pin_h 

class Pin{ 
    public: 
    Pin(byte pin); 
    void on();//turn the LED on 
    void off();//turn the LED off 
    void input();//input PIN 
    void output();//output PIN 

    private: 
    byte _pin;  
}; 

#endif 


//Pin.cpp is my members definitions 
#include "Arduino.h" 
#include "Pin.h" 

Pin::Pin(byte pin){//default constructor 
    this->_pin = pin; 
} 

void Pin::input(){ 
    pinMode(this->_pin, INPUT); 
} 

void Pin::output(){ 
    pinMode(this->_pin, OUTPUT); 
} 

void Pin::on(){ 
    digitalWrite(this->_pin, 1);//1 is equal to HIGH 
} 

void Pin::off(){ 
    digitalWrite(this->_pin, 0);//0 is equal to LOW 
} 


//this is my main code .ino 
#include "Pin.h" 

Pin LED[3] = {//array of objects 
Pin(11), 
Pin(12), 
Pin(13) 
}; 

const byte MAX = sizeof(LED); 

//MAIN PROGRAM---------------------------------------------------------------------------------- 
void setup() { 
    for(int i = 0; i < MAX; i++){ 
     LED[i].output(); 
    }//end for loop initialize LED as output 
}//end setup 

int i = 0; 

void loop() { 
    for(i = 0; i < 3; i++){ 
    LED[i].on(); 
    delay(1000); 
    } 

    for(i = 3; i >= 0; i--){ 
    LED[i].off(); 
    delay(1000); 
    } 

}//end loop 
//see class definition at Pin.h 
//see class members at Pin.cpp 

我的Arduino停止工作时,我使用两个为无效循环函数内部循环,但如果我在下面主要使用此代码,它工作正常。为什么我的arduino在使用for循环后会停一会儿?

void loop() { 
    LED[0].on(); 
    delay(1000); 

    LED[1].on(); 
    delay(1000); 

    LED[2].on(); 
    delay(1000); 

    LED[2].off(); 
    delay(1000); 

    LED[1].off(); 
    delay(1000); 

    LED[0].off(); 
    delay(1000); 
}//end loop 
+0

总是检查降价预览。 – LogicStuff

回答

0

这是因为你与我= 3开始你的第二个循环......

void loop() { 
    for(i = 0; i < 3; i++){ 
    LED[i].on(); 
    delay(1000); 
    } 

    for(i = 3; i >= 0; i--){ 
    LED[i].off(); // This causes a crash on the first run LED[3] is out of range... 
    delay(1000); 
    } 

}//end loop 

此外,要替换这些“3”“MAX”,所以当你改变大小,你不必在任何地方重写它...

void loop() { 
    for(i = 0; i < MAX; i++){ 
    LED[i].on(); 
    delay(1000); 
    } 

    for(i = MAX - 1; i >= 0; i--){ 
    LED[i].off(); 
    delay(1000); 
    } 

}//end loop 
+0

我的天啊。即时通讯如此愚蠢。谢谢.. ..谢谢一堆..我真的很感激它.. –

+0

马克这篇文章作为答案然后,所以其他人有同样的问题将能够解决它更快 –

相关问题