▷ Structs in Arduino: Data Organization for Efficient Projects

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 sensor
struct Sensor {
  int pin;                      // Sensor pin
  float value;                  // Read value
  float threshold;                 // Activation threshold
  bool activated;                // Activation state
  unsigned 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 struct
structPoint{
  intx;
  inty;
  intz;
};

void setup() {
  Serial.begin(9600);

// Create an instance of the struct
  structPointorigin;

// Access the members of the struct
  origin.x = 0;
  origin.y = 0;
  origin.z = 0;

// Create and initialize in one line
  structPointdestination = { 10, 20, 5 };

// Display the values
  Serial.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 sensors
struct SensorData {
  int pin;
  float value;
  float threshold;
  bool activated;
  unsigned longlastReading;
};

// Create sensor array
const 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 pins
  for (int i = 0; i < NUM_SENSORS; i++) {
    pinMode(sensors[i].pin, INPUT);
  }

  Serial.println("Monitoring system initialized");
}

void loop() {
// Read all sensors
  for (int i = 0; i < NUM_SENSORS; i++) {
    readSensor(&sensors[i]); // Pass struct address
  }

// Show data
  showSensorData();

  delay(1000); // Wait 1 second between readings
}

// Function to read a sensor
void readSensor(structSensorData*sensor) {
// Read analog value and convert it to voltage
  sensor->value = analogRead(sensor->pin) * (5.0 / 1023.0);
  sensor->lastReading = millis();

// Check if it exceeds the threshold
  sensor->activated = (sensor->value > sensor->threshold);
}

// Function to display data from all sensors
void 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 started
  unsigned long duration = 0; // Configured timer duration in milliseconds

// Starts the timer with a specific duration
  void start(unsigned long durationTime) {
start = millis();
duration = durationTime;
  }

// Checks if the timer has already finished
  bool hasFinished() const {
    return (millis() - start) >= duration;
  }

// Restarts the timer from the current time
  void restart() {
start = millis();
  }
};

// -----------------------------------------------------------
// Global variables
// -----------------------------------------------------------
Timer myTimer; // Timer instance
const 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 output
  Serial.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 monitor
    Serial.print("LED ");
    Serial.println(ledState ? "ON" : "OFF");

// Restart the timer for another 3 seconds
    myTimer.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

  1. Group related data: Use structs to keep together data that belongs to the same concept.
  2. Pass by reference: When passing structs to functions, use references or pointers to avoid copying large amounts of data.
  3. Consider memory usage:Large structs can consume a lot of memory, which is important in Arduino with limited resources.
  4. Document your structs:Add comments to explain the purpose of each member of the struct.
  5. 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.

0/Leave a comment/Comments

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.