我有以下结构:
typedef struct
{
uint8_t number;
uint8_t user_bank;
uint8_t temperature;
float acc_xyz[3];
float gyro_xyz[3];
float mag_xyz[3];
float acc_bias[3];
float gyro_bias[3];
float quaternions[4];
char *orientation_of_IMU;
char *component_orientation_on_pcb;
} Sensor;我对将一些浮点成员表示为字节很感兴趣,因此我可以通过SPI传输它们。到目前为止,我已经有了这些函数,它们允许我包装4个浮动四元数,并在缓冲区中返回16个字节。
typedef char byte;
void floatToByteArray(float f, byte buf[4])
{
memcpy(buf, &f, sizeof(f));
}
//Function that takes float quaternions from a sensor struct, and returns their values, represented as bytes for easier SPI transfer.
void wrap_quaternions(Sensor* imu, int8_t *buff)
{
for (int i = 0; i < 4; i++)
{
floatToByteArray(imu->quaternions[i], &buff[4*i]);
}
}现在我对泛化它很感兴趣,所以我可以在Sensor结构中获取我的任何浮点数组成员,并相应地包装它们。我希望能够使用参数为imu->float_member来调用floatToByteArray函数,但我不能这样做。然后,我可以将数字4更改为sizeof(float_member)。
有解决这个问题的办法吗?
发布于 2020-11-20 21:30:18
你有没有试过用你的浮动参数作为指针?对于这样的情况,指针非常方便。
发布于 2020-11-20 22:46:51
我试着实现了Toms,但我似乎仍然得到了一个错误,因为程序的行为不像它应该的那样。也许你们中的一个能帮上忙。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
typedef char byte;
void floatToByteArray(float f, byte buf[4])
{
memcpy(buf, &f, sizeof(f));
}
void wrap_floatData(int cnt, float *arr[cnt], int8_t *buff)
{
for (int i = 0; i < cnt; i++)
{
floatToByteArray(*arr[i], &buff[cnt*i]);
}
}
struct Sensor_Data_Wrapped
{
int8_t quaternions_wrapped[16];
int8_t mag_xyz_wrapped[12];
int8_t acc_bias_wrapped[12];
int8_t gyro_bias_wrapped[12];
};
typedef struct
{
uint8_t number;
uint8_t user_bank;
uint8_t temperature;
float acc_xyz[3];
float gyro_xyz[3];
float mag_xyz[3];
float acc_bias[3];
float gyro_bias[3];
float quaternions[4];
char *orientation_of_IMU;
char *component_orientation_on_pcb;
//struct Sensor_Data_Wrapped wrapped_data;
} Sensor;
Sensor IMU1;
Sensor IMU2;
int8_t Wrapped_IMU1_bias[12];
int main(void)
{
Wrapped_IMU1_bias[1] = 25;
IMU1.gyro_bias[0] =119.0;
IMU1.gyro_bias[1] = 1349;
IMU1.gyro_bias[2] = 5.2;
wrap_floatData(3, IMU1.gyro_bias, Wrapped_IMU1_bias);
for (int i = 0; i < 12; i++)
{
printf("Byte is %d", Wrapped_IMU1_bias[i]);
printf("\n");
}
return 0;
}错误包括:
main.c:89:20:警告:从不兼容的指针类型-Wincompatible- pointer -types传递“”wrap_floatData“”的参数2“”main.c:39:7:注意:应为“”float**“”,但参数的类型为“”float*“”分段错误(核心转储)“
https://stackoverflow.com/questions/64929104
复制相似问题