if & else conditions & ternary operator in Arduino

How if else conditions work in programming & how to use if else conditions works in code are some questions that may arise while programming an Arduino.

Hello guys! Welcome back to my blog today we are going to see about if-else conditions in Arduino.
if then else Arduino

So as the name suggests if and else if means checking the condition whether it’s true or false, equal or not, greater or less than between values. If the condition satisfies then do some task if the condition is not satisfied then do this task.  

Let’s take an example of it, suppose it’s your holiday and you want to enjoy it. You and your friends decide on a cricket match in the afternoon but you are worried that rain may spoil your day. So you begin to think and make the conclusion that if it doesn’t rain then we will go for a cricket match but if it starts raining in the afternoon then we will play PlayStation at home.

if else condition

Here there are two conditions will it rain or no rain and tasks are playing cricket or playing PlayStation.

Let’s take another example to get more clear. Suppose you are driving a car and you are late for the office. You don’t want to get late. So decide if there will be more traffic on road then you will take another route to avoid heavy traffic, more circumstances. Now you will take your real-time map to view traffic and take your decision accordingly.

Here are also two conditions traffic present or not and driving the same route or taking another route are tasks.

Arduino if statement

So from both of the examples, you will be clear what if else condition is. how we will see real-life project examples of if else conditions.

if else condition Example in Arduino

if else Arduino led
This image is created using fritzing

So we will look at one basic example of if & else conditions, using a push button and LED. we have connected one push button to know the current status if it is pressed or not. if the button pressed does some task or if the button is not pressed continue the previous task.

Here is a schematic of the circuit. We have connected the push button at pin number 8 of our Arduino board. We have given VCC 5v and GND to push the button.


Code -
int pushButton = 3;  // connect push button to pin 3 of Arduino
int ledpin=9;    // connect LED pin to pin 9 of Arduino
void setup()
 {
   pinMode(ledpin, OUTPUT); // declare LED as OUTPUT
   pinMode(pushButton, INPUT); // declare push button as INPUT
  Serial.begin(115200);        // Set baud rate of 115200
}
void loop() {
  int buttonState = digitalRead(pushButton);  // read the status of push button
  if(buttonState==HIGH)                      // check the condition if button presses or not
  {
   Serial.println("Button pressed");            // print the button status
   digitalWrite(ledpin,HIGH);   
}
   else if(buttonState==LOW)                // check the condition if button presses or not
   {
    Serial.println("Not pressed");     // print the button status
    digitalWrite(ledpin,LOW);       
}
  delay(100);                               // delay of 100 millisecond
}

Here we have declared a push button that is connected at pin number 3 of Arduino and led to pin 9. We have declared a baud rate of 115200 and push button pin as INPUT along with led pin as OUTPUT.

This is a void loop function the code inside it will repeat continuously again & again. So here we are continuously monitoring whether the button is pressed or not. If the button is pressed then the status of the pin connected to the button will be HIGH and Arduino will read value logic 1 which we will get our serial monitor and the LED will be turned ON. When the button is released pin status will change to LOW which will be read as logic 0 and the LED will be turned OFF.

ternary operator :

The conditional operator is also called a ternary operator. the ternary operator is the same as the if else condition but the only difference between the ternary operator and the if else condition is the simplicity of writing a code. ternary operator reduces the work of writing lengthy code.

condition? expression1(ifTrue) :  expression2(ifFalse)

Here the condition is compared with the expressions, if the expression1 is true then expression 1 condition is satisfied and expression 2 is ignored and if the condition is not satisfied then expression 1 will become ignored and expression 2 will be satisfied.

if ( Color == “Red” )
 {
  Serial.print(“red”);
 }
 else
 {
  Serial.print(“blue”);
 }


Is same as

Color == Red ?  Serial.print(“red”);  : Serial.print(“blue”);

Here first we check the condition if the value of the variable name Color is equal to red if it's red then the condition is satisfied and we can Serial.print(“red”) and if color is not red then the condition is not satisfied and we will Serial.print(“blue”).

Another Example of if else condition using LED and ultrasonic sensor

Arduino if else example

Code - 

