1、串口定义
串行接口简称串口,也称串行通信接口(通常指COM接口),是采用串行通信方式的扩展接口。
2、Linux下的使用
在Linux下操作、控制串口是通过操作设备文件进行的,可在/dev目录下看到串口设备文件,如ttyS0、ttyS1等。在应该程序中操作串口可进行以下步骤:
- 打开串口
int comfd;
comfd = open("/dev/ttyS2", O_RDWR | O_NOCTTY | O_NONBLOCK);
if (comfd <0 )
{
perror("Can't Open Serial Port");
return -1;
}
else {
return fd;
}
- 设置串口波特率
set_baud(comfd , 9600); //设置波特率为9600
set_baud()函数定义如下:
int baud_arr[] = { B38400, B19200, B9600, B4800, B2400, B1200, B300,
B38400, B19200, B9600, B4800, B2400, B1200, B300, };
int name_arr[] = {38400, 19200, 9600, 4800, 2400, 1200, 300, 38400,
19200, 9600, 4800, 2400, 1200, 300, };
void set_baud(int fd, int baud){
int i;
int status;
struct termios Opt;
tcgetattr(fd, &Opt);
for ( i= 0; i < sizeof(speed_arr) / sizeof(int); i++) {
if (baud== name_arr[i]) {
tcflush(fd, TCIOFLUSH);
cfsetispeed(&Opt, baud_arr[i]);
cfsetospeed(&Opt, baud_arr[i]);
status = tcsetattr(fd, TCSANOW, &Opt);
if (status != 0) {