Help with RGB light IF statements

Hi there, beginner in arduino projects.

I have written the below code for controlling an RGB LED in regards to a tempreture reading from an attached sensor, however I'm having difficult in "resetting" the RGB values if you will, it seems to stay blue at the moment regardless of a tempreture below 20, my temp is a float value if that would change things, thanks in advance. -Sam

if (temp >= 25) {
      analogWrite(redPin, 255); //red - hot
      analogWrite(greenPin, 0); 
      analogWrite(bluePin, 0); 
      delay(200);
    } else (temp <= 20); {
      analogWrite(redPin, 0);
      analogWrite(greenPin, 0);
      analogWrite(bluePin, 255); //blue - cool
      delay(200); 
    }

Lose the

;

The code executes and compiles, It doesn't go the colors i'd expect, I've currently got it to a point of flashing red but it then goes back to blue, it's as though it doesn't stop on the IF statement

Is that supposed to be

    } else if (temp <= 20) {

:thinking:

Ah yes - neither of them is any guarantee that the code will do what you wanted it to do!

There are many ways to write code that is syntactically valid (ie, compiles OK), but does not actually do what you wanted - just like a spell checker can tell you that all the words in a document are correctly spelled, but that doesn't mean they are the correct words, or that the text makes any sense!

For example:

That is syntactically valid, but I don't think it's what you want at all:

  1. @LarryD pointed out that you probably don't want the semicolon there;
  2. I pointed out that you probably should have an if in there.

@LarryD @awneil

Yep I was wrong, I must have made some changes to the code breaking it before posting, without sounding like i'm not grateful for the help you providided, I did find the solution to my problem which was finishing my IF statement with an else writing each pin back to 0 value.

My full code working is as below

if (temp >= 15) {
    analogWrite(redPin, 255);  //red - hot
    analogWrite(greenPin, 0);
    analogWrite(bluePin, 0);

    delay(1000);

  } else if (temp <= 14) {
    analogWrite(redPin, 0);
    analogWrite(greenPin, 0);
    analogWrite(bluePin, 255);  //blue - cool

      }else {
      analogWrite(redPin, 0);
      analogWrite(greenPin, 0);
      analogWrite(bluePin, 0);
     }


   if (humidity >=90) {
    analogWrite(redPin2, 0);
    analogWrite(greenPin2, 255);  //green - Wet
    analogWrite(bluePin2, 0);
  }


    else if (humidity <=70) {
    analogWrite(redPin2, 255);
    analogWrite(greenPin2, 165);  //orange- dry
    analogWrite(bluePin2, 0);
  }

  else {
      analogWrite(redPin2, 0);
      analogWrite(greenPin2, 0);
      analogWrite(bluePin2, 0);
     }

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.