C语言 使用 Arduino 自定义枚举类型声明
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17796344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom enum type declaration with Arduino
提问by Logan Williams
I'm having some trouble using a custom enum type in Arduino.
我在 Arduino 中使用自定义枚举类型时遇到了一些问题。
I've read elsewherethat 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)
我在其他地方读到过,由于 Arduino IDE 预处理,自定义类型声明需要使用头文件。所以,我已经这样做了,但我仍然无法使用我的自定义类型。这是我的主要 arduino 文件 (beacon.ino) 中代码的相关部分
#include <beacon.h>
State state;
And in beacon.h:
在信标.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?
我认为我编写或包含头文件的方式有问题。但是什么?
回答by mpflaga
beacon.h should be as follows:
beacon.h 应如下所示:
/* 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.
当您在主 INO 文件中实例化它时,将 typdef 放在外面,并关闭“状态”的尾随实例,或者反之亦然。上述beacon.h文件需要在用户目录.\Arduino\libraries\beacon\目录中,IDE需要重新启动以缓存其位置。
But you could just define it and instance it all at once in the INO
但是你可以定义它并在 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.
这里实例与枚举分开,允许枚举单独是一个 typedef。上面是一个实例而不是 typedef。

