3

Lesson 3: Variables & Data Types

Learn to store and manipulate data in your Arduino programs

32-Lesson Course • Semester 1

Learning Objectives

By the end of this Lesson, you will:

  • Understand different Arduino data types
  • Declare and use variables effectively
  • Perform mathematical operations
  • Handle user input and sensor data

Skills Developed:

  • Data type selection and optimization
  • Variable naming conventions
  • Mathematical calculations
  • Data conversion techniques

Section 1: Understanding Data Types

What Are Data Types?

Data types tell the Arduino what kind of information you're storing and how much memory to use. Choosing the right data type is important for efficient programming and avoiding errors.

Why Data Types Matter:

  • Memory Efficiency: Different types use different amounts of memory
  • Range Limits: Each type can hold different ranges of values
  • Operations: Some operations only work with specific types
  • Precision: Decimal numbers need special handling

Common Arduino Data Types

Integer Types (Whole Numbers)

  • int: -32,768 to 32,767 (most common)
  • byte: 0 to 255 (small positive numbers)
  • long: -2 billion to 2 billion (large numbers)
  • unsigned int: 0 to 65,535 (positive only)

Other Important Types

  • float: Decimal numbers (3.14, -2.5)
  • bool: True or false values
  • char: Single characters ('A', '5', '!')
  • String: Text messages ("Hello World")

Data Type Examples

// Integer examples
int temperature = 25;           // Room temperature
byte ledBrightness = 128;       // LED brightness (0-255)
long milliseconds = 1234567;    // Large time value
unsigned int sensorReading = 1023;  // Sensor value (always positive)

// Decimal examples
float voltage = 3.3;            // Precise voltage reading
float pi = 3.14159;             // Mathematical constant

// Boolean examples
bool ledState = true;           // LED is on
bool buttonPressed = false;     // Button is not pressed

// Character and String examples
char grade = 'A';               // Single letter grade
String robotName = "miniAuto";  // Robot's name
String message = "Hello, World!";  // Text message

// Special Arduino types
unsigned long currentTime = millis();  // Time since startup

Section 2: Working with Variables

Variable Declaration and Initialization

Variables are containers that store data values. You need to declare them before use and can initialize them with starting values.

Variable Syntax:

// Basic syntax: dataType variableName = initialValue;

// Declaration only (value is undefined)
int counter;
float temperature;
bool isRunning;

// Declaration with initialization (recommended)
int ledPin = 13;                    // Pin number for LED
float sensorVoltage = 0.0;          // Starting voltage
bool systemReady = false;           // System status
String deviceName = "Arduino";      // Device identifier

// Multiple variables of same type
int redPin = 9, greenPin = 10, bluePin = 11;
float x = 0.0, y = 0.0, z = 0.0;

// Constants (values that never change)
const int BUTTON_PIN = 2;           // Pin number (won't change)
const float MAX_VOLTAGE = 5.0;      // Maximum voltage
const String DEVICE_ID = "ROBOT_001";  // Device identifier

Variable Naming Best Practices

✅ Good Naming Practices

  • • Use descriptive names: buttonPin
  • • Use camelCase: sensorValue
  • • Constants in CAPS: MAX_SPEED
  • • Be consistent throughout your code
  • • Avoid abbreviations: temperature not temp

❌ Poor Naming Practices

  • • Single letters: x, y, z
  • • Numbers only: var1, var2
  • • Reserved words: int, void
  • • Spaces or special chars: my var
  • • Confusing names: data, stuff

Variable Scope and Lifetime

Understanding where variables can be used (scope) and how long they exist (lifetime) is crucial for effective programming.

// Global variables (declared outside functions)
int globalCounter = 0;        // Available everywhere in the program
String robotStatus = "Ready"; // Can be used in setup() and loop()

void setup() {
  // Local variables (declared inside functions)
  int setupCounter = 0;       // Only available inside setup()
  Serial.begin(9600);
  
  // Can access global variables
  globalCounter = 10;
  Serial.println(robotStatus);
  
  // setupCounter goes away when setup() ends
}

void loop() {
  // Local variables in loop()
  int loopCounter = 0;        // Only available inside loop()
  
  // Can access global variables
  globalCounter++;
  
  // Cannot access setupCounter here - it doesn't exist!
  // setupCounter++; // This would cause an error
  
  // Block scope example
  if (globalCounter > 5) {
    int blockVariable = 100;  // Only exists inside this if block
    Serial.println(blockVariable);
  }
  // blockVariable doesn't exist here
  
  delay(1000);
}

Section 3: Mathematical Operations

Basic Arithmetic Operators

Arduino supports all standard mathematical operations. Understanding these is essential for calculations involving sensors, timing, and control logic.

Basic Operators

  • + Addition: 5 + 3 = 8
  • - Subtraction: 10 - 4 = 6
  • * Multiplication: 6 * 7 = 42
  • / Division: 15 / 3 = 5
  • % Modulo (remainder): 17 % 5 = 2

