Structs are a fundamental tool in programming that allows you to group related variables under a single name. In Arduino, structs are especially useful for organizing sensor data, configurations, and states in a logical and efficient manner.
What is a Struct?
A struct is a custom data type that groups several related variables, possibly of different types, under a single name. Think of it as a "box" that contains related information.
Basic definition of a Struct
// Define a struct to represent a sensorstruct Sensor {int pin; // Sensor pinfloat value; // Read valuefloat threshold; // Activation thresholdbool activated; // Activation stateunsigned long lastRead; // Time of the last reading};
Advantages of using Structs in Arduino
- Organization:Group related data logically
- Readability:The code becomes clearer and more understandable
- Maintainability:It is easier to modify and extend the code
- Data passing:You can pass complete groups of data to functions
- Reusability:You can create multiple instances of the same structure
How to use Structs in Arduino
Declaration and use of Structs
// Define the structstructPoint{intx;inty;intz;};void setup() {Serial.begin(9600);// Create an instance of the structstructPointorigin;// Access the members of the structorigin.x = 0;origin.y = 0;origin.z = 0;// Create and initialize in one linestructPointdestination = { 10, 20, 5 };// Display the valuesSerial.print("Origin: ");Serial.print(origin.x);Serial.print(", ");Serial.print(origin.and);Serial.print(", ");Serial.println(origin.z);Serial.print("Destination: ");Serial.print(destination.x);Serial.print(", ");Serial.print(destination.and);Serial.print(", ");Serial.println(destination.z);}void loop() {// The loop can be empty for this example}
Practical Example: Monitoring System with Multiple Sensors
Management of multiple sensors using Structs
// Define a struct for the sensorsstruct SensorData {int pin;float value;float threshold;bool activated;unsigned longlastReading;};// Create sensor arrayconst int NUM_SENSORS = 3;struct SensorData sensors[NUM_SENSORS] = {{ A0, 0.0, 2.5, false, 0 }, // Sensor 0{ A1, 0.0, 3.0, false, 0 }, // Sensor 1{ A2, 0.0, 2.0, false, 0 } // Sensor 2};void setup() {Serial.begin(9600);// Configure sensor pinsfor (int i = 0; i < NUM_SENSORS; i++) {pinMode(sensors[i].pin, INPUT);}Serial.println("Monitoring system initialized");}void loop() {// Read all sensorsfor (int i = 0; i < NUM_SENSORS; i++) {readSensor(&sensors[i]); // Pass struct address}// Show datashowSensorData();delay(1000); // Wait 1 second between readings}// Function to read a sensorvoid readSensor(structSensorData*sensor) {// Read analog value and convert it to voltagesensor->value = analogRead(sensor->pin) * (5.0 / 1023.0);sensor->lastReading = millis();// Check if it exceeds the thresholdsensor->activated = (sensor->value > sensor->threshold);}// Function to display data from all sensorsvoid showSensorData() {Serial.println("=== SENSOR DATA ===");for (int i = 0; i < NUM_SENSORS; i++) {Serial.print("Sensor ");Serial.print(i);Serial.print(": ");Serial.print(sensors[i].value);Serial.print("V - ");if (sensors[i].activated) {Serial.println("ENABLED");} else {Serial.println("Inactive");}}Serial.println();}
Structs with Member Functions
In C++ (and therefore in Arduino), structs can have member functions, similar to classes:
Struct with member functions
// -----------------------------------------------------------// Structure that defines a simple timer based on millis()// -----------------------------------------------------------struct Timer {unsigned long start = 0; // Stores the time when the timer startedunsigned long duration = 0; // Configured timer duration in milliseconds// Starts the timer with a specific durationvoid start(unsigned long durationTime) {start = millis();duration = durationTime;}// Checks if the timer has already finishedbool hasFinished() const {return (millis() - start) >= duration;}// Restarts the timer from the current timevoid restart() {start = millis();}};// -----------------------------------------------------------// Global variables// -----------------------------------------------------------Timer myTimer; // Timer instanceconst int ledPin = 13; // Pin where the LED is connected (pin 13 on Arduino UNO)bool ledState = false; // Current state of the LED (false = off, true = on)// -----------------------------------------------------------// Initial setup (runs once at startup)// -----------------------------------------------------------void setup() {pinMode(ledPin, OUTPUT); // Set the LED pin as outputSerial.begin(9600); // Start serial communication at 9600 baud// Start the timer with a duration of 3000 ms (3 seconds)myTimer.start(3000);Serial.println("Timer started for LED blinking");}// -----------------------------------------------------------// Main loop (runs repeatedly)// -----------------------------------------------------------void loop() {// If the timer finished (3 seconds have passed)if (myTimer.hasFinished()) {// Change the state of the LED (if it was off, it turns on, and vice versa)ledState = !ledState;digitalWrite(ledPin, ledState);// Display the new state on the serial monitorSerial.print("LED ");Serial.println(ledState ? "ON" : "OFF");// Restart the timer for another 3 secondsmyTimer.restart();}// Note:// Other tasks could be executed here without blocking the timer// For example: reading sensors, listening to buttons, handling communication, etc.}
Differences between Structs and Classes
In C++, structs and classes are very similar, but they have some key differences:
| Feature | Struct | Class |
|---|---|---|
| Default access | Public (public) |
Private (private) |
| Typical use | Simple data structures | Objects with complex behavior |
| Inheritance | Yes (but not recommended) | Yes (designed for it) |
| Polymorphism | Possible but not common | Designed for it |
💡 Tip: Use structs to group related data and classes when you need strong encapsulation, inheritance, or polymorphism. In Arduino, structs are perfect for organizing configuration data, states, and sensor readings.
Tips for using Structs in Arduino
- Group related data: Use structs to keep together data that belongs to the same concept.
- Pass by reference: When passing structs to functions, use references or pointers to avoid copying large amounts of data.
- Consider memory usage:Large structs can consume a lot of memory, which is important in Arduino with limited resources.
- Document your structs:Add comments to explain the purpose of each member of the struct.
- Use arrays of structs:To handle multiple instances of the same type of data (like multiple sensors).
Conclusion
Structs are a powerful tool in Arduino for organizing data logically and efficiently. They allow you to group related variables, improve code readability, and simplify data passing between functions.
Whether you are working with multiple sensors, managing complex configurations, or simply organizing related data, structs can make your code clearer, more maintainable, and efficient.
Post a Comment
Hello! We're so glad you've made it this far and are reading this article on Edeptec.
This form is an open space for you: you can leave a comment with your questions, suggestions, experiences, or simply your opinion on the topic discussed.
» Did you find the information helpful?
» Do you have any personal experiences you'd like to share?
» Do you have any topics you'd like to see covered in future articles?
Remember that this space is for learning and sharing, so we encourage you to participate respectfully and constructively. Your comments can help other readers who are on the same path, whether in electronics, programming, sports, or technology.
Thank you for being part of this learning community! Your participation is what makes this project grow.