首页 > 解决方案 > 如何将十六进制字符串发送到串口?

问题描述

我正在开发一个串行通信程序来在主机 PC(Linux)和微控制器之间发送和接收数据。现在我必须向 MCU 发送十六进制字节的数据。那么如何在不使用 sprint/printf 的情况下将缓冲区字符串数据转换为十六进制字符串,以便用户将“AA12CDFF1000001201”而不是“\xAA\x12\xCD\xFF\x10\x00\x00\x12\x01”之类的字符串发送到 MCU。我还看到了将十六进制发送到串行端口,但它没有帮助,因为它说我可以使用 sprintf 将字符串转换为十六进制,但在我的情况下,我不想使用 sprintf。 基本上我想要的是:如果用户输入 = "AA12CDFF1000001201" 我必须将其转换为以下格式 "\xAA\x12\xCD\xFF\x10\x00\x00\x12\x01" 然后将其写入串行端口。

#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
void main()
{
int fd;
fd = open("/dev/ttyf1", O_RDWR | O_NOCTTY | O_NDELAY);
char buff[]="\xAA\x12\xCD\xFF\x10\x00\x00\x12\x01";
write(fd, buff, sizeof(buff));
close(fd);
}    

标签: clinuxserial-port

解决方案


在与 Hessam 和 Arkku 进行了富有成果的讨论之后,新版本的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* str2hexstr(char* inbuff) {

    char *outbuff;

    if (strlen(inbuff)%2) {
        outbuff=malloc((strlen(inbuff)*2+3)*sizeof(char));
        outbuff[strlen(inbuff)*2+2]='\0'; }
    else {
        outbuff=malloc(strlen(inbuff)*2+1*sizeof(char));
        outbuff[strlen(inbuff)*2]='\0'; }

    for (int strin=0,strout=0;strin<strlen(inbuff);) {
        outbuff[strout++]='\\';
        outbuff[strout++]='x';
        outbuff[strout++]=(!strin&&strlen(inbuff)%2)?'0':inbuff[strin++];
        outbuff[strout++]=inbuff[strin++];
    }
    return(outbuff);
}
int main()
{
    char inbuff1[]="123",inbuff2[]="1234";
    char *outbuff;

    outbuff=str2hexstr(inbuff1);
    printf("%s\n",outbuff);
    free(outbuff);
    outbuff=str2hexstr(inbuff2);
    printf("%s\n",outbuff);
    free(outbuff);
    return 0;
}

推荐阅读