c - 如何将十六进制字符串发送到串口?

标签 c linux serial-port

我正在开发一个串行通信程序,用于在主机 (Linux) 和微 Controller 之间发送和接收数据。现在我必须将十六进制字节的数据发送到 MCU。 那么如何在不使用 sprint/printf 的情况下将我的缓冲区字符串数据转换为十六进制字符串,以便用户向 MCU 发送类似“AA12CDFF1000001201”而不是“\xAA\x12\xCD\xFF\x10\x00\x00\x12\x01”的字符串。我也看到了 Sending Hexadecimal to Serial Port但它没有帮助,因为它说我可以使用 sprintf 将字符串转换为十六进制,但在我的例子中,我不想使用 sprinf。 基本上我想要的是: 如果用户输入 = "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);
}    

最佳答案

经过与 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;
}

关于c - 如何将十六进制字符串发送到串口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54050523/

相关文章:

linux - 将文件内容转换为大写

c++ - Qt编程: serial port communication module/plugin

c - 通过参数引用更新C中的全局变量

c - C中打印不同时区的当前时间

c - 格式化 C 字符串

linux - 'kill -STOP and kill -CONT' 是如何工作的?

linux - 根据操作系统运行 Node.js

c - Arduino Serial.print() 优化

java - 指定 Java 通信库的位置

c - 在没有 valgrind 的嵌入式系统上寻找内存泄漏(或使用最小的类似 valgrind 的应用程序)