Linux下串口的读写操作(linux串口读写)

本文主要介绍Linux下串口的读写操作:

Linux下的串口是一种串行通信的手段,它通过按字符串的形式发送和接收数据,常被用于系统自动检测,工控系统等控制应用场景。

为了实现Linux下的串口的读写操作,首先要打开串口,并设置串口的参数,即波特率,数据位,停止位和校验位,一般是使用下面的函数来实现:

//设置串口
void uart_set(int fd,int speed,int flow_ctrl,int databits,int stopbits,int parity)
{
int i;
int status;
int speed_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, };
struct termios options;

tcgetattr( fd,&options);
for ( i= 0; i
if (speed == name_arr[i]){
cfsetispeed(&options, speed_arr[i]);
cfsetospeed(&options, speed_arr[i]);
}
}
options.c_cflag |= CLOCAL;
//设置数据位
options.c_cflag &= ~CSIZE;
switch (databits){
case 7:
options.c_cflag |= CS7;
break;
case 8:
options.c_cflag |= CS8;
break;
default:
fprintf(stderr,"Unsupported data size\n");
return (FALSE);
}
//设置校验位
switch (parity){
case 'n':
case 'N':
options.c_cflag &= ~PARENB;
options.c_iflag &= ~INPCK;
break;
case 'o':
case 'O':
options.c_cflag |= (PARODD | PARENB);
options.c_iflag |= INPCK;
break;
case 'e':
case 'E':
options.c_cflag |= PARENB;
options.c_cflag &= ~PARODD;
options.c_iflag |= INPCK;
break;
case 's':
case 'S':
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
break;
default:
fprintf(stderr,"Unsupported parity\n");
return (FALSE);
}
//设置停止位
switch (stopbits){
case 1:
options.c_cflag &= ~CSTOPB;
break;
case 2:
options.c_cflag |= CSTOPB;
break;
default:
fprintf(stderr,"Unsupported stop bits\n");
return (FALSE);
}
//修改输出模式,原始数据输出
options.c_oflag &= ~OPOST;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);

//设置等待时间和最小接收字符
options.c_cc[VTIME] = 1; /* 读取一个字符等待1*(1/10)s */
options.c_cc[VMIN] = 1; /* 读取字符的最少个数为1 */

//如果发生数据溢出,接收数据,但是不再读取 刷新收到的数据但是不读
tcflush(fd,TCIFLUSH);

//激活配置 (将修改后的termios数据设置到串口中)
if (tcsetattr(fd,TCSANOW,&options) != 0)
{
perror("com set error!\n");
return (FALSE);
}
return (TRUE);
}

接下来就是串口的写操作,使用write函数很容易实现,我们定义一个函数,来写数据到串口:

void uart_write(int fd,char* buf,int len){
int count = 0;

//发送数据
count = write(fd,buf,len);
if (count
printf("write data failed!\n");
}
else{
printf("write data:%s\n",buf);
}
}

最后我们来看看串口的读操作,读取的操作和写的操作也是很相似,我们也定义一个函数来实现:

//读取串口数据
int uart_read(int fd, char *buf, int data_len)
{
int len = 0, ret = 0;

//设置串口为阻塞状态
fcntl(fd, F_SETFL, 0);

while(1){
ret = read(fd, buf + len, data_len);
if(ret > 0){
len += ret;
}
//读取完毕
else{
break;
}
}

return len;
}

经过上述步骤的操作,Linux系统的串口已经配置好了,我


数据运维技术 » Linux下串口的读写操作(linux串口读写)