Custom enum type declaration with Arduino

ⅰ亾dé卋堺 提交于 2019-12-13 05:23:51

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/17796344/custom-enum-type-declaration-with-arduino

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!