我正在尝试使用继电器、光敏电阻和串行通信通过 Arduino 将灯“打开”和“关闭”。当我尝试在光敏电阻接收到低值并通过串行通信收到指令以防止“IF”语句激活时关闭灯时,问题就出现了,它根本不起作用灯一直亮着。
我正在使用 4 个“IF”语句来控制灯:使用光敏电阻和序列值在“ON/OFF”中恢复自动点亮,使用序列值“h”打开灯,使用序列值关闭灯“l”和另一个序列值来控制自动灯语句,使用“a”来控制第一个语句。
我如何使用一个值来同时控制基于传感器和串行输出的光。换句话说,我怎样才能阻止灯自动打开?我做错了什么或遗漏了什么?
这是我的简单代码:
char val;
boolean setAuto=true; // Automatic Light Status Value
int ldr;
int relayPin=4;
void setup() {
pinMode(relayPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
ldr = analogRead(A0); // Read value from Photoresistor
if ( Serial.available()) {
val = Serial.read(); // Get serial value
}
if ( setAuto == true && ldr < 50 ) { // Here is the main problem
digitalWrite(relayPin, HIGH);
}
else if ( val == 'h' ) {
digitalWrite(relayPin, HIGH); // Work
}
else if ( val == 'l') {
digitalWrite(relayPin, LOW); // Work
}
else if (val == 'a') { // Here is the other part of the problem
setAuto = !setAuto; // Changing value for automatic light
}
}
最佳答案
第一个 if 语句:
if ( setAuto == true && ldr < 50 ) { // Here is the main problem
digitalWrite(relayPin, HIGH);
} else {
优先于接下来的两个 if 语句。由于 setAuto 始终为真,因此当 ldr < 50 时,通过 relayPin 的灯会亮起。
考虑一下您可能希望如何将 Auto 设置为 false。
提示。您可能希望在读取 val
后对其求值:
if ( Serial.available()) {
val = Serial.read(); // Get serial value
if (val == ..... logic to affect the course of events.....
}
关于c++ - 使用光敏电阻和串行通信控制光 - Arduino,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18840864/