Reputation: 31
I´m trying to use struct with Arduino and I´m a beginner and I don´t know how to declare an array inside the struct and use it (int pin[5]
and int vecinos[6]
).
typedef struct
{
int id;
int pin[5];
int tiempoCero;
int tiempoApagado;
int estado;
int vecinos[6];
} zonas;
zonas zona[5];
Upvotes: 3
Views: 29339
Reputation: 6882
Your declaration is fine. However you need to understand that Arduino IDE automatically generates function prototypes for you. Unfortunately the IDE does a poor job. It sorts the generated prototypes to the top BEFORE the declarations. Thus you can not use them in any function definitions. Unless you prevent the IDE from auto generating the prototypes.
I found three ways to achieve this:
For small files my preferred solution is #1. Your sketch would then be
namespace whatever {
typedef struct
{
int id;
int pin[5];
int tiempoCero;
int tiempoApagado;
int estado;
int vecinos[6];
} zonas;
function example(zonas z) {
...
}
}
void setup() {
...
}
void loop() {
whatever::zonas z;
...
whatever::example(z);
}
For an extensive example look here.
Upvotes: 8
Reputation: 333
I would suggest avoiding the coding directly in the .ino files, unless it's really a few lines. For anything else, just create separate .h and .c/.cpp files. This will allow also to test all/part of the code by compiling and running on a PC.
Usually I have a simple project.cpp file to which i create a project.ino symlink. Then in a separate .cpp/.h pair of files I write all the code, including entry points to call from setup() and loop().
Upvotes: 3
Reputation: 976
The way you've declared it is fine. In order to access the pin array (and similarly for vecinos):
for (int i = 0; i < 5; i++) {
zona[0].pin[i] = i;
}
Upvotes: -1