串行口是计算机一种常用的接口,具有连接线少,通讯简单,得到广泛的使用。常用的串口是 RS-232-C 接口(又称 EIA RS-232-C)它是在 1970 年由美国电子工业协会(EIA)联合贝尔系统、 调制解调器厂家及计算机终端生产厂家共同制定的用于串行通讯的标准。它的全名是"数据终端设备(DTE)和数据通讯设备(DCE)之间串行二进制数据交换接口技术标准"该标准规定采用一个 25 个脚的 DB25 连接器,对连接器的每个引脚的信号内容加以规定,还对各种信号的电平加以规定。传输距离在码元畸变小于 4% 的情况下,传输电缆长度应为 50 英尺。
串口设备通常有RS232,RS485,RS422,这些设备在LInux系统中统一为TTY设备。
打开设备:
int serial_fd; serial_fd=open("/dev/ttymxc1",O_RDWR|O_NOCTTY|O_NDELAY);
关闭设备:
close(serial_fd);
配置串口:
Linux中对串口配置通过兼容POSIX标准的Termios结构体来实现。
struct termio { 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 */ };
波特率设置:
Linux支持多种波特率,可选参数如下:
B38400, B19200, B9600, B4800, B2400, B1200, B300,B38400, B19200, B9600, B4800, B2400, B1200, B300
struct termios Opt; tcgetattr(fd, &Opt); cfsetispeed(&Opt,B19200); cfsetospeed(&Opt,B19200); tcsetattr(fd,TCANOW,&Opt);
数据位设置:
Termios支持两种停止位,7bit和8bit。
Data Bit | Argument |
---|---|
7 Bit | CS7 |
8 Bit | CS8 |
options.c_cflag |= CS8;
停止位设置:
串口的停止位一般有两种,1bit和2bit。
设置方法如下:
// Stop Bit as 1Bit options.c_cflag &= ~CSTOPB; // Stop Bit as 2Bit options.c_cflag |= CSTOPB;
校验位设置:
串口的校验位有四种方式,无校验(None),奇校验(Odd),偶校验(E)和空校验(Space)。
参考代码如下:
// Parity is None options.c_cflag &= ~PARENB; /* Clear parity enable */ options.c_iflag &= ~INPCK; /* Enable parity checking */ // Parity is Odd options.c_cflag |= (PARODD | PARENB); /* 设置为奇效验*/ options.c_iflag |= INPCK; /* Disnable parity checking */ // Parity is E options.c_cflag |= PARENB; /* Enable parity */ options.c_cflag &= ~PARODD; /* 转换为偶效验*/ options.c_iflag |= INPCK; /* Disnable parity checking */ /*as no parity*/ options.c_cflag &= ~PARENB; options.c_cflag &= ~CSTOPB;break;
串口读写:
Linux中得益于设备即是文件的理念,可以直接使用read()和write()函数对串口操作。
char buffer[1024]; int wsize, rsize; // write data to fd of indicator device wsize = write(serial_fd, buffer ,Length) // read data from fd of indicator device memset(buffer, 0, sizeof(buffer)); rsize = read(serial_fd, buff, Len);