I'm having some trouble using a custom enum type in Arduino.
I've read elsewhere that using a header file is necessary for custom type declarations, due to Arduino IDE preprocessing. So, I've done that, but I'm still unable to use my custom type. Here's the relevant portions of my code in my main arduino file (beacon.ino)
#include <beacon.h>
State state;
And in beacon.h:
typedef enum {
menu,
output_on,
val_edit
} State;
But, when I try to compile, I get the following error:
beacon:20: error: 'State' does not name a type
I assume something is wrong about the way I have written or included my header file. But what?
beacon.h should be as follows:
/* filename: .\Arduino\libraries\beacon\beacon.h */
typedef enum State{ // <-- the use of typedef is optional
menu,
output_on,
val_edit
};
with
/* filename: .\Arduino\beacon\beacon.ino */
#include <beacon.h>
State state; // <-- the actual instance
void setup()
{
state = menu;
}
void loop()
{
state = val_edit;
}
Leave the typdef's out and either the trailing instance of "state" off as you are instancing it in the main INO file, or vice verse. Where the above beacon.h file needs to be in users directory .\Arduino\libraries\beacon\ directory and the IDE needs to be restarted to cache its location.
But you could just define it and instance it all at once in the INO
/* filename: .\Arduino\beacon\beacon.ino */
enum State{
menu,
output_on,
val_edit
} state; // <-- the actual instance, so can't be a typedef
void setup()
{
state = menu;
}
void loop()
{
state = val_edit;
}
Both compile fine.
You can also use the following:
/* filename: .\Arduino\beacon\beacon2.ino */
typedef enum State{ // <-- the use of typedef is optional.
menu,
output_on,
val_edit
};
State state; // <-- the actual instance
void setup()
{
state = menu;
}
void loop()
{
state = val_edit;
}
here the instance is separate from the enum, allowing the enum to be solely a typedef. Where above it is a instance and not typedef.