Frage

I'm trying to turn a light "On" and "Off" with Arduino using a Relay, Photo-resistor and Serial Communication. 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.

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.

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
   }
}
War es hilfreich?

Lösung

The first if statement:

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

takes precedence over the next two if statements. Since setAuto is ALWAYS true and so when ldr < 50 the light thru relayPin is ON.

Think about how you might want to setAuto to false.

Hint. You might want to evaluate val just after it is read:

if ( Serial.available()) {
  val = Serial.read(); // Get serial value
  if (val == ..... logic to affect the course of events.....
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top