Linux Reads Serial Data
Computer serial port data reading is often used when using sensors. Next, I introduce the method of reading Linux serial port data in a project. I hope it will be helpful to you.
Data Format
A set of data transmitted by the sensor through serial port is 13 bytes. The data format is as follows:
Initialize Serial Port
We need to initialize the serial port before reading the serial port data. The initialization of the serial port needs three steps:opening the serial port, setting the parameters of the serial port (including baud rate, data bit, stop bit, check bit).
Opening the Port
The procedure of opening serial port is as follow, function returns a handle:
int openPort()
{
int fd;
fd = open(SERIAL_PORT, O_RDWR | O_NOCTTY |O_NDELAY);
if(fd == -1)
{
perror("open serial failed!\n");
exit(1);
}
return fd;
}
SERIAL_PORT is a serial address;
O_RDWR means to open in a readable and writable manner;
O_NOCTTY indicates that if the open file is a terminal device, the terminal will not be regarded as a process control terminal;
O_NDELAY denotes opening a file in an uninterruptible manner.
Setting the Parameters
Here is the program for setting baud rate and data bits
int setSpeed(int fd, int speed, struct termios Opt)
{
int i;
if(tcgetattr(STDIN_FILENO, &Opt) !