Comparison operators are used to compare different data types such as integers, floating-point numbers, characters, and even strings in Arduino programming. They play a crucial role in conditional statements and loops, allowing you to control the flow of your code based on specific conditions.
Comparison or Relational Operators
In Arduino programming, comparison operators allow us to compare two values and evaluate whether a particular condition is true or false. These operators are often used within conditional statements like if, else if, and while loops.
There are 6 relational operators in Arduino IDE:
Relational Operators | Example |
---|---|
Greater than (>) | a > b (true if a is greater than b) |
Less than (<) | a < b (true if a is less than b) |
Greater than or equal to (>=) | a >= b (true if a is greater than or equal to b) |
Less than or equal to (<=) | a <= b (true if a is less than or equal to b) |
Equal to (==) | a == b (true if a equals b) |
Not equal to (!=) | a!= b (true if a is not equal to b) |
Equality Operator (==)
The equality operator (==) checks whether two values are equal. If the values are indeed equal, the condition evaluates to true; otherwise, it evaluates to false.
Example,
void setup() {
int temperature = 25;
if (temperature == 25) {
// Execute specific actions when the temperature is 25
}
}
void loop() {
}
Inequality Operator (!=)
The inequality operator (!=) checks if two values are not equal. It evaluates to true if the values are different and false if they are the same.
Example,
void setup() {
int distance = 100;
if (distance != 0) {
// Execute specific actions when the distance is not zero
}
}
void loop() {
}
Greater Than Operator (>)
The greater than operator (>) compares two values and returns true if the left operand is greater than the right operand. Otherwise, it returns false.
Example,
void setup() {
int score = 85;
if (score > 70) {
// Execute specific actions when the score is greater than 70
}
}
void loop() {
}
Less Than Operator (<)
The less than operator (<) checks if the left operand is less than the right operand. If true, it returns true; otherwise, it returns false.
Example,
void setup() {
int score = 85;
if (score < 90) {
// Execute specific actions when the score is less than 90
}
}
void loop() {
}
Greater Than or Equal To Operator (>=)
The greater than or equal to operator (>=) evaluates to true if the left operand is greater than or equal to the right operand. Otherwise, it returns false.
Example,
void setup() {
int age = 18;
if (age >= 18) {
// Execute specific actions when the person is 18 years old or older
}
}
void loop() {
}
Less Than or Equal To Operator (<=)
The less than or equal to operator (<=) checks whether the left operand is less than or equal to the right operand. If true, it returns true; otherwise, it returns false.
Example,
void setup() {
int quantity = 5;
if (quantity <= 10) {
// Execute specific actions when the quantity is less than or equal to 10
}
}
void loop() {
}
Let’s see some Arduino code to understand the use of relational operators.
Example 1
Here is an Arduino program that reads and compares two analog input values and depending on the comparison results, we’ll control an LED to turn on or off.
const int analogPin1 = A0; // Analog input pin 1
const int analogPin2 = A1; // Analog input pin 2
const int ledPin = 13; // LED connected to digital pin 13
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
// Read analog values from the two input pins
int value1 = analogRead(analogPin1);
int value2 = analogRead(analogPin2);
// Print the values to the serial monitor
Serial.print("Analog Value 1: ");
Serial.print(value1);
Serial.print(" Analog Value 2: ");
Serial.println(value2);
// Compare the two analog values using different operators
if (value1 > value2) {
digitalWrite(ledPin, HIGH); // Turn on the LED if value1 is greater
Serial.println("LED ON");
} else {
digitalWrite(ledPin, LOW); // Turn off the LED if value2 is greater or equal
Serial.println("LED OFF");
}
delay(1000); // Delay for a second before the next comparison
}
Explanation of Code
In this program, we define two analog input pins (A0 and A1) to read analog values from external sensors. We also define a digital output pin (13) to control an LED using below lines of code :
const int analogPin1 = A0; // Analog input pin 1
const int analogPin2 = A1; // Analog input pin 2
const int ledPin = 13; // LED connected to digital pin 13
In the setup() function, we set the LED pin as an output and initialize serial communication for debugging purposes.
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
The loop() function repeatedly reads the analog values from the two input pins and prints them to the serial monitor.
It then compares value1 and value2 using the greater than (>) operator. If value1 is greater than value2, it turns on the LED and prints “LED ON” to the serial monitor. Otherwise, it turns off the LED and prints “LED OFF“.
Finally, there’s a delay of 1 second between each comparison to make it easier to observe the LED’s behavior.
void loop() {
// Read analog values from the two input pins
int value1 = analogRead(analogPin1);
int value2 = analogRead(analogPin2);
// Print the values to the serial monitor
Serial.print("Analog Value 1: ");
Serial.print(value1);
Serial.print(" Analog Value 2: ");
Serial.println(value2);
// Compare the two analog values using different operators
if (value1 > value2) {
digitalWrite(ledPin, HIGH); // Turn on the LED if value1 is greater
Serial.println("LED ON");
} else {
digitalWrite(ledPin, LOW); // Turn off the LED if value2 is greater or equal
Serial.println("LED OFF");
}
delay(1000); // Delay for a second before the next comparison
}
Example 2
An Arduino program that compares three integers and checks which one is the greatest.
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Define the three integers
int num1 = 10;
int num2 = 25;
int num3 = 15;
// Print the values of the integers
Serial.print("num1: ");
Serial.println(num1);
Serial.print("num2: ");
Serial.println(num2);
Serial.print("num3: ");
Serial.println(num3);
// Compare the integers and find the greatest
int greatest = num1;
if (num2 > greatest) {
greatest = num2;
}
if (num3 > greatest) {
greatest = num3;
}
// Print the greatest integer
Serial.print("The greatest integer is: ");
Serial.println(greatest);
}
void loop() {
// Nothing to do here
}
Explanation of Code
This program is completely written inside the setup() function.
Firstly, we define three integers num1, num2, and num3 with some initial values and print them on the Serial terminal using below lines of code:
// Initialize serial communication
Serial.begin(9600);
// Define the three integers
int num1 = 10;
int num2 = 25;
int num3 = 15;
// Print the values of the integers
Serial.print("num1: ");
Serial.println(num1);
Serial.print("num2: ");
Serial.println(num2);
Serial.print("num3: ");
Serial.println(num3);
Then we use the if statements to compare these integers and find the greatest among them. We initialize a variable greatest to num1 and then use the “>” operator to check if num2 and num3 are greater than the current value of greatest. If they are, we update the greatest accordingly.
// Compare the integers and find the greatest
int greatest = num1;
if (num2 > greatest) {
greatest = num2;
}
if (num3 > greatest) {
greatest = num3;
}
Finally, we print the value of the greatest integer to the serial monitor.
// Print the greatest integer
Serial.print("The greatest integer is: ");
Serial.println(greatest);
Example 3:
An Arduino program that allows you to input marks for five subjects for a student and then calculates the total marks and assigns a grade based on the total marks.
const int numSubjects = 5; // Number of subjects
int marks[numSubjects]; // Array to store marks
int totalMarks = 0; // Variable to store total marks
char grade; // Variable to store the grade
void setup() {
Serial.begin(9600);
// Input marks for each subject
for (int i = 0; i < numSubjects; i++) {
Serial.print("Enter marks for subject ");
Serial.print(i + 1);
Serial.print(": ");
while (!Serial.available()) {
// Wait for input
}
marks[i] = Serial.parseInt(); // Read integer from serial monitor
Serial.println(marks[i]);
}
// Calculate total marks
for (int i = 0; i < numSubjects; i++) {
totalMarks += marks[i];
}
// Determine grade based on total marks
if (totalMarks >= 90) {
grade = 'A';
} else if (totalMarks >= 80) {
grade = 'B';
} else if (totalMarks >= 70) {
grade = 'C';
} else if (totalMarks >= 60) {
grade = 'D';
} else {
grade = 'F';
}
// Display total marks and grade
Serial.print("Total marks: ");
Serial.println(totalMarks);
Serial.print("Grade: ");
Serial.println(grade);
}
void loop() {
// Nothing to do here
}
Explanation of Code
This program is completely written inside setup() function.
Firstly we define an array marks to store the marks for each subject, a variable totalMarks to store the total marks, and a grade variable to store the calculated grade. Using below lines of code:
const int numSubjects = 5; // Number of subjects
int marks[numSubjects]; // Array to store marks
int totalMarks = 0; // Variable to store total marks
char grade; // Variable to store the grade
Inside the setup() function, we use a for loop to input marks for each subject from the serial monitor. The user is prompted to enter marks for each subject, and the program waits for the user’s input.
Serial.begin(9600);
// Input marks for each subject
for (int i = 0; i < numSubjects; i++) {
Serial.print("Enter marks for subject ");
Serial.print(i + 1);
Serial.print(": ");
while (!Serial.available()) {
// Wait for input
}
marks[i] = Serial.parseInt(); // Read integer from serial monitor
Serial.println(marks[i]);
}
After reading all the marks, we calculate the total marks by summing up the values in the marks array.
// Calculate total marks
for (int i = 0; i < numSubjects; i++) {
totalMarks += marks[i];
}
We then use a series of if and else if statements to determine the grade based on the total marks. In this example, we use a simple grading scale with letter grades (A, B, C, D, and F) based on the total marks.
// Determine grade based on total marks
if (totalMarks >= 90) {
grade = 'A';
} else if (totalMarks >= 80) {
grade = 'B';
} else if (totalMarks >= 70) {
grade = 'C';
} else if (totalMarks >= 60) {
grade = 'D';
} else {
grade = 'F';
}
Finally, we display the total marks and the calculated grade on the serial monitor.
// Display total marks and grade
Serial.print("Total marks: ");
Serial.println(totalMarks);
Serial.print("Grade: ");
Serial.println(grade);
In this tutorial, we discussed the six relational operators available in the Arduino IDE. We can use these operators to compare two values and get a boolean (true or false) result. Ready to use these relational operators in your own projects?