我们在日常使用过程中经常需要对USB串口进行一些读写操作,这里记录一下C,C++两种语言的操作过程.
注意:作者使用的环境为Ubuntu,在windows系统中使用需要对应把ttyUSB转换为COM口.
C语言读写USB串口
/* xiaochen open ttyUSB ------------------------------------------------------*/
int openttyUSB(char* path)
{
int brate=9600,bsize=8,stopb=1;
char *p,parity='N',dev[128],port[128],fctr[64]="";
if ((p=strchr(path,':'))) {
strncpy(port,path,p-path); port[p-path]='\0';
sscanf(p,":%d:%d:%c:%d:%s",&brate,&bsize,&parity,&stopb,fctr);
}
else strcpy(port,path);
sprintf(dev,"/dev/%s",port);
int fd = open(dev, O_RDWR | O_NOCTTY);
if (fd == -1) {
perror("open");
return 1;
}
struct termios ios={0};
tcgetattr(fd,&ios);
/*设置波特率*/
cfsetospeed(&ios, brate);
cfsetispeed(&ios, brate);
/*设置数据位、停止位和校验位等*/
ios.c_cflag &= ~PARENB; /*清除校验位*/
ios.c_cflag &= ~CSTOPB; /*使用一位停止位*/
ios.c_cflag &= ~CSIZE; /*清除数据位*/
ios.c_cflag |= CS8; /*设置数据位为 8*/
if (tcsetattr(fd, TCSANOW, &ios) != 0) {
perror("tcsetattr");
return 1;
}
tcflush(fd,TCIOFLUSH);
/*printf("path: %s \n", path);*/
return fd;
}
/*调用 path = 'ttyUSB0:115200:8:N:1:off'*/
int fd = openttyUSB(path);
/*读取数据*/
unsigned char read_buf[256];
m_read = read(fd, read_buf, sizeof(read_buf));
/*写出数据*/
int bytes_written = write(fd, buff, strlen(buff));
if (bytes_written == -1) {
fprintf(stderr, "写入数据失败\n");
close(fd);
return 1;
}
C++读写USB串口
/*boost*/
#include<boost/asio.hpp>
#include<boost/bind.hpp>
boost::asio::io_service io;
boost::asio::serial_port sp(io, serial_port);
sp.set_option( boost::asio::serial_port::baud_rate(baud_rate));
sp.set_option( boost::asio::serial_port::flow_control( boost::asio::serial_port::flow_control::none ) );
sp.set_option( boost::asio::serial_port::parity( boost::asio::serial_port::parity::none ) );
sp.set_option( boost::asio::serial_port::stop_bits( boost::asio::serial_port::stop_bits::one ) );
sp.set_option( boost::asio::serial_port::character_size( 8 ) );
// 读取数据
char read_once[1]={'\0'};
boost::asio::read(sp,boost::asio::buffer(read_once));
// 写出数据
boost::asio::write(sp,boost::asio::buffer(buff,buff_len));