Scale-N

Scale-N

Arduino

Componenten

Rollend Materieel

Naslag

Onderdelen

Wissels

Basis Electronica

Symbols Electronica

Programming Arduino

DCC++

DR5000

Products

Link

Stats













































Programming Arduino - struct

A structure type is a user-defined composite type. It is composed of fields or members that can have different types. It enables the programmer to create a variable that structures a selected set of data.
For instance, it might be useful to have a struct that represents a RGB value. Being a RGB variable always consists of three other variables a struct is the correct datatype.

Declaration

Creation and usage
RGB variable = { 255 , 0 , 0 };
if (variable.r == 255 && variable.g == 0 && variable.b == 0){
//red detected, go black
variable.r = 0;
}
else if (variable.r == 0 && variable.g == 255 && variable.b == 0){
// green detected, go purple
// Rather than changing each members of the struct one
// at a time, you can create a new instance of the struct:
variable = (RGB){255, 0, 255};
}

Passing struct to a function.
You can use the struct as parameter or the pointer to the struct as parameter.
  • Struct as a parameter.
    void SetWithoutPointer(RGB rgb);
    Access 'b'in the struct rgb: rgb.b = 255;
  • Pointer
    void SetWithPointer(RGB* rgb)
    Syntax for a pointer is the '*'
    Access 'g'in the struct rgb: rgb->g = 255;
struct RGB {
byte r;
byte g;
byte b;
};
void setup() {
RGB variable = { 255, 0, 0};
Serial.begin(9600);
Serial.println("Start test struct");
Serial.print("R: ");
Serial.println(variable.r);
Serial.print("G: ");
Serial.println(variable.g);
Serial.print("B: ");
Serial.println(variable.b);
SetWithoutPointer(variable);
Serial.println("");
Serial.println("Variable after SetWithoutPointer");
Serial.print("R: ");
Serial.println(variable.r);
Serial.print("G: ");
Serial.println(variable.g);
Serial.print("B: ");
Serial.println(variable.b);
SetWithPointer(&variable);
Serial.println("");
Serial.println("Variable after SetWithPointer");
Serial.print("R: ");
Serial.println(variable.r);
Serial.print("G: ");
Serial.println(variable.g);
Serial.print("B: ");
Serial.println(variable.b);
}
void loop() {
}
void SetWithPointer(RGB* rgb)
{
rgb->g = 255;
Serial.println("");
Serial.println("Variable in SetWithPointer");
Serial.print("R: ");
Serial.println(rgb->r);
Serial.print("G: ");
Serial.println(rgb->g);
Serial.print("B: ");
Serial.println(rgb->b);
}
void SetWithoutPointer(RGB rgb)
{
rgb.b = 255;
Serial.println("");
Serial.println("Variable in SetWithoutPointer");
Serial.print("R: ");
Serial.println(rgb.r);
Serial.print("G: ");
Serial.println(rgb.g);
Serial.print("B: ");
Serial.println(rgb.b);
}

Output:


Initialize a struct:
RGB variable = { 255 , 0 , 0 };

Clear a struct:
memset(&variable, 0, sizeof(variable)) ;

ref: arduino