我在 Arduino 中使用自定义枚举类型时遇到了一些问题。
我读过 elsewhere由于 Arduino IDE 预处理,自定义类型声明需要使用头文件。所以,我已经做到了,但我仍然无法使用我的自定义类型。这是我的主要 arduino 文件 (beacon.ino) 中代码的相关部分
#include <beacon.h>
State state;
在 beacon.h 中:
typedef enum {
menu,
output_on,
val_edit
} State;
但是,当我尝试编译时,出现以下错误:
beacon:20: error: 'State' does not name a type
我假设我编写或包含头文件的方式有问题。但是什么?
最佳答案
beacon.h应该如下:
/* filename: .\Arduino\libraries\beacon\beacon.h */
typedef enum State{ // <-- the use of typedef is optional
menu,
output_on,
val_edit
};
与
/* filename: .\Arduino\beacon\beacon.ino */
#include <beacon.h>
State state; // <-- the actual instance
void setup()
{
state = menu;
}
void loop()
{
state = val_edit;
}
在主 INO 文件中实例化它时,将 typdef 保留在外面,并关闭尾随的“state”实例,反之亦然。其中上面的beacon.h文件需要在用户目录.\Arduino\libraries\beacon\目录下,需要重启IDE来缓存它的位置。
但是您可以在 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;
}
两者都编译得很好。
您还可以使用以下内容:
/* 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;
}
这里的实例与枚举是分开的,允许枚举仅仅是一个类型定义。上面是一个实例而不是 typedef。
关于使用 Arduino 的自定义枚举类型声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17796344/