Arduino自动灯开关2

时间:2013-04-15 23:25:22

标签: automation arduino

我正在研究一种自动灯开关。这是我的代码:

#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)。我不知道为什么会给我这么大的数字。非常感谢帮助。

1 个答案:

答案 0 :(得分: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
    }
}