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

时间:2013-09-17 03:30:25

标签: c++ arduino light

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

1 个答案:

答案 0 :(得分:1)

第一个if语句:

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

优先于接下来的两个if语句。由于setAuto 总是为真,所以当ldr&lt; 50灯通过relayPin开启。

考虑一下如何将setAuto设置为false。

提示。您可能希望在阅读之后评估val

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