c - 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.
解决方案
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);
...
推荐阅读
- elasticsearch - Kibana 地图 - 使用来自另一个索引的地理围栏 (geo_shapes) 过滤一个索引中的 geo_points
- c# - 如何使用平面法线将矢量从 xyz 转换为 xy?(使用 hlsl)
- javascript - React 是否等待渲染更新状态?
- javascript - JS 验证填字游戏线索枚举
- c++ - GUI - 无法将列添加到 ListView
- react-native - 如何使用 AsyncStorage 创建一个将数组值和 Button 状态保存到设备的 React Native Button?
- sparql - SPARQL 查询返回空结果集
- string - 获取与列表一个字符不匹配的相似唯一字符串
- reactjs - React + Fomik + redux:函数作为 React 子级无效
- javascript - 为什么我可以修改模块内部命名返回对象的属性,但不能修改对象本身?