# Using if else statement

Hi trying to get leds to come on at certain temperatures (27c down to 24c then from 24c down to 20c then 20c & below)
I have got the coding this far but seems long way to do this? can I use the IF ELSE statement instead if so please please show me how. Thanks Malcolm

``````int tempPin = A1;
int led01 = 8;
int led02 = 9;
int led03 = 10;
int tempMax = 28;
int tempMid = 27;
int tempMin = 24;
int temp;

void setup() {
Serial.begin(9600);

pinMode (led01, OUTPUT);
pinMode (led02, OUTPUT);
pinMode (led03, OUTPUT);
pinMode (tempPin, INPUT);
}

void loop() {
temp = temp * 0.48828125;

Serial.print("TEMPRATURE = ");
Serial.print(temp);
Serial.print("*C");
Serial.println();
delay(1000);

if (temp > tempMax)
{
digitalWrite(led01, HIGH);
digitalWrite(led02, LOW);
digitalWrite(led02, LOW);
}
if (temp < tempMid)
{
digitalWrite(led01, LOW);
digitalWrite(led02, HIGH);
digitalWrite(led02, LOW);
}
if (temp < tempMin)
{
digitalWrite(led01, LOW);
digitalWrite(led02, LOW);
digitalWrite(led02, LOW);
}

}
``````

Thanks Malcolm

Moderator: added code tags => # button above smiley’s

Regarding the if/else, please do some homework first. There are a gazillion posts on the internet about if/else notation and nested if/else for C. A quick google will solve your issue.

The series of IF ELSE statements should be

if X > mid // which covers everything above mid

else if x > low // which covers everything between low and mid

else // which covers everything below mid

and you can have as many steps as necessary.

...R

something like this, notice how I moved them slightly…

``````int tempPin = A1;
int led01 = 8;
int led02 = 9;
int led03 = 10;
int tempMax = 28;
int tempMid = 27;
int tempMin = 24;
int temp;

void setup()
{
Serial.begin(9600);
pinMode (led01, OUTPUT);
pinMode (led02, OUTPUT);
pinMode (led03, OUTPUT);
pinMode (tempPin, INPUT);
}

void loop()
{
temp = temp * 0.48828125;
Serial.print("TEMPRATURE = ");
Serial.print(temp);
Serial.print("*C");
Serial.println();
delay(1000);
if (temp > tempMax)
{
digitalWrite(led01, HIGH);
digitalWrite(led02, LOW);
digitalWrite(led02, LOW);
}
else if (temp > tempMin)
{
digitalWrite(led01, LOW);
digitalWrite(led02, LOW);
digitalWrite(led02, LOW);
}
else
{
digitalWrite(led01, LOW);
digitalWrite(led02, HIGH);
digitalWrite(led02, LOW);
}
}
``````
``````    digitalWrite(led01, LOW);
digitalWrite(led02, LOW);
digitalWrite(led02, LOW);
``````

Shouldn't there be an led03 in there (and elsewhere) ?

This looks like the copy/paste/distracted/forget to revise pasted text syndrome. - BTDTGTTS

To me the program looks a little odd with temp being an int which is multiplied by 0.48828125 with the result assigned back to temp.