0
我想用C++完成我的樹莓上的串口配置。我需要設置此參數: - 波特率38400, - 數據位8, - 無奇偶校驗, - 無握手。 閱讀工作正常,寫作並不總是正確的。 這裏是我的代碼:串口配置C++
int set_interface_attribs (int fd)
{
struct termios oldtio,newtio;
/* Save current settings */
tcgetattr(fd,&oldtio);
/* clear struct for new settings */
bzero(&newtio, sizeof(newtio));
if (tcgetattr (fd, &oldtio) != 0)
{
std::cout<<"[WARNING]Error from tcgetattr: "<<errno<<" \n \r"<<std::endl;
return -1;
}
newtio.c_cflag |= (CLOCAL | CREAD);
newtio.c_cflag |= BAUDRATE;
newtio.c_cflag &= ~CRTSCTS;
/* Set no parity */
newtio.c_cflag &= ~(PARENB | PARODD);
newtio.c_cflag &= ~CSTOPB;
newtio.c_cflag &= ~CSIZE; /* Mask the character size bits */
newtio.c_cflag |= CS8; /* Select 8 data bits */
newtio.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
newtio.c_iflag &= ~(IXON | IXOFF | IXANY);
newtio.c_lflag = 0; // no signaling chars, no echo,
// no canonical processing
newtio.c_oflag = 0; // no remapping, no delays
newtio.c_cc[VMIN] = 0; // read doesn't block
newtio.c_cc[VTIME] = 5; // 0.5 seconds read timeout
/* Clear */
tcflush(fd, TCIFLUSH);
/* Enable the settings */
tcsetattr(fd,TCSANOW,&newtio);
if (tcsetattr (fd, TCSANOW, &newtio) != 0)
{
std::cout<<"[WARNING]Error from tcgetattr: "<<errno<<" \n \r"<<std::endl;
return -1;
}
return 0;
}
有時候寫的消息是髒的或不完整的。配置是否正確?