int trigger = 8;    // Set trigger pin at Arduino pin 8
int echo = 9;       // Set echo pin at Arduino pin 9
int ref_signal;     // declare variable to store width of pulse
int distance;       // declare variable to calculate distance
int Ledpin = 10;
void setup() {
  Serial.begin(115200);      // set baud rate for Serial communication
  pinMode(trigger,OUTPUT);  // trigger pin set to output
  pinMode(echo,INPUT);      // echo pin set to output
pinMode(Ledpin ,OUTPUT); 
}
void loop() {
   digitalWrite(trigger, LOW);   // make trigger pin low-to-high-low to generate pulse of 10µs
   delayMicroseconds(2);
   digitalWrite(trigger,HIGH);
   delayMicroseconds(10);
   digitalWrite(trigger,LOW);
   ref_signal=pulseIn(echo,HIGH); // use pulse In function to calculate amount of time pulse was high 
  // Distance = speed x time 
  distance = (0.034*ref_signal)/2;     // speed of sound in cm/µs 
  
  // divide the equation by half because the time which we will get will be required to reach the object and get reflected back.
  
  Serial.print("Distance:");       // print the output 
  Serial.print(distance);      
  Serial.print("cm");  
  Serial.println(" ");
  delay(100);
if(distance < 10)
{
digitalWrite(Ledpin , HIGH);
}
else{
digitalWrite(Ledpin , LOW);
}
}

In this example of an ultrasonic sensor, here we are checking the distance provided by the ultrasonic sensor. Here we are applying conditions through the if statement. Here we are checking if the distance is less than < 10 then the condition will get satisfied and the LED will turn ON, if the condition is not satisfied means the distance is more than > 10 then the LED will turn OFF.

ternary operator Example in Arduino

We have simply replaced the if else condition in the above example with the ternary operator while the rest of the code is the same.

if(distance < 10)
{
digitalWrite(Ledpin , HIGH);
}
else{
digitalWrite(Ledpin , LOW);
}

using ternary operator -

distance < 10 ? digitalWrite(Ledpin,HIGH):digitalWrite(Ledpin,LOW);

Here we are checking the condition first if the distance is less than 10 if the distance is less than 10 then we will turn the LED ON using the digitalWrite() function and if the distance is greater than 10 then the LED will turn OFF.

int trigger = 8;    // Set trigger pin at Arduino pin 8
int echo = 9;       // Set echo pin at Arduino pin 9
int ref_signal;     // declare variable to store width of pulse
int distance;       // declare variable to calculate distance
int Ledpin = 10;
void setup() {
  Serial.begin(115200);      // set baud rate for Serial communication
  pinMode(trigger,OUTPUT);  // trigger pin set to output
  pinMode(echo,INPUT);      // echo pin set to output
pinMode(Ledpin ,OUTPUT); 
}
void loop() {
   digitalWrite(trigger, LOW);   // make trigger pin low-to-high-low to generate pulse of 10µs
   delayMicroseconds(2);
   digitalWrite(trigger,HIGH);
   delayMicroseconds(10);
   digitalWrite(trigger,LOW);
   ref_signal=pulseIn(echo,HIGH); // use pulse In function to calculate amount of time pulse was high 
  // Distance = speed x time 
  distance = (0.034*ref_signal)/2;     // speed of sound in cm/µs 
  
  // divide the equation by half because the time which we will get will be required to reach the object and get reflected back.
  
  Serial.print("Distance:");       // print the output 
  Serial.print(distance);      
  Serial.print("cm");  
  Serial.println(" ");
  delay(100);
distance < 10 ? digitalWrite(Ledpin,HIGH):digitalWrite(Ledpin,LOW);
}

Now we used the serial monitor to observe the output. . To open up the serial monitor click on Tools > Serial Monitor or use the shortcut (SHIFT + CONTROL + M). You can see output on the Serial monitor. when the distance is less than 10 then we will print "LED ON" and if the distance is greater than 10 then the LED will be OFF.


Conclusion – 

So in this blog, we learn about what if else condition is, how to use if else condition in Arduino, we see the application or use of if else condition through a push button and led also with another example with ultrasonic sensor and led. we also have seen the ternary operator, what is ternary operator, and how to use the ternary operator.

"I hope you find this IoT blog very helpful to you. In the upcoming lesson, we will see more about IoT sensors till then bye. See you all in my next blog."

Close Menu