Lab 1 人体检测与继电器

连线。PIR 的 S → D12、V → 5 V、G → GND。D13 → 限流电阻 → LED 阳极,阴极 → GND。程序输出 LED,可直接看亮灭。课堂 Week 07 Part01 00:05:05–00:09:12 介绍这个任务,实验步骤见 Tutorial 1 第 4 页。

第 1–14 行 · 指定引脚与开机状态

const int PIR_PIN = 12; 设固定输入脚,LED_PIN = 13 设固定输出脚。进入 setup() 后,把 D12 设成 INPUT,把 D13 设成 OUTPUT,再把灯写成 LOW。最后启动 9600 波特率串口,打印标题一次。因此开机后默认灭灯,随后才进入检测。

展开原代码第 1–14 行
   1  
   2  const int PIR_PIN = 12;
   3  const int LED_PIN = 13;
   4  
   5  void setup() {
   6    pinMode(PIR_PIN, INPUT);
   7    pinMode(LED_PIN, OUTPUT);
   8  
   9    digitalWrite(LED_PIN, LOW);
  10  
  11    Serial.begin(9600);
  12    Serial.println("Experiment 1: PIR Motion Detection");
  13  }
  14  

第 15–24 行 · 第一次读到 HIGH,点亮并等待

int motion = digitalRead(PIR_PIN);
if (motion == HIGH) {
    digitalWrite(LED_PIN, HIGH);
    Serial.println("Motion detected - LED ON");
    delay(3000);

digitalRead 给出当前 D12 电平。if 成立时,先亮灯再打印。Arduino 等 3000 ms 才执行下一句,期间灯保持 HIGH。第一次读到 LOW 时,直接跳到外层 else。

展开原代码第 15–24 行
  15  void loop() {
  16    int motion = digitalRead(PIR_PIN);
  17  
  18    if (motion == HIGH) {
  19      // Motion detected: turn LED ON
  20      digitalWrite(LED_PIN, HIGH);
  21      Serial.println("Motion detected - LED ON");
  22  
  23      // Wait 3 seconds
  24      delay(3000);

第 25–40 行 · 等够三秒后的复查

第 27 行重新读 D12,把新值覆盖进 motion。若 LOW,灭灯并打印 No motion - LED OFF。若 HIGH,只打印 Motion still detected - LED ON,灯保持原状态。外层的 else 处理一开始就是 LOW 的情况,只熄灯。每轮最后额外 delay(100),再回到第 16 行读一次。

手动跟踪。 第 0 秒读 HIGH,立即亮。第 1 秒 PIR 转 LOW,程序还在等待。第 3 秒复查 LOW 才熄灭。若第 3 秒仍是 HIGH,保持亮,第 3.1 秒附近开始下一轮,读到 HIGH 就再等 3 秒。比较 LED 和日志,能看出是哪次判断改变输出。

展开原代码第 25–40 行
  25  
  26      // Check the sensor again
  27      motion = digitalRead(PIR_PIN);
  28  
  29      if (motion == LOW) {
  30        digitalWrite(LED_PIN, LOW);
  31        Serial.println("No motion - LED OFF");
  32      } else {
  33        Serial.println("Motion still detected - LED ON");
  34      }
  35    } else {
  36      digitalWrite(LED_PIN, LOW);
  37    }
  38  
  39    delay(100);
  40  }