How to Use Struct in Arduino: Simple Guide with Examples
In Arduino, use
struct to group related variables under one name, making your code organized and easier to manage. Define a struct with the struct keyword, then create variables of that type to store multiple related values together.Syntax
A struct groups different variables into one named type. You start with the struct keyword, give it a name, then list variables inside curly braces. After defining it, you can create variables of this new type.
- struct: keyword to define a structure
- Name: the name of your struct type
- Members: variables inside the struct, can be different types
- Variable: create a variable of the struct type to hold data
arduino
struct SensorData {
int temperature;
int humidity;
bool isActive;
};
SensorData sensor1; // variable of type SensorDataExample
This example shows how to define a struct for sensor data, assign values, and print them to the Serial Monitor.
arduino
#include <Arduino.h>
struct SensorData {
int temperature;
int humidity;
bool isActive;
};
SensorData sensor1;
void setup() {
Serial.begin(9600);
sensor1.temperature = 25;
sensor1.humidity = 60;
sensor1.isActive = true;
Serial.print("Temperature: ");
Serial.println(sensor1.temperature);
Serial.print("Humidity: ");
Serial.println(sensor1.humidity);
Serial.print("Active: ");
Serial.println(sensor1.isActive ? "Yes" : "No");
}
void loop() {
// Nothing here
}Output
Temperature: 25
Humidity: 60
Active: Yes
Common Pitfalls
Common mistakes when using struct in Arduino include:
- Forgetting the semicolon
;after the struct definition. - Not initializing struct variables before use, which can cause unexpected values.
- Confusing the struct type name with variable names.
- Trying to print a whole struct directly instead of its members.
arduino
/* Wrong: Missing semicolon after struct definition */ struct Data { int x; int y; }; // <-- Missing semicolon was here /* Right: */ struct Data { int x; int y; };
Quick Reference
- Define a struct with
struct Name { members }; - Create variables of that struct type to hold grouped data
- Access members with dot notation, e.g.,
variable.member - Always end struct definitions with a semicolon
- Initialize members before use to avoid garbage values
Key Takeaways
Use
struct to group related variables under one name for better organization.Always end your
struct definition with a semicolon.Access struct members using dot notation like
myStruct.member.Initialize struct variables before using their values to avoid unexpected results.
You cannot print a whole struct directly; print each member separately.