我必须通过SPI将混合类型数组(union)从一个uController(源)传输到另一个uController(target),因此我必须在传输之前将整个传输块放入uint8_t数组中,然后在其中重建将uC返回到混合类型联合数组。
我尝试了以下方法,但是没有用。 (简体)
int i;
int len=4;
union dummy{
float f32;
uint32_t u32;
uint8_t u8[4];
};
union dummy inst1[len]; //First instance on source uC
union dummy inst2[len]; //Second instance on target uC
inst1[0].u8[0]=73;
inst1[1].f32=17.5;
//... and so on
printf("Source: %d, %f\n",inst1[0].u8[0],inst1[1].f32);
//Prepare SPI uint8_t array
uint8_t spi_arr[4*len];
*spi_arr=*inst1; //Wrong. What to do here?
//SPI uint8_t array arrived on target. Convert it back to union type
*inst2=*spi_arr; //Wrong. What to do here?
printf("Target: %d, %f\n",inst2[0].u8[0],inst2[1].f32);
它给了我错误:
error: incompatible types when assigning to type 'uint8_t {aka unsigned char}' from type 'union dummy'
我想要的只是将数组的内容原样地来回复制。该怎么做?
答案 0 :(得分:1)
此示例程序展示了如何将数据复制到char
数组并使用memcpy
重新复制:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int len = 4;
union dummy{
float f32;
uint32_t u32;
uint8_t u8[4];
};
int main(void) {
union dummy inst1[len]; //First instance on source uC
union dummy inst2[len]; //Second instance on target uC
uint8_t spi_arr[sizeof(inst1)];
for (int index = 0; index < len; index++) {
for (int inner_index = 0; inner_index < 4; inner_index++) {
inst1[index].u8[inner_index] = '1' + inner_index;
}
}
memcpy(spi_arr, inst1, sizeof(inst1));
memcpy(inst2, spi_arr, sizeof(spi_arr));
for (int index = 0; index < len; index++) {
for (int inner_index = 0; inner_index < 4; inner_index++) {
printf("%c", inst2[index].u8[inner_index]);
}
printf("\n");
}
return 0;
}
输出
1234
1234
1234
1234
答案 1 :(得分:1)
这是一个示例程序,显示了如何使用指针以两种不同的类型访问数据:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int len = 4;
union dummy{
float f32;
uint32_t u32;
uint8_t u8[4];
};
int main(void) {
union dummy inst1[len]; //First instance on source uC
union dummy *inst2; //Second instance on target uC
uint8_t *spi_arr;
for (int index = 0; index < len; index++) {
for (int inner_index = 0; inner_index < 4; inner_index++) {
inst1[index].u8[inner_index] = '1' + inner_index;
}
}
spi_arr = (uint8_t *) inst1;
for (int index = 0; index < sizeof(inst1); index++) {
printf("%c", spi_arr[index]);
}
printf("\n\n");
inst2 = (union dummy *) spi_arr;
for (int index = 0; index < len; index++) {
for (int inner_index = 0; inner_index < 4; inner_index++) {
printf("%c", inst2[0].u8[inner_index]);
}
printf("\n");
}
return 0;
}
输出
1234123412341234
1234
1234
1234
1234
答案 2 :(得分:0)
如果您更改行:
*spi_arr=*inst1; //Wrong. What to do here?
阅读:
*spi_arr=inst1[0].u8[0];
它编译。我不确定这是否是您想要的。数据类型应该匹配以进行指针分配,这就是错误消息告诉您的内容。在此示例中,*spi_arr
和inst1[0].u8[0]
均为 unit8_t 类型。