Download presentation
Presentation is loading. Please wait.
1
Arduino Programming: “if” statements
Mechanical and Materials Engineering Portland State University
2
Overview Motivation: The need for conditional execution “if” statement concepts Logical expressions Examples On-line reference:
3
Use case: Making decisions in programs
Build a system to maintain water level in a tank
4
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
5
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
6
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); }
7
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; }
8
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);
9
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]
10
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”); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.