3.0 Storing Information: Variables and Data Types
3.1 What is a Variable?
A variable is like a labeled box or a container where you can store a piece of information. This lets you save data, give it a name, and refer to it or change it later in your program. Before you can use a variable, you must declare it, which means giving it a specific data type and a unique name.
3.2 The Most Common “Flavors”: Essential Data Types
A data type tells the Arduino what kind of information a variable is designed to hold. This is important because an int is treated as a number you can do math with, while a char is treated as a letter, and the Arduino needs to know the difference to work correctly. For a beginner, there are four essential data types to know.
| Data Type | What It Stores | Example Declaration |
| int | Whole numbers (no decimals) | int counter = 0; |
| float | Numbers with a decimal point | float temperature = 21.5; |
| boolean | A state of either true or false | boolean ledState = true; |
| char | A single character (like a letter) | char myInitial = ‘A’; |
3.3 Where Variables “Live”: Understanding Scope
The scope of a variable determines where in your program it can be used.
- Global Variables: These are declared outside of all functions, usually at the top of your sketch. Think of them as a public announcement that any function in the program (setup(), loop(), etc.) can see and use.
- Local Variables: These are declared inside a function (like setup() or loop()). They are like a private note that can only be used by the code within that specific function.
This is why we often declare variables for pin numbers globally (at the top), so both setup() and loop() can use them.
Once you have data stored in variables, you need a way to work with and manipulate that data, which is where operators come in.