![]() |
1、輸入定時延時函數(shù)數(shù)值。2、為了模擬,輸出為13,板子上面有LED觀察,可改為其它引腳為繼電器輸出。 3、2、3設定為定時開始和停止按鍵。 由于要求未說明白,本例使用MsTimer2定時器和硬件中斷,以提高穩(wěn)定性。
看能否適用這個要求。 [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; } } } } } |
簡單程序直接用等待語句,復雜場合用中斷? |
Powered by 單片機教程網(wǎng)