我目前正在研究自动电灯开关。这是我的代码:
#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)。我不知道为什么它会给我这么大的数字。帮助将不胜感激。