Lesson 1 - Understanding bool and boolean in Arduino
Learn how true/false values help your ESP32 make simple decisions and remember small states like LED ON/OFF.
Progress indicator
Lesson 1 of 4
Learning Objectives
- Understand what a bool variable is in Arduino and ESP32 sketches.
- Learn that bool stores only two values: true and false.
- See how bool is used for LED state and button state in real hardware programs.
- Read a short Arduino code example and explain what each line does.
- Use the simulator to connect code values to visible hardware behavior.
Concept Explanation
What is bool in Arduino?
In Arduino (and ESP32 Arduino code), bool is a small variable type used to store a yes/no or on/off answer. You may also see boolean in older examples. In practice, beginners can think of both as a true/false type for simple logic.
What values can bool hold?
A bool can hold only two values: true or false. This makes it very easy to represent states like enabled/disabled, pressed/released, or LED on/off.
Why is bool useful in embedded systems?
Embedded systems like ESP32 projects often track many simple states. Using bool keeps your code readable and helps you avoid mistakes when checking conditions.
Real ESP32 example: LED state
A variable like bool ledState can remember whether the LED should be ON (true) or OFF (false).
Real ESP32 example: Button state
A variable like bool buttonPressed can store if a user is pressing a button right now, which helps control LEDs or menus.
Code Example
A simple `bool` variable is used to control the LED output.
bool ledState = true;
void setup() {
pinMode(2, OUTPUT);
digitalWrite(2, ledState);
}Code Explanation (Step-by-Step)
- The first line creates a bool variable named ledState and sets it to true, which means the LED should start ON.
- setup() runs one time when the ESP32 starts, so this code prepares the hardware at startup.
- pinMode(2, OUTPUT) tells the ESP32 that pin 2 will send a signal to control an LED.
- digitalWrite(2, ledState) writes the bool value to pin 2. Because ledState is true, the pin outputs HIGH and the LED turns on.
- If you change ledState to false, the LED would stay off when the board starts.
Try it now
Open the simulator and test how changing ledState affects the LED output.