简体   繁体   English

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

[英]Arduino: union/struct attribute returns the wrong value

I'm trying to use a union and struct to represent a 32-bit signal that is going to be sent via a 433Mhz radio transmitter. 我正在尝试使用union和struct来表示将通过433Mhz无线电发射器发送的32位信号。 I have a problem with getting the Arduino to store the 26-bit remote id on the signal.parts.remote attribute. 我有一个问题,让Arduino将26位远程id存储在signal.parts.remote属性上。 When I fetch the value after setting it to 23607301 (decimal) I get 14341 (decimal) instead. 当我将其设置为23607301(十进制)后取值时,我得到14341(十进制)。 How should I construct this union to have it return the correct value? 我应该如何构建此联合以使其返回正确的值?

Signal.h 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 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() 
{
}

Output (from Arduino): 输出(来自Arduino):

Unit: 2
Should be: 2

Status: 1
Should be: 1

Remote: 14341
Should be: 23607301

Data: 1110000000010100110010
Should be: 01011010000011100000000101110010

This is a follow up question on Arduino: cannot pass union struct as pointer ac I can with gcc compiler 这是关于Arduino的一个后续问题:不能将union struct作为指针ac传递给gcc编译器

I suspect the issue has to do with the fact that unsigned (aka unsigned int ) is 16 bits wide. 我怀疑这个问题与unsigned (aka unsigned int )是16位宽的事实有关。 Try changing the remote field to unsigned long : 尝试将remote字段更改为unsigned long

unsigned long remote :26;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM