简体   繁体   English

linux-串行端口编程(ASCII到字节)

[英]linux - serial port programming ( ASCII to Byte )

I tried to receive data from serial port. 我试图从串行端口接收数据。 However, those data is unrecognized to me. 但是,这些数据对我来说是无法识别的。 The root cause is because those are in ASCII. 根本原因是因为这些都是ASCII格式。 To decode the data, it needs to be the byte formate. 要解码数据,它必须是字节格式。 在此处输入图片说明

The buffer I've created is unsigned char [255] and I try to print out the data by using 我创建的缓冲区是unsigned char [255] ,我尝试使用来打印出数据

while (STOP==FALSE) {  
        res = read(fd,buf,255);
        buf[res]=0; 
        printf(":%x\n", buf[0]);
        if (buf[0]=='z') STOP=TRUE;
     }

Two questions here: 这里有两个问题:

  1. The data might is shorter than 255 in the real case. 在实际情况下,数据可能短于255。 It might takes 20 - 30 arrays from 255. In this case, how can I print 20 arrays ? 从255开始,它可能需要20到30个数组。在这种情况下,如何打印20个数组?

  2. The correct output should be 41542b ( AT+ ) as the head of the entire command since this is the AT command. 正确的输出应为41542b(AT +)作为整个命令的开头,因为这是AT命令。 So I expect the buf[0] should be 41 in the beginning. 因此,我希望buf [0]开头应该为41。 It is, however, I dont know why the second one is e0 while I expect to have 54 (T). 但是,我不知道为什么第二个是e0,而我希望有54(T)。

在此处输入图片说明

Thanks 谢谢

Ascii is a text encoding in bytes. Ascii是一种以字节为单位的文本编码。 There's no difference in reading them, it's just a matter of how you interpret what you read. 阅读它们没有区别,这只是您如何解读阅读内容的问题。 This is not your problem. 这不是你的问题。

Your problem is you read up to 255 bytes at once and only ever print the first of them. 您的问题是您一次最多读取255个字节,并且只能打印其中的第一个。

It's pointless to set buf[res] to 0 when you expect binary data (that possibly contains 0 bytes). 当期望二进制数据(可能包含0个字节)时,将buf[res]设置为0是毫无意义的。 That's just useful for terminating text strings . 这对于终止文本字符串很有用。

Just use a loop over your buffer, eg 只需在缓冲区上使用循环,例如

for (int i = 0; i < res; ++i)
{
    printf("%x", buf[i]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM