Functionality:
利用红外传感器来切换发光二极管和motorFAN的状态。因此,在满足触发距离条件时,LED光和motorFAN状态都会从低到高切换。延迟5秒后,只要满足触发距离条件,motorFAN状态将从高到低切换,而发光二极管的状态将保持较高。当触发距离不再满足时,LED灯将切换到较低的位置。
发行:
当触发距离条件满足时,发光二极管光和motorFAN状态都会从低到高切换。
但是,经过5秒的延迟后,motorFan状态将不会从高到低切换,它仍然会保持高的状态。
第二个问题是,当触发距离条件不再满足时,LED光和motorFan状态都从高切换到低。当条件再次满足时,只有LED灯从低到高,但马达风扇状态不切换,保持在低状态。
因此,需要寻求帮助来纠正这一问题和做错了什么。谢谢。
代码:
const int signalPin = 1; //wire pin to analog for IR Sensor
//Motor-Fan connected to arduino pin number
//const int FanPin = 5;
//Motor-Fan Relay
byte FanRelay = 4;
//const int FanRelay = 4;
//Light Relay
byte LightRelay = 6;
//const int LightRelay = 5;
int IRSignal; //variable signal, will hold the analog value read by Arduino
long duration;
int distance;
unsigned long Timer;
unsigned long Interval = 10000; //teh repeat Interval
unsigned long SmellInterval = 10000;
void setup()
{
//Execute only once at startup
//pinMode (FanPin , OUTPUT) ; // Set pinMode for FanPin as OUTPUT, display
pinMode (signalPin, INPUT); //infared sensor line will be an input to the Arduino
pinMode(FanRelay, OUTPUT);
pinMode(LightRelay, OUTPUT);
Serial.begin(9600); // Open serial port to communicate with the Ultrasaonic Sensor
}
void loop()
{
//execute multiple times in a loop
IRSignal = analogRead(signalPin); //arduino reads the value from the infared sensor
distance = 9462 / (IRSignal -16.92);
Serial.println(distance);
if(distance < 30 && distance > 0)
{
Timer = millis();
// Write a pin of HIGH
Serial.println("1");
digitalWrite (FanRelay, HIGH);
digitalWrite (LightRelay, HIGH);
if (Timer > SmellInterval){
//digitalWrite (FanPin, LOW);
digitalWrite (FanRelay, LOW);
}
}
else
{
Serial.println("0");
//Check if Timer is longer than 10s
if ((millis()-Timer)>Interval){
//digitalWrite (FanPin, LOW);
//digitalWrite (FanRelay, LOW);
digitalWrite (LightRelay, LOW);
}
}
delay(1000);
}发布于 2016-11-22 07:59:39
问题在于:
Timer = millis();
....
if (Timer > SmellInterval){
//digitalWrite (FanPin, LOW);
digitalWrite (FanRelay, LOW);
}Timer变量将保存millis()的当前值,即从上次重置开始的系统时间。这意味着,在运行程序的10s之后,if条件总是可以满足的。
这就是为什么当您的条件第二次满足时,FanRelay仍然很低--足够的时间过期了,所以在打开它之后,它立即被关闭。
延迟后关闭也不起作用(BTW和你的延迟都是10秒,而不是像你在帖子中提到的5秒)。您需要只在第一次满足距离条件时节省时间,并检查与该时刻的时间差。
有关类似的示例,请参见https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay。此外,如果您使用状态机概念,您的设计将更加可读性更强,更易于调试。在维基和StackOverflow上读了一些文章。在状态机中,您定义了一组状态(比如no_object_detected, object_just_detected, object_detected_a_while_ago),以及它们之间的转换(当它们发生时,以及它们发生时应该做什么)。
https://stackoverflow.com/questions/40733737
复制相似问题