首先描述一下我遇到的问题:
用单片机将计算好的浮点数,用串口发送到上位机。串口是按字节进行发送的,那么如果发送浮点数就应该将32位的浮点数按位拆为4个字节,尝试了一些方法都不太好,最终发现用联合体union最为恰当:
union
{
uint8_t i_array[4];
uint32_t i_32;
float f;
}float_change;
int main(void)
{
usart_config_t config;
/* attach 12 MHz clock to FLEXCOMM0 (debug console) */
CLOCK_AttachClk(BOARD_DEBUG_UART_CLK_ATTACH);
BOARD_InitPins();
BOARD_BootClockPLL150M();
BOARD_InitDebugConsole();
USART_GetDefaultConfig(&config);
config.baudRate_Bps = BOARD_DEBUG_UART_BAUDRATE;
config.enableTx = true;
config.enableRx = true;
USART_Init(DEMO_USART, &config, DEMO_USART_CLK_FREQ);
float_change.f=2.34;
PRINTF("the initial value float:%6.3f\r\n",float_change.f);
PRINTF("the initial value float:%x\r\n",float_change.f);
PRINTF("the initial value intger:%x\r\n",float_change.i_32); PRINTF("a3:%x,a2:%x,a1:%x,a0:%x\r\n",float_change.i_array[3],float_change.i_array[2],float_change.i_array[1],float_change.i_array[0]);
while(1) {}
}
运行后结果如下: