Arduino:union / struct属性返回错误的值

时间:2014-01-11 17:41:27

标签: c memory struct arduino unions

我正在尝试使用union和struct来表示将通过433Mhz无线电发射器发送的32位信号。我有一个问题,让Arduino将26位远程id存储在signal.parts.remote属性上。当我将其设置为23607301(十进制)后取值时,我得到14341(十进制)。我应该如何构造这个联合以使它返回正确的值?

SIGNAL.H

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

typedef union signal_union Signal;

structtest.ino

#include "Signal.h"

Signal signal1;
Signal signal2;

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

    Serial.print("Unit: ");
    Serial.println(variable->parts.unit);
    Serial.println("Should be: 2");
    Serial.println("");
    Serial.print("Status: ");
    Serial.println(variable->parts.status);
    Serial.println("Should be: 1");
    Serial.println("");
    Serial.print("Remote: ");
    Serial.println(variable->parts.remote);
    Serial.println("Should be: 23607301");
    Serial.println("");
    Serial.print("Data: ");
    Serial.println(variable->data, BIN);
    Serial.println("Should be: 01011010000011100000000101110010");
    Serial.println("");
}

void setup() 
{
    Serial.begin(115200);

    signal1.parts.remote = 23607301;
    signal1.parts.unit = 2;
    signal1.parts.group = 1;
    testPassingStruct(&signal1);
}

void loop() 
{
}

输出(来自Arduino):

Unit: 2
Should be: 2

Status: 1
Should be: 1

Remote: 14341
Should be: 23607301

Data: 1110000000010100110010
Should be: 01011010000011100000000101110010

这是关于Arduino: cannot pass union struct as pointer ac I can with gcc compiler

的后续问题

1 个答案:

答案 0 :(得分:3)

我怀疑这个问题与unsigned(又名unsigned int)16位宽的事实有关。尝试将remote字段更改为unsigned long

unsigned long remote :26;