![]() |
1、输入定时延时函数数值。2、为了模拟,输出为13,板子上面有LED观察,可改为其它引脚为继电器输出。 3、2、3设定为定时开始和停止按键。 由于要求未说明白,本例使用MsTimer2定时器和硬件中断,以提高稳定性。
看能否适用这个要求。 [color=rgba(0, 0, 0, 0.85)] |
给你个参考。 int led_pin = 18; int relay_pin = 12; int sensor_pin = 4; bool detected = false; bool stop_relay = false; unsigned long motion_stopped_time = 0; //will track the elapsed time after the motion stop void setup() { pinMode(led_pin, OUTPUT); pinMode(relay_pin, OUTPUT); pinMode(sensor_pin, INPUT_PULLUP); Serial.begin(9600); } void loop(){ if(digitalRead(sensor_pin) == HIGH){ //the sensor has detected motion //enclose the code here so it only executes once when motion is detected if(detected == false){ Serial.println("Motion detected!"); detected = true; digitalWrite(led_pin, HIGH); //turn led on digitalWrite(relay_pin, HIGH); //switch the relay on } }else{ //the sensor has stopped detecting motion if(detected == true){ //execute this only once when motion stops Serial.println("Motion stopped!"); detected = false; digitalWrite(led_pin, LOW); //turn the led off motion_stopped_time = millis(); //remember the current time stop_relay = true; }else{ if(stop_relay == true){ // ensures that this block will only execute once after the delay timer logic below //the current millis() time is 60sec more than the remembered time when the motion stopped if(millis() - motion_stopped_time >= 60000){ digitalWrite(relay_pin, LOW); //switch the relay off stop_relay = false; } } } } } |
简单程序直接用等待语句,复杂场合用中断? |