使用光敏电阻和串行通信控制光 - Arduino



>我正在尝试使用继电器,光敏电阻和串行通信使用Arduino"打开"和"关闭"灯。当我尝试关闭灯时,当光敏电阻接收到低值并通过串行通信收到指令以防止"IF"语句激活时,问题就出现了,它根本不工作,因为灯一直亮着。

我使用 4 个"IF"语句

来控制灯光:使用光敏电阻自动点亮并在"开/关"中恢复串行值,使用串行值"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 时,光通继电器引脚为打开。

考虑一下您可能希望如何将"自动"设置为 false。

提示。 您可能希望在读取val后立即对其进行评估:

if ( Serial.available()) {
  val = Serial.read(); // Get serial value
  if (val == ..... logic to affect the course of events.....
}

最新更新