为什么静态变量不允许循环()运行?

时间:2013-03-23 23:44:43

标签: c variables loops static

我正在编写一个模仿太阳的灯的代码(即根据真实的太阳升起和设置)。

我正在尝试在循环中使用静态变量以保持自1/1/12(最后一个闰年(366天)以来的天数)

由于某种原因,程序仅在变量声明为静态时才起作用,但我需要计数器在每天的迭代中持续存在。

非常感谢任何帮助。谢谢。

// Sun Object 

#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3

//#define FADESPEED 480// make this higher to slow down
#define FADESPEED 120

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);


}

void loop() {

  // daylengths for 4 year's worth of days starting from jan 1 of Great year (366 days) (1/1/2012)
 int dayLengths[] = {33540000,
33540000,
33600000,
// ....
// hundreds of values omitted here
// ....
33360000,
33420000,
33480000,
33480000};


//2012 = 366 days + day # from jan 1st (in 2013)
//starts on 0th day so subtract 1
//ready to go for march 24st @ sunrise

 // why does it not function when day is static?????

     static int day = 449;


  int r, g, b;




   long start = millis();

   for (r = 0; r <256; r++){
     analogWrite(REDPIN, r);
     delay(FADESPEED);
   }

  //analogWrite(REDPIN, 255);

 for (g = 0; g < 230; g++) { 
    analogWrite(GREENPIN, (g*.4));
    delay(FADESPEED*2);

   }

   long stopped = millis();
   long elapsed = stopped - start;
                                          //approx
   // delays (amount of daylight - ( sunrise/sunset time )
 //  delay(dayLengths[day]- (97200*2));

     delay(dayLengths[day]- (elapsed*2));


   for (g = 230; g > 0; g--) { 
    analogWrite(GREENPIN, (g*.4));
    delay(FADESPEED*2);
   }

   for (r = 256; r >0; r--){
     analogWrite(REDPIN, r);
     delay(FADESPEED);
   }

   analogWrite(REDPIN,0);


   //delays (millis in 1 day) - (length of daylight)
   delay(86400000 - dayLengths[day]);



  // once 4 year cycle is over, resets day to 0
   if (day < sizeof(dayLengths  )){

   day++;
   }

   else
   {
   day = 0;

  } 

}

1 个答案:

答案 0 :(得分:0)

听起来您在嵌入式环境中运行,并且本机硬件可能存在一些限制:loop功能中的静态使用。

我已经讨厌自己提出这个建议,但也许您可以尝试globalglobal static使用(即将day变量放在loop()函数之外,或者使用或没有static关键字)。这将使其适用于所有loop()次呼叫......