If Statement


Step 1 - Build the Project

If Statement Hookup: Only Maker Board required.

Topics Covered:

 

The 'if' statement puts a branch into your code. It allows you to run a certain part of the code only when a condition is true. 

Step 2 - Upload the Code

/* * Learning examples: If * * LED on when the button is pressed, off otherwise */ void setup() { pinMode(13,OUTPUT); //LED pinMode(8,INPUT_PULLUP); //Button } void loop() { if (digitalRead(8) == HIGH){ //If button is not pressed digitalWrite(13,LOW); //Turn the LED off } if (digitalRead(8) == LOW){ //If button is pressed digitalWrite(13,HIGH); //Turn the LED on } } // (c) 2016 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Step 3 - Read the Walkthrough

The "if" statement tests a condition and, if that condition is true, some code statements will run. If the condition is false, the 'if' statement is passed over.

You can create an “if” statement by itself or you can use it along with other “if” statements, “else if” statements, and “else” statements.

When you use an “else if” statement, its condition is checked only when the “if” statement before it is false.

When you use an “else” statement, it will always run when the “if” statement right before it is false. You cannot use “else if” and “else” without first using “if”.