Home ArduinoArduino Tutorials Tutorial: Arduino Variables and Constants

Tutorial: Arduino Variables and Constants

by shedboy71

Variables and constants are fundamental building blocks of Arduino programming. They allow you to store, modify, and access data throughout your program.

This tutorial introduces variables and constants, their types, how to declare them, and their practical applications.

Table of Contents

1. What Are Variables and Constants?

  • Variables: Storage locations in memory with a name, type, and value that can change during program execution.
  • Constants: Fixed values that do not change throughout the program’s execution.

2. Types of Variables

2.1 Integer (int)

  • Used to store whole numbers.
  • Range: -32,768 to 32,767 (16-bit on Arduino).

Example: Declaring and Using an Integer

void setup() {
  Serial.begin(9600);

  int count = 5;  // Declare and initialize an integer
  Serial.println(count);  // Print the value of count
}

void loop() {
  // Empty
}

2.2 Floating Point (float)

  • Used to store decimal numbers.
  • Precision: Up to 6-7 digits.

Example: Storing and Using a Float

void setup() {
  Serial.begin(9600);

  float pi = 3.14159;  // Declare and initialize a float
  Serial.println(pi);  // Print the value of pi
}

void loop() {
  // Empty
}

2.3 Character (char)

  • Used to store a single character or small integer (1 byte).
  • Range: -128 to 127.

Example: Using char Variables

void setup() {
  Serial.begin(9600);

  char letter = 'A';  // Declare and initialize a character
  Serial.println(letter);  // Print the character
}

void loop() {
  // Empty
}

2.4 Boolean (bool)

  • Used to store true or false.
  • Values: true (1) or false (0).

Example: Using a Boolean

void setup() {
  Serial.begin(9600);

  bool isOn = true;  // Declare a boolean
  if (isOn) {
    Serial.println("The device is ON.");
  } else {
    Serial.println("The device is OFF.");
  }
}

void loop() {
  // Empty
}

2.5 String (String)

  • Used to store sequences of characters.
  • Example: Names, messages.

Example: Using a String

void setup() {
  Serial.begin(9600);

  String message = "Hello, Arduino!";  // Declare a string
  Serial.println(message);  // Print the string
}

void loop() {
  // Empty
}

3. Constants in Arduino

Constants are defined using the const keyword or #define preprocessor directive.

Using const

  • Preferred method for type-safe constants.

Example: Declaring Constants

void setup() {
  const int ledPin = 13;  // Declare a constant
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, HIGH);  // Turn on LED
}

void loop() {
  // Empty
}

Using #define

  • Preprocessor directive (not type-safe).

Example: Defining Constants

#define LED_PIN 13

void setup() {
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);  // Turn on LED
}

void loop() {
  // Empty
}

4. Variable Scope

4.1 Local Variables

  • Declared inside a function or block.
  • Accessible only within the scope in which they are declared.

Example: Local Variable

void setup() {
  int localVar = 10;  // Local variable
  Serial.begin(9600);
  Serial.println(localVar);  // Accessible here
}

void loop() {
  // localVar is not accessible here
}

4.2 Global Variables

  • Declared outside any function.
  • Accessible throughout the program.

Example: Global Variable

int globalVar = 20;  // Global variable

void setup() {
  Serial.begin(9600);
  Serial.println(globalVar);  // Accessible here
}

void loop() {
  Serial.println(globalVar);  // Accessible here
}

5. Examples of Variables and Constants

Example 5.1: Blink LED Using a Constant

const int ledPin = 13;

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  digitalWrite(ledPin, HIGH);  // Turn LED on
  delay(1000);                 // Wait 1 second
  digitalWrite(ledPin, LOW);   // Turn LED off
  delay(1000);                 // Wait 1 second
}

Example 5.2: Reading Sensor Value into a Variable

const int sensorPin = A0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  int sensorValue = analogRead(sensorPin);  // Read sensor value
  Serial.println(sensorValue);             // Print the value
  delay(500);
}

Example 5.3: Using Multiple Data Types

void setup() {
  Serial.begin(9600);

  int count = 10;          // Integer
  float voltage = 3.3;     // Float
  char grade = 'A';        // Character
  bool isActive = true;    // Boolean
  String message = "Done"; // String

  Serial.println(count);
  Serial.println(voltage);
  Serial.println(grade);
  Serial.println(isActive);
  Serial.println(message);
}

void loop() {
  // Empty
}

Example 5.4: Toggle LED with Button Using a Boolean

const int buttonPin = 2;
const int ledPin = 13;

bool ledState = false;

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  if (digitalRead(buttonPin) == HIGH) {
    ledState = !ledState;         // Toggle LED state
    digitalWrite(ledPin, ledState);
    delay(500);                   // Debounce delay
  }
}

6. Best Practices for Using Variables and Constants

  1. Use Descriptive Names:
    • Choose meaningful names to improve code readability.
    int temperatureSensorPin = A0; // Good
    int ts = A0;                   // Avoid short names
    
  2. Use Constants for Fixed Values:
    • Replace magic numbers with constants for clarity and maintainability.
    const int MAX_SPEED = 255;
    
  3. Minimize Global Variables:
    • Prefer local variables when possible to avoid unexpected behavior.
  4. Initialize Variables:
    • Always initialize variables before use to prevent undefined behavior.
    int counter = 0; // Initialize
    
  5. Optimize Memory Usage:
    • Use the smallest data type that fits your needs (e.g., byte instead of int).

Conclusion

Variables and constants are crucial for storing and managing data in Arduino programs. By understanding their types, scope, and usage, you can write efficient and maintainable code.

This tutorial covers the fundamentals, along with practical examples to help you get started with Arduino programming.

For more details, visit the official Arduino reference.

You may also like