0
votes

I am writing a program that reads the data from the serial port on Linux. The data are sent by another device with the following frame format:


|start | Command | Data               | CRC  | End |
|0x02  | 0x41    | (0-127 octets)     |      | 0x03|
----------------------------------------------------

The Data field contains 127 octets as shown and octet 1,2 contains one type of data; octet 3,4 contains another data. I need to get these data.

Because in C, one byte can only holds one character and in the start field of the frame, it is 0x02 which means STX which is 3 characters.

So, in order to test my program,

On the sender side, I construct an array as the frame formatted above like:


char frame[254];
frame[0] = 0x02; // starting field
frame[1] = 0x41; // command field which is character 'A'
..so on..

And, then On the receiver side, I take out the fields like:


char result[254];
// read data
read(result);
printf("command = %c", result[1]); // get the command field of the frame

// get other field's values

the command field value (result[1]) is not character 'A'.

I think, this because the first field value of the frame is 0x02 (STX) occupying 3 first places in the array frame and leading to the wrong results on the receiver side.

How can I correct the issue or am I doing something wrong at the sender side?

related questions:
Parse and read data frame in C?
Clear data at serial port in Linux in C?

1
What does the buffer contain? What function do you call to perform the read? (That is clearly not a read system call.) Have you verified the serial link with a terminal application? - Potatoswatter
STX does not take 3 bytes; all characters take 1 byte. Some characters (like STX) just have longer names. - Gabe
the full code of read() function is here: stackoverflow.com/questions/2500567/…. I think so too. If I call result[1], the value should be 0x41 which means 'A', right? But it is not. I returns a strange value. Am I thinking wrong? - ipkiss
What value are you getting? - Nathan Fellman
I got a '?' which means an unknown value. - ipkiss

1 Answers

0
votes

If your program actually contains

read(result);

then you need to add

#include <unistd.h>

at the top, to get the function prototype for read. Then you need to open the serial port and pass the resulting file descriptor to read along with your buffer, so it knows what to read. See man 2 read and man 2 open.