Skip to content
Advertisement

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. To decode the data, it needs to be the byte formate. enter image description here

The buffer I’ve created is unsigned char [255] and I try to print out the data by using

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

Two questions here:

  1. The data might is shorter than 255 in the real case. It might takes 20 – 30 arrays from 255. In this case, how can I print 20 arrays ?

  2. The correct output should be 41542b ( AT+ ) as the head of the entire command since this is the AT command. So I expect the buf[0] should be 41 in the beginning. It is, however, I dont know why the second one is e0 while I expect to have 54 (T).

enter image description here

Thanks

Advertisement

Answer

Ascii is a text encoding in bytes. 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.

It’s pointless to set buf[res] to 0 when you expect binary data (that possibly contains 0 bytes). That’s just useful for terminating text strings.

Just use a loop over your buffer, e.g.

for (int i = 0; i < res; ++i)
{
    printf("%x", buf[i]);
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement