简体   繁体   English

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

[英]Controling Light With Photoresistor And Serial Communication - Arduino

I'm trying to turn a light "On" and "Off" with Arduino using a Relay, Photo-resistor and Serial Communication. 我正在尝试使用继电器,光敏电阻和串行通信使用Arduino将灯“打开”和“关闭”。 The problem come in to play when I try to turn the light Off when the Photo-resistor is receiving a low value and has received an instruction via Serial Communication to prevent the "IF" statement from activating, it simply doesn't not work as the light is kept on. 当光敏电阻接收到一个低值并且已通过串行通信接收到一条指令来阻止“ IF”语句激活时,当我尝试将灯关闭时,问题就来了,这根本不起作用灯一直亮着。

I'm using 4 "IF" statement to control the light: auto light using Photo-resistor and serial value resumed in "ON/OFF", turn light on using serial value "h", turn light off using serial value "l" and another serial value to control the auto light statement using "a" to control the first statement. 我正在使用4个“ IF”语句来控制灯光:使用光敏电阻自动点亮,并在“ ON / OFF”中恢复序列值,使用序列值“ h”打开光源,使用序列值“ l”关闭光源另一个序列值使用“ a”控制第一条语句来控制自动点亮语句。

How can I use a value to control light based on a sensor and serial output at the same time. 如何同时使用基于传感器和串行输出的值来控制光。 In other words, how can I stop light from turning on automatically?? 换句话说,如何阻止自动打开灯? What I'm doing wrong or what I left? 我做错了什么或我剩下了什么?

Here is my simple code: 这是我的简单代码:

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
   }
}

The first if statement: 第一个if语句:

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

takes precedence over the next two if statements. 优先于接下来的两个if语句。 Since setAuto is ALWAYS true and so when ldr < 50 the light thru relayPin is ON. 由于setAuto 始终为 true,因此当ldr <50时,继电器Pin点亮。

Think about how you might want to setAuto to false. 考虑一下您可能希望如何将Auto设置为false。

Hint. 暗示。 You might want to evaluate val just after it is read: 您可能要在读取后立即评估val

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM