熱門: 51單片機(jī) | 24小時(shí)必答區(qū) | 單片機(jī)教程 | 單片機(jī)DIY制作 | STM32 | Cortex M3 | 模數(shù)電子 | 電子DIY制作 | 音響/功放 | 拆機(jī)樂園 | Arduino | 嵌入式OS | 程序設(shè)計(jì)
![]() |
1、輸入定時(shí)延時(shí)函數(shù)數(shù)值。2、為了模擬,輸出為13,板子上面有LED觀察,可改為其它引腳為繼電器輸出。 3、2、3設(shè)定為定時(shí)開始和停止按鍵。 由于要求未說明白,本例使用MsTimer2定時(shí)器和硬件中斷,以提高穩(wěn)定性。
看能否適用這個(gè)要求。 [color=rgba(0, 0, 0, 0.85)] |
給你個(gè)參考。 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; } } } } } |
簡(jiǎn)單程序直接用等待語句,復(fù)雜場(chǎng)合用中斷? |
Powered by 單片機(jī)教程網(wǎng)