30 Days Lost in Space → Help Center

Coding Concepts

Variables & Data Types

How to store and work with data in Arduino. Learn about int, float, bool, char, and String, the building blocks of every program.

What is a Variable?

A variable is a named container that holds a value in your program's memory. You can change the value, read it, and use it in calculations.

Declaring Variables

int myNumber = 42;        // Declaration + initialization
int anotherNumber;        // Declaration only (value is 0)
anotherNumber = 100;      // Assignment

Common Data Types

| Type | Size | Range | Use For | |------|------|-------|---------| | int | 2 bytes | -32,768 to 32,767 | Pin numbers, counters | | long | 4 bytes | ±2 billion | millis() values, big numbers | | float | 4 bytes | ±3.4e38 | Decimal numbers, math | | bool | 1 byte | true/false | On/off states, flags | | char | 1 byte | Single character | Letters, ASCII codes | | byte | 1 byte | 0-255 | Raw data, small numbers | | String | varies | Text | Display messages |

Choosing the Right Type

  • Pin numbers: int or const int
  • analogRead values: int (0-1023)
  • millis() timing: unsigned long
  • LED state: bool
  • PWM values: int or byte (0-255)
  • Temperature: float

Constants

Use const for values that never change:

const int LED_PIN = 13;       // Can't be modified later
const float PI_VAL = 3.14159;

Or use #define (preprocessor macro):

#define LED_PIN 13    // Replaced before compilation

Scope

  • Global variables (outside functions): Accessible everywhere
  • Local variables (inside functions): Only accessible in that function