attachInterrupt() 函數
要在 Arduino IDE 中設置中斷,請使用 attachInterrupt() 函數,該函數接受以下參數:GPIO 中斷引腳、要執行的函數的名稱和模式:
attachInterrupt(digitalPinToInterrupt(GPIO), ISR, mode);
1.png (56.38 KB, 下載次數: 15)
下載附件
2022-11-6 06:52 上傳
- #define timeSeconds 10
- // Set GPIOs for LED and PIR Motion Sensor
- const int led = 12;
- const int motionSensor = 14;
- // Timer: Auxiliary variables
- unsigned long now = millis();
- unsigned long lastTrigger = 0;
- boolean startTimer = false;
- // Checks if motion was detected, sets LED HIGH and starts a timer
- ICACHE_RAM_ATTR void detectsMovement() {
- Serial.println("MOTION DETECTED!!!");
- digitalWrite(led, HIGH);
- startTimer = true;
- lastTrigger = millis();
- }
- void setup() {
- // Serial port for debugging purposes
- Serial.begin(115200);
-
- // PIR Motion Sensor mode INPUT_PULLUP
- pinMode(motionSensor, INPUT_PULLUP);
- // Set motionSensor pin as interrupt, assign interrupt function and set RISING mode
- attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING);
- // Set LED to LOW
- pinMode(led, OUTPUT);
- digitalWrite(led, LOW);
- }
- void loop() {
- // Current time
- now = millis();
- // Turn off the LED after the number of seconds defined in the timeSeconds variable
- if(startTimer && (now - lastTrigger > (timeSeconds*1000))) {
- Serial.println("Motion stopped...");
- digitalWrite(led, LOW);
- startTimer = false;
- }
- }
復制代碼 |