Files
LampControler/src/LightControl.cpp

61 lines
1.6 KiB
C++
Raw Normal View History

2025-05-13 16:55:49 +08:00
// LightControl.cpp
#include "LightControl.h"
#include "Arduino.h"
LightControl::LightControl(BH1750& sensor, DS3502& pot)
: lightSensor(sensor), digitalPot(pot) {}
void LightControl::setTargetLight(float target) {
targetLightLevel = target;
}
float LightControl::getCurrentLight() {
return lightSensor.readLightLevel();
}
2025-06-17 17:24:26 +08:00
void LightControl::runUntilTargetReached(float target, int maxAttempts) {
const float tolerance = 100.0f; // 容许误差范围(±100 lux)
float currentLight;
float res;
int attempt = 0;
const int max_retries = maxAttempts; // 最大尝试次数,防止死循环
do {
currentLight = getCurrentLight();
res = target - currentLight;
if (abs(res) <= tolerance) {
Serial.println("Target reached.");
break;
}
int lastWiperValue = digitalPot.getWiper();
if (res > 0) {
// 需要增加亮度 -> 增加电位器阻值
if (lastWiperValue <= 127) {
lastWiperValue++;
}
} else if (res < 0) {
// 需要减少亮度 -> 减少电位器阻值
if (lastWiperValue > 0) {
lastWiperValue--;
}
}
digitalPot.setWiper(lastWiperValue);
Serial.printf("Current light: %.0f, Target: %.0f, Res: %.0f, Wiper: %d\n", currentLight, target, res, lastWiperValue);
delay(200); // 等待响应,必要!!
attempt++;
// 超出最大尝试次数退出
if (attempt >= max_retries) {
Serial.println("Max attempts reached. Exiting...");
break;
}
} while (true);
2025-05-13 16:55:49 +08:00
}