1

我正在尝试使用继电器、光敏电阻和串行通信通过 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
   }
}
4

1 回答 1

1

第一个 if 语句:

 if ( setAuto == true && ldr < 50 ) { // Here is the main problem
     digitalWrite(relayPin, HIGH);
 } else {

优先于接下来的两个 if 语句。由于 setAuto始终为真,因此当 ldr < 50 时,通过 relayPin 的灯为 ON。

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

暗示。您可能想val在阅读后立即进行评估:

if ( Serial.available()) {
  val = Serial.read(); // Get serial value
  if (val == ..... logic to affect the course of events.....
}
于 2013-09-17T05:31:20.807 回答