Lab 2 光敏自动调光

光敏模块 S/V/G → A0/5 V/GND。D11 经限流电阻接 LED 阳极,阴极接 GND。A0 读 0–1023,D11 写 PWM 0–255。先分别遮光、照光,看读数方向。本草图按「暗处读数低」计算。课堂 Week 07 Part01 00:05:05–00:09:12 把它列为当次第二项任务。

第 1–21 行 · 先分清阈值、模式和手动亮度

LDR_PIN、LED_PIN 固定接线。thresholdValue = 20 是默认阈值,autoMode = true 表示默认按光调节,manualBrightness = 0 存手动档亮度。lastPrint 记上次输出时刻。函数 showHelp() 一行一行打印三条命令和允许的范围,供用户在串口监视器查看。

展开原代码第 1–21 行
   1  
   2  const int LDR_PIN = A0;
   3  const int LED_PIN = 11;
   4  
   5  // Light threshold (change this value)
   6  int thresholdValue = 20;
   7  
   8  bool autoMode = true;
   9  int manualBrightness = 0;
  10  
  11  unsigned long lastPrint = 0;
  12  
  13  void showHelp() {
  14    Serial.println("Experiment 2: Automatic Light Control");
  15    Serial.println("Commands:");
  16    Serial.println("auto");
  17    Serial.println("manual X (0-255)");
  18    Serial.println("threshold T (0-1023)");
  19    Serial.println("-----------------------------");
  20  }
  21  

第 22–56 行 · 字符串如何变成状态修改

语句 程序怎么处理
trim() 和 toLowerCase() 去掉首尾空白,把 Manual 128 变成 manual 128
command == "auto" 设为自动模式并回报
startsWith("manual ") 前缀共 7 字符,substring(7) 取后面的数字文本
value >= 0 && value <= 255 符合范围才保存、关闭自动模式、立即写 PWM 并打印
startsWith("threshold ") 前缀共 10 字符,同理取参数,范围 0–1023 后保存阈值

toInt() 在无可读数字时会得到 0,因此当前 manual hello 可能被当成合法的 0。要拒绝此类输入,可在转换前确认参数每个字符都为数字。改变阈值时模式变量没有被改写,手动档仍保持原亮度。

展开原代码第 22–56 行
  22  void handleCommand(String command) {
  23    command.trim();
  24    command.toLowerCase();
  25  
  26    if (command == "auto") {
  27      autoMode = true;
  28      Serial.println("AUTO mode enabled");
  29    }
  30  
  31    else if (command.startsWith("manual ")) {
  32      int value = command.substring(7).toInt();
  33  
  34      if (value >= 0 && value <= 255) {
  35        autoMode = false;
  36        manualBrightness = value;
  37  
  38        analogWrite(LED_PIN, manualBrightness);
  39  
  40        Serial.print("Manual brightness: ");
  41        Serial.println(manualBrightness);
  42      }
  43    }
  44  
  45    else if (command.startsWith("threshold ")) {
  46      int value = command.substring(10).toInt();
  47  
  48      if (value >= 0 && value <= 1023) {
  49        thresholdValue = value;
  50  
  51        Serial.print("Threshold changed to: ");
  52        Serial.println(thresholdValue);
  53      }
  54    }
  55  }
  56  

第 57–71 行 · 初始化引脚、串口和开机帮助

A0 配成输入,D11 配成输出。串口用 9600,setTimeout(50) 给读取等待设定超时时间。先写 PWM 0,再打印帮助和初始阈值,让打开监视器的人知道可输入哪些命令。

展开原代码第 57–71 行
  57  void setup() {
  58    pinMode(LDR_PIN, INPUT);
  59    pinMode(LED_PIN, OUTPUT);
  60  
  61    Serial.begin(9600);
  62    Serial.setTimeout(50);
  63  
  64    analogWrite(LED_PIN, 0);
  65  
  66    showHelp();
  67  
  68    Serial.print("Initial threshold: ");
  69    Serial.println(thresholdValue);
  70  }
  71  

第 72–84 行 · 一轮先收命令,再读光强

有串口数据时,用 readStringUntil('\n') 等到换行或超时,再交给 handleCommand。监视器可选发送换行,命令就能立即结束读取。接下来 analogRead(A0) 得当前光值,先把本轮 PWM 设成 0,交给下一段改写。

展开原代码第 72–84 行
  72  void loop() {
  73  
  74    // Read serial commands
  75    if (Serial.available() > 0) {
  76      String command = Serial.readStringUntil('\n');
  77      handleCommand(command);
  78    }
  79  
  80    // Read light sensor
  81    int lightValue = analogRead(LDR_PIN);
  82  
  83    int pwmValue = 0;
  84  

第 85–111 行 · 阈值之内按比例点灯,手动时取上次设定

自动模式只在 x<Tx<T 时调用 map(x,0,T,255,0)。光值 xx 从 0 增到 TT,在量程走了 x/Tx/T,亮度便从 255 减去 255x/T255x/T。Arduino 整数运算截断这段差值,接着 constrain 把 PWM 限制在 0–255。

默认 T=20T=20 时,x=10x=10 得 255−⌊255×10/20⌋=128255-\lfloor 255\times10/20\rfloor=128。当 x≥20x\ge20,直接写 0。T=0T=0 时条件始终不成立,程序也不会做除零。手动模式直接取 manualBrightness。两条路径最后都用 analogWrite(LED_PIN, pwmValue) 控灯。

走一遍。 自动模式读 10,PWM 128。发 manual 200 后照光把读数变成 100,PWM 仍为 200。再发 auto,读数 100 超过 20,PWM 回到 0。

展开原代码第 85–111 行
  85    if (autoMode) {
  86  
  87      // LED ON only when Light < threshold
  88      if (lightValue < thresholdValue) {
  89  
  90        // Darker = Brighter
  91        pwmValue = map(
  92          lightValue,
  93          0,
  94          thresholdValue,
  95          255,
  96          0
  97        );
  98  
  99        pwmValue = constrain(pwmValue, 0, 255);
 100  
 101      } else {
 102        pwmValue = 0;
 103      }
 104  
 105    } else {
 106      pwmValue = manualBrightness;
 107    }
 108  
 109    // Apply LED brightness
 110    analogWrite(LED_PIN, pwmValue);
 111  

第 112–128 行 · 每 200 ms 打印一条

millis()-lastPrint 计算经过时间。差值够 200 就更新 lastPrint,依次打印光强、阈值、PWM 和模式。表达式 autoMode ? "AUTO" : "MANUAL" 按布尔值选字符串。最后 println 换行。条件没到时分支直接跳过,下一轮仍可继续读光和串口。

展开原代码第 112–128 行
 112    // Print data every 200 ms
 113    if (millis() - lastPrint >= 200) {
 114      lastPrint = millis();
 115  
 116      Serial.print("Light: ");
 117      Serial.print(lightValue);
 118  
 119      Serial.print(" | Threshold: ");
 120      Serial.print(thresholdValue);
 121  
 122      Serial.print(" | PWM: ");
 123      Serial.print(pwmValue);
 124  
 125      Serial.print(" | Mode: ");
 126      Serial.println(autoMode ? "AUTO" : "MANUAL");
 127    }
 128  }