1. Introduction & Objectives
Welcome to your first lab! The goal of this lab is to apply the C++ programming concepts you've learned to a practical Arduino project. You will build a simple calculator that takes input from the computer via the Serial Monitor and performs basic arithmetic operations (+, -, *, /).
The most important part of this lab is not just making the calculator work, but structuring your code in a modular way. This means separating your code into logical files: a main sketch file, a header file for declarations, and a source file for implementations. This is a fundamental practice in professional software development.
Learning Objectives:
- Reinforce understanding of C++ variables, operators, and conditional statements (
if/else,switch). - Learn to use the Arduino Serial Monitor for two-way communication (sending and receiving data).
- Understand and implement a modular program using a header file (
.h) and a source file (.cpp). - Practice writing and calling custom functions.
- Implement basic error handling (e.g., for division by zero).
2. Required Materials
- Hardware: Arduino Uno R3, USB A-to-B cable
- Software: Arduino IDE (version 1.8.x or 2.x)
3. Pre-Lab Preparation
Before you begin the lab, please make sure you have done the following:
- Review your lecture notes from Weeks 4-7, focusing on:
- Header files (
.h) and source files (.cpp) - Functions (declaration vs. definition)
- Serial communication (
Serial.begin(),Serial.print(),Serial.read(),Serial.parseFloat()) - Conditional logic (
if-elseandswitch-case)
- Header files (
- Ensure your Arduino IDE is installed and you can successfully upload the basic
Blinksketch to your Arduino Uno.
4. Lab Procedure
Follow these steps carefully to build your project.
Part A: Project Setup - Creating the Files
In the Arduino IDE, a project (or "sketch") can be composed of multiple files, which appear as tabs. We will create three files for our project.
- Open the Arduino IDE and save the new, empty sketch. Name it
Lab1_Calculator. This creates a file namedLab1_Calculator.ino. - Create the header file. Click the downward arrow on the right side of the tab bar and select "New Tab".
- Name the new file
calculator.hand click OK. -
Create the source file. Repeat the process: click the "New Tab" button, name the new file
calculator.cpp, and click OK.
You should now have three tabs in your IDE: Lab1_Calculator.ino, calculator.h, and calculator.cpp.
.ino: The main sketch file. Contains the requiredsetup()andloop()functions..h: The header file. Contains function declarations (prototypes) and pre-processor directives. It tells the rest of the program what functions are available in your module..cpp: The source or implementation file. Contains the function definitions (the actual code that runs).
Part B: The Header File (calculator.h)
The header file declares the functions that our calculator module will provide. It acts like a public menu of our module's capabilities.
Copy the following code into your calculator.h file.
// This is the start of a "header guard". It prevents the file from being included more than once,
// which can cause compilation errors. The name CALCULATOR_H should be unique to this project.
#ifndef CALCULATOR_H
#define CALCULATOR_H
// Function Declarations (Prototypes)
// These tell the compiler that these functions exist, what parameters they take,
// and what type of value they return. The actual code is in calculator.cpp.
// Function to add two numbers
float add(float a, float b);
// Function to subtract two numbers
float subtract(float a, float b);
// Function to multiply two numbers
float multiply(float a, float b);
// Function to divide two numbers
float divide(float a, float b);
#endif // This ends the header guard.
Part C: The Implementation File (calculator.cpp)
This is where we write the actual logic for the functions we declared in the header file.
Copy the following code into your calculator.cpp file. Your task is to complete the logic inside each function.
// We must include Arduino.h to use standard Arduino types and functions.
#include
// We include our own header file to link the declarations to these definitions.
#include "calculator.h"
// Function Definitions
float add(float a, float b) {
// TODO: Return the sum of a and b.
return a + b;
}
float subtract(float a, float b) {
// TODO: Return the result of a minus b.
return a - b;
}
float multiply(float a, float b) {
// TODO: Return the product of a and b.
return a * b;
}
float divide(float a, float b) {
// We must handle division by zero, as it's an invalid operation.
if (b == 0) {
Serial.println("Error: Division by zero!");
return 0; // Return 0 or another indicator of an error.
} else {
// TODO: Return the result of a divided by b.
return a / b;
}
}
Part D: The Main Sketch (Lab1_Calculator.ino)
This is the main entry point of our program. It will handle user interaction through the Serial Monitor and call the functions from our calculator module.
25 * 4. The Serial.parseFloat() function is perfect for this. It reads numbers from the serial buffer and stops when it encounters a non-numeric character (like '+', '-', '*', '/'). We can then read that character separately.
Copy the following code into your Lab1_Calculator.ino file.
// Include our custom calculator header file.
// Use "" for local project files and <> for system/library files.
#include "calculator.h"
void setup() {
// Initialize serial communication at 9600 bits per second.
Serial.begin(9600);
// Wait for the serial port to connect. Needed for native USB port only.
while (!Serial);
Serial.println("Arduino Calculator is ready!");
Serial.println("Enter a calculation in the format: number operator number");
Serial.println("For example: 10.5 + 5");
Serial.println("------------------------------------");
}
void loop() {
// Check if there is data available to read from the serial port.
if (Serial.available() > 0) {
// 1. Read the first number.
// parseFloat() reads digits until it finds a non-digit character.
float num1 = Serial.parseFloat();
// 2. Read the operator.
// We need to skip any whitespace between the number and the operator.
char op = ' ';
while (Serial.available() > 0) {
char c = Serial.read();
if (c == '+' || c == '-' || c == '*' || c == '/') {
op = c;
break; // Found the operator, exit the loop.
}
}
// 3. Read the second number.
float num2 = Serial.parseFloat();
float result = 0;
bool validOperation = true;
// 4. Use a switch statement to perform the correct operation.
switch (op) {
case '+':
result = add(num1, num2);
break;
case '-':
result = subtract(num1, num2);
break;
case '*':
result = multiply(num1, num2);
break;
case '/':
result = divide(num1, num2);
break;
default:
Serial.println("Invalid operator. Please use +, -, *, or /");
validOperation = false;
break;
}
// 5. Print the result if the operation was valid.
if (validOperation) {
Serial.print("Result: ");
Serial.print(num1);
Serial.print(" ");
Serial.print(op);
Serial.print(" ");
Serial.print(num2);
Serial.print(" = ");
Serial.println(result);
}
Serial.println("------------------------------------");
// Clear any remaining characters from the input buffer
while(Serial.available() > 0) {
Serial.read();
}
}
}
Part E: Testing Your Calculator
- Verify and upload the sketch to your Arduino Uno.
- Open the Serial Monitor (Tools -> Serial Monitor or Ctrl+Shift+M).
- Make sure the baud rate is set to 9600 baud in the bottom-right corner of the Serial Monitor.
- In the input box at the top, type a calculation like
15 + 30and press Enter. - The Arduino should print the result.
- Test all four operations (+, -, *, /). Be sure to test the division by zero case (e.g.,
100 / 0).
Your Serial Monitor output should look something like this:
Arduino Calculator is ready!
Enter a calculation in the format: number operator number
For example: 10.5 + 5
------------------------------------
Result: 15.00 + 30.00 = 45.00
------------------------------------
Result: 100.00 / 4.00 = 25.00
------------------------------------
Error: Division by zero!
Result: 100.00 / 0.00 = 0.00
------------------------------------
5. Submission Requirements
To receive credit for this lab, you must submit the following:
- A single
.zipfile containing your three project files:Lab1_Calculator.inocalculator.hcalculator.cpp
- A screenshot of your Serial Monitor showing successful calculations for all four operations, including a test for division by zero.