Arduino的:能不能通过工会结构作为指针的交流,我可以用gcc编译器(Arduino: cann

2019-10-19 04:39发布

我试图使用结构与Arduino的,但不能传递结构指针与函数调用。 添加的主要功能和编译我的电脑用gcc但与Arduino的IDE我得到的错误时,一切工作正常。

我试过的代码是:

typedef union
{
    struct
    {
        unsigned unit   :2;
        unsigned channel:2;
        unsigned status :1;
        unsigned group  :1;
        unsigned remote :26;
    };
    unsigned long data;
} Signal;

Signal signal;

void testPassingStruct(Signal *variable)
{
    variable->status = 1;
}

void setup()
{
    signal.status = 1;
    testPassingStruct(&signal);
}

void loop()
{
}

而错误的是:

structtest:2: error: variable or field ‘testPassingStruct’ declared void
structtest:2: error: ‘Signal’ was not declared in this scope
structtest:2: error: ‘variable’ was not declared in this scope

Answer 1:

你有几个未命名的项目。 这种情况与typedef秒。 你可以试试,

union sig_union
{
    struct
    {
        unsigned unit   :2;
        unsigned channel:2;
        unsigned status :1;
        unsigned group  :1;
        unsigned remote :26;
    } d;                       /* Note the name here. */
    unsigned long data;
} signal;
typedef union sig_union Signal;

然后在你的代码,你需要,

void testPassingStruct(Signal *variable)
{
    variable->d.status = 1;
}

您也可以使用蒙版和位字段定义。 通常,它使什么位的控制是哪里清晰,编译器会在两种情况下,类似的代码。 例如,

#define SIG_UNIT(d)    (d&0x3)
#define SIG_CHANNEL(d) (d&0xc>>2)
#define SIG_STATUS(d)  (d&0x10)
/* etc. */

特别是随着系统编程,位没关系,这是更好的,因为我不相信“C”位字段指定它们是如何放置。 最重要的是,我相信它会编译。



Answer 2:

它基本上是工会和缺乏名称为结构成员的(我把它叫做部分在下面的代码)。 尝试这个

union Signal
{
    struct
    {
        unsigned unit   :2;
        unsigned channel:2;
        unsigned status :1;
        unsigned group  :1;
        unsigned remote :26;
    } parts;
    unsigned long data;
};

union Signal signal;

void testPassingStruct(union Signal *variable)
{
    variable->parts.status = 1;
}

void setup()
{
    signal.parts.status = 1;
    testPassingStruct(&signal);
}

void loop()
{
}


文章来源: Arduino: cannot pass union struct as pointer ac I can with gcc compiler