1

我需要在一些德州仪器 CC2530 节点之间发送一些浮点数。这种架构只能发送一个 uint8 数组。
我已经尝试做的是将带有强制转换的浮点指针分配给 uint8 指针。然后我发送这些字节,当接收到它们时,它们被复制到一个 uint8 数组中。最后,我创建了另一个浮点指针,该指针设置了先前创建的数组的强制转换。
实际上,这个技巧适用于我的电脑(使用 unsigned char 而不是 uint8),但不适用于接收到的数字始终为 0 的节点。

这是传输事件中使用的代码的一部分(它在那里创建msa_Data1,即传输的数据包,其中要发送的数字是valMed(全局变量)):

void Data_create(){
    uint8 *sends;
    sends = (uint8 *) &valMed;
    uint8 rec_index;
    for(rec_index=0; rec_index < sizeof(float); ++rec_index){
        msa_Data1[rec_index]= sends[rec_index];
    }
}

在接待部分,我有:

uint8 receiveds[sizeof(float)];
uint8 rec_index;
    for(rec_index=0; rec_index < sizeof(float); ++rec_index){
        receiveds[rec_index]= pData->dataInd.msdu.p[rec_index];
    }
float *received= (float *)receiveds;

来自传输的数据被接收到pData->dataInd.msdu.p[rec_index]

我在电脑上试过的传输模拟是:

main(){
    float send= -3.14;
    unsigned char *sends;
    sends = (unsigned char *)&send;
    printf("1:%d, 2:%d, 3:%d, 4:%d \nfloat sent:%f \n", sends[0], sends[1], sends[2], sends[3], send);
    unsigned char receiveds[sizeof(float)];
    int rec_index;
    for(rec_index=0; rec_index < sizeof(float); ++rec_index){
        receiveds[rec_index]= sends[rec_index];
    }
    float *received= (float *)receiveds;
    printf("float received:%f\n", *received);
} 

输出:

alex@aspire7738G ~/test $ ./test 
1:195, 2:245, 3:72, 4:192 
float sent:-3.140000 
float received:-3.140000

在这种情况下,我可以看到测试在 pc 上运行良好,但在节点上却没有。怎么了?

预先感谢您的任何帮助!

亚历克斯

4

2 回答 2

2

接收部分的代码有问题。您将字节复制到receiveds然后使用指针转换将其视为float. 但是,许多 C 实现对字符/字节类型(receiveds很可能)使用一字节对齐,对类型使用四字节对齐float。将uint8指针转换为float指针可能会导致指针对齐不正确。

相反,您可以这样做:

float received;
… // Code that prepares receiveds goes here.
memcpy(&received, receiveds, sizeof received);

此外,如果pData->dataInd.msdu.p是字节数组或指向字节的指针(charunsigned char或,可能,uint8并且uint8是 C 实现中的字符类型),那么您可以省略 usingreceiveds作为中间缓冲区,直接复制:

float received;
// Omit the code that copied into receiveds.
memcpy(&received, pData->dataInd.msdu.p, sizeof received);

如果这不能解决问题,请检查复制到发送缓冲区的实际字节和从接收缓冲区复制的字节,并确保它们相同。

于 2013-12-05T21:26:54.100 回答
1

为什么不使用定点表示您的数字?每当我使用 TI CC2530 时,我都试图避免浮点的开销,并采用定点表示数字。这些值在发送时更加直接,但您必须小心您的表示。

于 2013-12-05T22:30:31.500 回答