linux串口设备文件:
/dev/ttyS0 , /dev/ttyS1 ,/dev/ttyS3 以此类推,还有其他为终端等设备文件。
打开串口设备
#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 */
/*
* 'open_port()' - Open serial port 1.
*
* Returns the file descriptor on success or -1 on error.
*/
int
open_port(void)
{
int fd; /* File descriptor for the port */
fd = open("/dev/ttyS3", O_RDWR | O_NOCTTY); //打开串口
if (fd == -1)
{
perror("open_port: Unable to open /dev/ttyf1 - ");
}
else
fcntl(fd, F_SETFL, 0); //设置描述符标志位
return (fd);
}
设置串口
最基本的设置串口包括波特率设置,效验位和停止位设置。
串口设置也就是填充结构体struct termios。
struct termios
{ unsigned short c_iflag; /* 输入模式标志 */
unsigned short c_oflag; /* 输出模式标志 */
unsigned short c_cflag; /* 控制模式标志*/
unsigned short c_lflag; /* local mode flags */
unsigned char c_line; /* line discipline */
unsigned char c_cc[NCC]; /* control characters */
};
tcflush(fd, TCIOFLUSH);
tcgetattr(fd, &ti);
cfmakeraw(&ti);
ti.c_cflag |= (CLOCAL | CREAD);
ti.c_cflag &= ~(PARENB | CSIZE | CSTOPB | CRTSCTS);
ti.c_cflag |= CS8;
ti.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
cfsetospeed(&ti, B115200);
cfsetispeed(&ti, B115200);
tcsetattr(fd, TCSANOW, &ti);
tcflush(fd, TCIOFLUSH);