Arduino Programming: “if” statements Mechanical and Materials Engineering Portland State University http://me120.mme.pdx.edu/
Overview Motivation: The need for conditional execution “if” statement concepts Logical expressions Examples On-line reference: https://www.arduino.cc/reference/en/language/structure/control-structure/if/
Use case: Making decisions in programs Build a system to maintain water level in a tank
Use case: Making decisions in programs Build a system to maintain water level in a tank Arduino reads output from the level sensor If water level is low, open the supply valve An “if” statement is used to implement the decision
Logical statements control code execution “if” construct to make a single choice “if – else” construct to choose either/or if ( something is true ) { code block } if ( something is true ) { code block 1 } else { code block 2 } See http://arduino.cc/en/Reference/If http://arduino.cc/en/Reference/Else
Syntax of “if” construct “if” construct to make a single choice “something is true” must be a logical expression Example: if ( something is true ) { code block } Symbol Meaning < Is less than > Is greater than == Is equal to >= Is greater than or equal to <= Is less than or equal to != Is not equal to if ( x>0 ) { y = sqrt(x); }
Test your understanding What is the value of z? a. x = 2; y = 5; z = 0; if ( x < y ) { z = y – x; } c. x = 2; y = 5; z = 0; if ( (y-x)<= 3 ) { z = y/x; } b. x = 2; y = 5; z = 0; if ( x > y ) { z = y – x; } d. x = 2; y = 5; if ( (y-x)<= 3 ) { z = y/x; } else { z = 0.0; }
Example: Night light int LED_pin = 12; void setup() { pinMode(LED_pin, OUTPUT); } void loop() { int reading, sensor_pin=3, threshold = 150; reading = analogRead(sensor_pin); if ( reading < threshold ) { digitalWrite(LED_pin, HIGH); } else { digitalWrite(LED_pin, LOW);
Example: Night light int LED_pin = 12; void setup() { pinMode(LED_pin, OUTPUT); } void loop() { int reading, sensor_pin=3, threshold = 250; reading = analogRead(sensor_pin); if ( reading < threshold ) { digitalWrite(LED_pin, HIGH); } else { digitalWrite(LED_pin, LOW); analogRead returns a value in the range [0, 1023]
Compound “if-else-if” Implement a piecewise function Notice the error-handling for x<x1 and x>x4 if ( x<x1 ) { Serial.println(“Error: x<x1”); } else if ( x<x2 ) { y = ya; } else if ( x<x3 ) { y = yb; } else if ( x<x4 ) { y = yc; } else { Serial.println(“Error: x>x4”); }