gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:05:28 25 4
gpt4 key购买 nike

我正在尝试使用 union 和结构来表示将通过 433Mhz radio 发射器发送的 32 位信号。我在让 Arduino 将 26 位远程 ID 存储在 signal.parts.remote 属性上时遇到问题。当我将其设置为 23607301(十进制)后获取该值时,我得到的是 14341(十进制)。我应该如何构建这个 union 才能让它返回正确的值?

信号.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;

结构测试.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 的后续问题

最佳答案

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

unsigned long remote :26;

关于c - Arduino:union/struct 属性返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21065615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com