首页 > 解决方案 > How can a char array of hex values be sent as plain text over serial

问题描述

I am using an STM32, and monitoring the serial port using CoolTerm.

I have an array, that stores the following: 0x01 0xFA 0xAA 0x05 ... etc. I want to sent that over serial and see those values in plain text.

When I use the following:

char array[10] = { 0x01, 0xFA, 0xAA, 0x05, 0x01, 0xFA, 0xAA, 0x05, 0x01, 0x01 };
HAL_UART_Transmit(&huart4, (uint8_t *)array, len, 1);

The output on CoolTerm is:

. . . . . . . . . .

Dots instead of plain text values are shown, if I switch to HEX mode I can see the values.

What I need the output to look like:

"0x01 0xFA 0xAA 0x05 0x01 0xFA 0xAA 0x05 0x01 0x01"

I imagine this is due to the array storing byte literals, but I have no idea what to use to see the hex in plain text in the ASCII decoding serial monitor.

标签: chexasciistm32

解决方案


You'd need to use sprintf() to a char* then send it. Something like:

char* buf = malloc(5*len);
for (i = 0; i < len; i++)
    sprintf(buf+5*i, "0x%02x ", array[i]);
HAL_UART_Transmit(&huart4, buf, 5*len-1, 1);
free(buf);

You need to allocate five time the amount of bytes because a single byte will transform into 5:

0 x ? ? <space>

then you don't transmit the last space over the serial link (hence the -1 in 5*len-1).

You can also add an \n at the end instead of the last space, and then transmit it:

...
buf[5*len-1] = '\n';
HAL_UART_Transmit(&huart4, buf, 5*len, 1);
...

推荐阅读