Variables and data
What you’ll learn
- How to create and change variables
- Common Arduino data types and their limits
- Scope: where a variable can be used
- Why
constis useful
Variables
A variable is a named box for a value:
int speed = 150; // create it, starting at 150speed = 200; // change itspeed = speed + 10;Data types
| Type | Holds | Range on an UNO |
|---|---|---|
bool |
true / false | — |
int |
Whole numbers | −32,768 to 32,767 |
long |
Bigger whole numbers | about ±2.1 billion |
unsigned long |
Big non-negative numbers | 0 to about 4.3 billion; used for millis() |
float |
Decimals | about 6–7 significant digits |
char |
One character | ‘A’, ‘7’ |
String |
Text | “Hello” |
Scope
- Global variables (outside any function) keep their value and can be used everywhere.
- Local variables (inside a function) exist only while that function runs and start fresh each time.
Constants
const int MOTOR_PIN = 9; can’t be changed by accident. Use constants for pin numbers and settings, so you only change them in one place.
Example: global vs local
int laps = 0; // global: remembered between loops
void loop() { int reading = analogRead(A0); // local: fresh each loop if (reading < 200) laps++;}Example: integer division
int a = 7 / 2; // 3 (whole numbers drop the .5)float b = 7 / 2; // still 3.0! both sides are intsfloat c = 7.0 / 2; // 3.5Example: settings at the top
const int LEFT_MOTOR = 5;const int RIGHT_MOTOR = 6;const int CRUISE_SPEED = 180;const int STOP_DISTANCE = 20; // cmPick the typeEasy
Which type would you use for: a distance in cm with decimals; whether a button is pressed; the time from millis(); a lap counter?
float, bool, unsigned long, int.
Spot the overflowMedium
int start = millis(); works for a while, then the robot behaves strangely. Why, and what’s the fix?
After about 32.8 s millis() is bigger than an int can hold, so it overflows to a negative number. Use unsigned long start = millis();.
Average speedHard
A robot drove 237 cm in 4 s. Write code that prints the speed as a decimal in cm/s.
float speed = 237.0 / 4; Serial.println(speed); prints 59.25. Without the .0, integer division would give 59.
Quick check
Finished this lesson?