05. Operators & Decisions
Calculate, compare and select actions.
Learning outcomes
- Use arithmetic, comparison and Boolean operators
- Distinguish assignment from equality
- Write if, else if and else chains
- Combine conditions with AND, OR and NOT
Parts and preparation
Arduino Uno, two push buttons and onboard LED.
Before power: inspect wiring, confirm supply voltage and ensure all connected circuits share GND.
Arithmetic
+, -, , / and % calculate values. Integer division discards the remainder. Use a decimal operand such as 5.0 when a floating-point result is required.
Assignment and comparison
= stores a value. == compares equality. Other comparisons are !=, <, <=, > and >=.
Boolean logic
A && B requires both conditions. A || B requires either condition. !A reverses a condition. Parentheses make complex conditions easier to read.
Decision chains
Only the first true branch of an if / else if / else chain runs. Separate if statements are each tested independently.
Wiring and safe build sequence
- Button 1: D2 to GND
- Button 2: D3 to GND
- Use INPUT_PULLUP for both
- Use onboard LED as output
Worked sketch
Download .ino sketchconst byte buttonA = 2;
const byte buttonB = 3;
void setup() {
pinMode(buttonA, INPUT_PULLUP);
pinMode(buttonB, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
bool aPressed = digitalRead(buttonA) == LOW;
bool bPressed = digitalRead(buttonB) == LOW;
if (aPressed && bPressed) {
digitalWrite(LED_BUILTIN, HIGH);
} else if (aPressed || bPressed) {
digitalWrite(LED_BUILTIN, millis() / 250 % 2);
} else {
digitalWrite(LED_BUILTIN, LOW);
}
}How the code works
- Pressed is LOW because INPUT_PULLUP holds an open input HIGH.
- Both buttons give steady light; either button gives flashing light.
Test and record evidence
Practical evidence checklist
Common faults and checks
- If behavior is inverted, remember that pressed reads LOW.
- Check && versus || and == versus =.
Check your understanding
Q1. What is the difference between = and ==?
Show answer
= assigns; == compares.
Q2. When does A || B evaluate true?
Show answer
When A, B or both are true.