Assignment Operators

  • = Assign: x = 10
  • += Add and assign: x += 5
  • -= Subtract and assign: x -= 3
  • *= Multiply and assign: x *= 2
  • /= Divide and assign: x /= 4
// Mathematical operations examples
int a = 10;
int b = 3;
int result;

// Basic arithmetic
result = a + b;        // result = 13
result = a - b;        // result = 7
result = a * b;        // result = 30
result = a / b;        // result = 3 (integer division!)
result = a % b;        // result = 1 (remainder)

// Assignment operators
int counter = 0;
counter += 5;          // counter = 5 (same as counter = counter + 5)
counter -= 2;          // counter = 3
counter *= 4;          // counter = 12
counter /= 3;          // counter = 4

// Increment and decrement
counter++;             // counter = 5 (add 1)
counter--;             // counter = 4 (subtract 1)
++counter;             // counter = 5 (pre-increment)
--counter;             // counter = 4 (pre-decrement)

// Working with floats for precise division
float voltage = 3.3;
float current = 0.02;
float resistance = voltage / current;  // resistance = 165.0

// Converting between types
int sensorValue = 512;
float percentage = (float)sensorValue / 1023.0 * 100.0;  // Convert to percentage

Practical Math Examples

/*
  Practical Mathematical Operations
  Real-world examples for robotics and sensor applications
*/

void setup() {
  Serial.begin(9600);
  Serial.println("=== Mathematical Operations Demo ===");
  
  // Example 1: Converting sensor readings to voltage
  int sensorReading = 512;      // Raw ADC value (0-1023)
  float voltage = sensorReading * (5.0 / 1023.0);  // Convert to voltage
  Serial.print("Sensor reading: ");
  Serial.print(sensorReading);
  Serial.print(" = ");
  Serial.print(voltage);
  Serial.println(" volts");
  
  // Example 2: Calculating LED brightness percentage
  int brightness = 128;         // PWM value (0-255)
  float percentage = (brightness / 255.0) * 100.0;
  Serial.print("LED brightness: ");
  Serial.print(percentage);
  Serial.println("%");
  
  // Example 3: Distance calculation from time
  long duration = 2000;         // Microseconds from ultrasonic sensor
  float distance = (duration * 0.034) / 2;  // Convert to centimeters
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  
  // Example 4: Temperature conversion
  float celsius = 25.0;
  float fahrenheit = (celsius * 9.0 / 5.0) + 32.0;
  Serial.print(celsius);
  Serial.print("°C = ");
  Serial.print(fahrenheit);
  Serial.println("°F");
}

void loop() {
  // Example 5: Cycling through values with modulo
  static int counter = 0;
  
  int ledValue = (counter % 256);  // Cycles 0-255 repeatedly
  Serial.print("Counter: ");
  Serial.print(counter);
  Serial.print(", LED value: ");
  Serial.println(ledValue);
  
  counter++;
  delay(500);
}

Section 4: Hands-On Activity

🛠️ Activity: Build a Personal Data Logger

Create a program that collects, processes, and displays data using different variable types and mathematical operations!

Activity Instructions

Step 1: Choose Your Data Theme

Pick one theme for your data logger:

  • Environmental Monitor: Track temperature, humidity, light levels
  • Activity Tracker: Count steps, calculate distance, track time
  • System Monitor: Track uptime, memory usage, performance metrics
  • Game Statistics: Score tracking, level progression, achievements
  • Your Choice: Any data collection theme that interests you

Step 2: Plan Your Variables

Your program must include:

  • At least 3 different data types (int, float, bool, String)
  • At least 2 mathematical calculations
  • At least 1 constant value
  • Meaningful variable names following best practices
  • Both global and local variables

Step 3: Required Features

  • Display current values every 2 seconds
  • Calculate and show averages or totals
  • Include percentage calculations
  • Show data in different units (e.g., Celsius and Fahrenheit)
  • Use Serial Monitor for clear, formatted output

💡 Programming Challenges

  • Beginner: Create a simple counter with percentage display
  • Intermediate: Add multiple data types and calculations
  • Advanced: Include data validation and error handling
  • Expert: Create a menu system to view different statistics

Section 5: Assessment & Homework

📝 This Lesson's Quiz

Test your understanding of variables, data types, and mathematical operations.

Quiz Topics:

  • • Data type selection and memory usage
  • • Variable declaration and initialization
  • • Scope and lifetime concepts
  • • Mathematical operators and expressions
  • • Type conversion and casting

🏠 Homework Assignment

Practice variable usage and mathematical operations with these exercises.

Assignment Tasks:

  1. Complete your personal data logger from the hands-on activity
  2. Create a temperature conversion program (C ↔ F ↔ K)
  3. Build a simple calculator using Serial input
  4. Write a program that finds the average of 10 sensor readings
  5. Bonus: Create a unit converter (inches/cm, pounds/kg, etc.)

📋 Submission Guidelines

  • • Use appropriate data types for each variable
  • • Include comments explaining your variable choices
  • • Test all mathematical calculations with known values
  • • Demonstrate proper variable naming conventions
  • • Show examples of both global and local variable usage