const int RELAY_PIN = 7;//输出7引脚,给继电器的输入用的
const int THRESHOLD = 215; // 根据实际情况设置光照阈值
void setup() {
pinMode(RELAY_PIN, OUTPUT);
pinMode(A0, INPUT);//A0读取光敏电阻的输入
}
void loop() {
int lightValue = valueToLightValue();
if (lightValue < THRESHOLD) {
digitalWrite(RELAY_PIN, HIGH); // 打开继电器,发光二极管亮起
} else {
digitalWrite(RELAY_PIN, LOW); // 关闭继电器,发光二极管熄灭
}
delay(100); // 延迟一段时间进行下一次光照检测
}
//从读取过来的值转换为光强值(lux)
//换算公示文档抄来的:https://docs.wokwi.com/zh-CN/parts/wokwi-photoresistor-sensor#%E5%B7%A5%E4%BD%9C%E6%96%B9%E5%BC%8F
int valueToLightValue() {
// These constants should match the photoresistor's "gamma" and "rl10" attributes
const float GAMMA = 0.7;
const float RL10 = 50;
// Convert the analog value into lux value:
int analogValue = analogRead(A0);//A0读取光敏电阻的输入
float voltage = analogValue / 1024. * 5;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
return lux;
}