0

我目前正在研究自动电灯开关。这是我的代码:

#include <Servo.h>

boolean time = false;
const int timeLim = 10000;
const int delLen = 5000;
int pirVal = 0;

const int pirPin = 2;
const int sensePin = 5;
boolean timeRet = false;
int lightVal;
Servo  myServo;
unsigned long limit;

void setup() {

  Serial.begin(9600);
  pinMode(pirPin, INPUT);
  myServo.attach(11);
  myServo.write(40);

}

void loop() {
  unsigned long Timer = millis(); 

  pirVal = digitalRead(pirPin); 
  int lightVal = analogRead(sensePin);

  Serial.print(pirVal);
  Serial.print(' ');
  Serial.print(lightVal);
  Serial.print(' ');
  Serial.print(Timer);
  Serial.print(' ');
  Serial.print(time);
  Serial.print(' ');
  Serial.print(limit);
  Serial.print(' ');
  Serial.println(timeRet);

  if ( lightVal < 400 ) {
    time = false;
    limit = 0;
    timeRet = false;
  } if ( lightVal < 400 && pirVal == 1 ) {
    unsigned long time = false;
    pirVal = 0;
    myServo.write(160);
  } if ( lightVal > 400 && pirVal == 0 && timeRet == false){
    limit = getTimeLim( timeLim, Timer );
    pirVal = 0;
    timeRet = true;
  } if ( lightVal > 400 && pirVal == 0 && timeRet == true ) {
    time = timeStat ( limit, Timer );
  } if ( lightVal > 400 && time == true ) {
    myServo.write(40);
  }
}

int getTimeLim( const int timeLim, unsigned long Timer ) {
  unsigned long limit = Timer + timeLim;
  return limit;
}

boolean timeStat( unsigned long limit, unsigned long Timer ) {

  if ( Timer < limit ) {
    time = false;
  } else if ( Timer > limit ) {
    time = true;
  }
  return time;
}

问题是,当您第一次查看序列时,getTimeLim 函数它可以工作,但第二次总是一些离谱的数字(例如 4294937965)。我不知道为什么它会给我这么大的数字。帮助将不胜感激。

4

1 回答 1

1

由于您的代码现在可以工作并且您想要优化它,我建议这样做:

// ( pseudo code since i'm not familiar with arduino )

void loop( ){

    if( ( analogRead( sensePin ) < 400 ) 
    &&  ( digitalRead( pirPin ) ) ){

        myServo.write( 160 );               // turn on light

        int time_end = millis( ) + 60,000;  // initiate timer value

        while( millis( ) < time_end );      // poll time until at 60s

        myServo.write( 40 );                // turn off light
    }
}
于 2013-04-15T23:36:28.757 回答