Struct Resource for Arduino Author: Alexander Brevig Contact: alexanderbrevig@gmail.com
A structure type is a user-defined composite type. It is composed of fields or members that can have different types. In C++, a structure is the same as a class except that its members are public by default. MSDN
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.
struct RGB {
byte r;
byte g;
byte b;
};
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};
}
How can I use structs as function returntypes or as parameters to functions?
The usual arduino workaround/hack is to have all functions that requires custom datatstructures to be placed in an additional .h file. Just create a new tab in the IDE and give it a name.h then #include "name.h"
RGB getBlue(); //return RGB color = { 0 , 0 , 255 };
void displayRGB(RGB color); //could call an analogWrite on all member variables
| Part of AlphaBeta Resources. | |
| Last Modified: | August 08, 2011, at 06:49 AM |
| By: | Atalanttore |