25/06/17
This commit is contained in:
@ -14,22 +14,48 @@ float LightControl::getCurrentLight() {
|
||||
return lightSensor.readLightLevel();
|
||||
}
|
||||
|
||||
void LightControl::adjustWiper() {
|
||||
float currentLight = getCurrentLight();
|
||||
float error = targetLightLevel - currentLight;
|
||||
void LightControl::runUntilTargetReached(float target, int maxAttempts) {
|
||||
const float tolerance = 100.0f; // 容许误差范围(±100 lux)
|
||||
float currentLight;
|
||||
float res;
|
||||
|
||||
// 计算输出变化量(比例控制)
|
||||
int delta = (int)(abs(error) * Kp);
|
||||
if (delta < 1) delta = 1; // 最小调节步长
|
||||
int attempt = 0;
|
||||
const int max_retries = maxAttempts; // 最大尝试次数,防止死循环
|
||||
|
||||
if (error > 0) {
|
||||
// 需要增加亮度 -> 减小电位器阻值
|
||||
lastWiperValue = max(0, lastWiperValue - delta);
|
||||
} else if (error < 0) {
|
||||
// 需要减少亮度 -> 增大电位器阻值
|
||||
lastWiperValue = min(127, lastWiperValue + delta);
|
||||
}
|
||||
do {
|
||||
currentLight = getCurrentLight();
|
||||
res = target - currentLight;
|
||||
|
||||
digitalPot.setWiper(lastWiperValue);
|
||||
Serial.printf("Current Light: %.0f lux | Wiper Value: %d\n", currentLight, lastWiperValue);
|
||||
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);
|
||||
}
|
||||
Reference in New Issue
Block a user