3

Lesson 3: Calculations with Variables

Use variables to do math, convert values, and print useful results

32-Lesson Course • Semester 1

Use Wokwi for this lesson's experiments so you can practice variables, calculations, and Serial Monitor output before dealing with physical wiring.

Learning Objectives

By the end of this Lesson, you will:

  • Review the most useful variable types from Lesson 2
  • Use variables in arithmetic calculations
  • Convert one value into another using formulas
  • Print calculation results clearly in the Serial Monitor

Skills Developed:

  • Choosing simple, appropriate variable types
  • Writing readable arithmetic expressions
  • Tracing how values change step by step
  • Displaying results for debugging and checking work

Section 1: A Quick Review of Variables

What should you remember from Lesson 2?

Lesson 2 already introduced variables and some basic types. In this lesson, we will use those ideas instead of starting over from the beginning.

The main ideas to keep in mind:

  • Variables store values: You give a name to a piece of data
  • Different types store different kinds of data: whole numbers, decimals, letters, and true/false
  • Good names help: temperature is clearer than x
  • We can change variable values: that is what makes calculations possible

Most useful types for now

Whole numbers and decimals

  • int: whole numbers like 0, 7, or 100
  • float: decimal numbers like 3.14 or 22.5
  • byte: small positive values like brightness from 0 to 255
  • const int: a whole number that should not change

Other basic types

  • bool: true or false values
  • char: a single character like 'A'
  • String: text like "Hello"
  • You do not need every type yet: for many early programs, int and float are enough

Small review example

// Integer examples
int temperature = 25;           // Room temperature
byte ledBrightness = 128;       // LED brightness (0-255)

// Decimal examples
float voltage = 3.3;            // Precise voltage reading

// 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 message = "Hello, World!";  // Text message

// A constant
const int maxScore = 10;

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

Section 3: Mathematical Operations

Basic Arithmetic Operators

Arduino supports all standard mathematical operations. Understanding these is essential for calculations involving counters, conversions, 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)

// 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

void setup() {
  Serial.begin(9600);
  Serial.println("=== Variable Math Demo ===");

  // Example 1: 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");

  // Example 2: Percentage calculation
  int score = 8;
  int total = 10;
  float percentage = (score / 10.0) * 100.0;
  Serial.print("Score: ");
  Serial.print(score);
  Serial.print("/");
  Serial.print(total);
  Serial.print(" = ");
  Serial.print(percentage);
  Serial.println("%");
}

void loop() {
}

Section 4: Hands-On Activity

🛠️ Activity: Build a Simple Calculator Program

Create a small Arduino program that uses variables to calculate and print useful results.

Activity Instructions

Step 1: Choose one calculation theme

Pick one simple program idea:

  • Temperature Converter: Convert Celsius to Fahrenheit
  • Score Calculator: Turn points into a percentage
  • Distance Tracker: Add lap distances together
  • Budget Helper: Add prices and calculate total cost
  • Your Choice: Any simple calculation with 2 or 3 variables

Step 2: Plan your variables

Your program should include:

  • At least 2 variables
  • At least 1 calculation using +, -, *, or /
  • Clear variable names
  • At least 1 line of Serial output that explains the result
  • An int or float, depending on the problem

Step 3: Required features

  • Print the starting values
  • Print the calculated result
  • Use Serial.print() and Serial.println() to make the output readable
  • Add at least one comment to explain part of the code
  • Test the program by changing one value and observing the new result

💡 Programming Challenges

  • Beginner: Convert one temperature from Celsius to Fahrenheit
  • Intermediate: Calculate both total and percentage
  • Advanced: Use a constant like const int totalPoints = 10;
  • Extra Challenge: Make the program repeat in loop() with changing values

Section 5: Assessment & Homework

📝 This Lesson's Quiz

Test your understanding of variables in calculations and clear Serial output.

Quiz Topics:

  • • Choosing between int and float
  • • Writing arithmetic expressions
  • • Understanding percentages and conversions
  • • Reading calculation code
  • • Printing results clearly

🏠 Homework Assignment

Practice using variables in small, readable Arduino math programs.

Assignment Tasks:

  1. Complete your simple calculator program from the hands-on activity
  2. Create one temperature conversion program
  3. Create one score-to-percentage program
  4. Write clear Serial output that explains each answer
  5. Bonus: Change one program to use a constant value

📋 Submission Guidelines

  • • Use appropriate variable types for the numbers in your program
  • • Include comments explaining what the program calculates
  • • Test each calculation with values you can check by hand
  • • Use descriptive variable names
  • • Make the Serial output easy for someone else to read