Code Along - Chapter 3

Operators & Decisions

Compare readings, combine conditions and choose what the sketch does with if, else if and switch.

Estimated time 75-100 minExercises passed 0 / 8

Comparing values

A comparison is either true or false. C++ has six comparison operators: == (equal), != (not equal), <, <=, > and >=.

An if statement runs its block only when the condition is true. else gives the other path. Watch out: a single = stores a value, a double == compares two values.

Decision flow where only the first true branch of an if chain runs
Only the first true branch of an if / else if chain runs.
Worked example

Deciding with if and else

Change temperature to 20 and press Run again to see the other branch.

int temperature = 28;

void setup() {
  Serial.begin(9600);
  if (temperature > 25) {
    Serial.println("Fan ON");
  } else {
    Serial.println("Fan OFF");
  }
}

void loop() {
}

Turn on JavaScript to edit, run and test this code in the browser.

Expected output
Fan ON
Exercise 3.1

Above the threshold?

Not started

reading is a value from analogRead(), between 0 and 1023. Print the reading, then HIGH if it is 512 or more and LOW if it is below 512 - exactly as in the sample.

Sample output
Reading 700: HIGH
int reading = 700;

void setup() {
  Serial.begin(9600);
  // Print: Reading 700: HIGH

}

void loop() {
}

Turn on JavaScript to edit, run and test this code in the browser.

Exercise 3.2

Even or odd pulse count

Not started

A counter has recorded pulses pulses. Print whether that count is even or odd, as in the sample. A number is even when dividing by 2 leaves no remainder - use %.

Sample output
7 pulses: odd
int pulses = 7;

void setup() {
  Serial.begin(9600);
  // Print: 7 pulses: odd

}

void loop() {
}

Turn on JavaScript to edit, run and test this code in the browser.

Exercise 3.3

Battery level bands

Not started

Turn a battery voltage into a status word:

  • 4.00 V or more: Full
  • 3.60 to 3.99 V: Good
  • 3.30 to 3.59 V: Low
  • below 3.30 V: Critical

Print it like the sample, using an if / else if / else chain.

Sample output
3.70 V: Good
float volts = 3.7;

void setup() {
  Serial.begin(9600);
  // Print: 3.70 V: Good

}

void loop() {
}

Turn on JavaScript to edit, run and test this code in the browser.

Combining conditions

  • && (AND) is true only when both sides are true.
  • || (OR) is true when at least one side is true.
  • ! (NOT) flips true and false.

Brackets make mixed conditions clear: (a && b) || c.

Worked example

AND, OR and NOT

Predict the output before you press Run. Then change alarmArmed to true.

bool doorOpen = true;
bool alarmArmed = false;
int lightLevel = 120;

void setup() {
  Serial.begin(9600);
  if (doorOpen && alarmArmed) {
    Serial.println("ALARM!");
  } else if (doorOpen || lightLevel < 200) {
    Serial.println("Check the room");
  } else {
    Serial.println("All quiet");
  }
  if (!alarmArmed) {
    Serial.println("Alarm is not armed");
  }
}

void loop() {
}

Turn on JavaScript to edit, run and test this code in the browser.

Expected output
Check the room
Alarm is not armed
Exercise 3.4

Pump interlock

Not started

A pump may only run when its switch is on and the tank is not yet full. Print Pump running when both are true, and Pump stopped otherwise.

Sample output
Pump running
bool pumpSwitch = true;
bool tankFull = false;

void setup() {
  Serial.begin(9600);
  // Print: Pump running   or   Pump stopped

}

void loop() {
}

Turn on JavaScript to edit, run and test this code in the browser.

Exercise 3.5

Thermostat with a dead band

Not started

A heater should not click on and off every time the temperature wobbles. Use these rules:

  • below 18 °C: switch the heater on
  • above 22 °C: switch the heater off
  • from 18 to 22 °C: leave heaterOn as it is

Update heaterOn, then print the temperature and the heater state like the sample.

Sample output
17.50 C: heater ON
float temperature = 17.5;
bool heaterOn = false;

void setup() {
  Serial.begin(9600);
  // Apply the rules to heaterOn


  // Print: 17.50 C: heater ON

}

void loop() {
}

Turn on JavaScript to edit, run and test this code in the browser.

Exercise 3.6

Fix the = bug

Not started

This sketch always reports five presses - and it even changes the count! Find the bug and fix it. Read the compiler warning: it points straight at the problem.

Sample output
Not five presses
buttonPresses = 3
int buttonPresses = 3;

void setup() {
  Serial.begin(9600);
  if (buttonPresses = 5) {
    Serial.println("Five presses - resetting");
  } else {
    Serial.println("Not five presses");
  }
  Serial.print("buttonPresses = ");
  Serial.println(buttonPresses);
}

void loop() {
}

Turn on JavaScript to edit, run and test this code in the browser.

Worked example

Choosing with switch

switch compares one whole number or character with several fixed values. break ends each case; default catches everything else.

char command = 'G';

void setup() {
  Serial.begin(9600);
  switch (command) {
    case 'R':
      Serial.println("Red");
      break;
    case 'G':
      Serial.println("Green");
      break;
    default:
      Serial.println("Unknown command");
  }
}

void loop() {
}

Turn on JavaScript to edit, run and test this code in the browser.

Expected output
Green
Exercise 3.7

Mode selector

Not started

A rotary switch sets mode: 1 is Manual, 2 is Auto, 3 is Test. Anything else is Unknown. Print the mode with a switch, exactly as in the sample.

Sample output
Mode 2: Auto
int mode = 2;

void setup() {
  Serial.begin(9600);
  Serial.print("Mode ");
  Serial.print(mode);
  Serial.print(": ");
  // switch on mode and print its name

}

void loop() {
}

Turn on JavaScript to edit, run and test this code in the browser.

Exercise 3.8

Is the supply within tolerance?

DeeperNot started

A 5 V supply is acceptable while it stays within 5 % of 5.00 V. Work out the allowed range from nominal, then print whether measured is inside it, as in the sample.

Work it out - the tests change both values.

Sample output
4.85 V: inside tolerance
float measured = 4.85;
float nominal = 5.0;

void setup() {
  Serial.begin(9600);
  // Work out 5% of nominal, then compare


  // Print: 4.85 V: inside tolerance

}

void loop() {
}

Turn on JavaScript to edit, run and test this code in the browser.

Try it on a real Uno

Download Above the threshold?, replace the fixed reading with int reading = analogRead(A0); inside loop(), add delay(500); and upload it with a potentiometer on A0. Turn the knob and watch HIGH and LOW swap over as you pass the middle.