我想写入 com 端口并从中读取一定数量的字节。录制似乎没有问题,它不write
返回错误。但是在阅读问题时:它read
挂起。也就是说,港口什么都没有,但如果我以前做过,怎么可能write
呢?或者它是否以其他方式工作?
int main(int argc, char* argv[])
{
int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY /*| O_NDELAY*/);
if (fd == -1)
{
std::cout << " Unable to open /dev/ttyS0" << std::endl;
return 0;
}
// configure
termios attr_old;
termios attr;
memset( &attr_old, 0, sizeof(termios) );
memset( &attr, 0, sizeof(termios) );
if ( tcgetattr(fd, &attr_old) )
{
std::cout << "Error: " << strerror(errno) << " from tcgetattr" << std::endl;
return 0;
}
attr = attr_old;
//Baud rate
cfsetospeed(&attr, B9600);
cfsetispeed(&attr, B9600);
attr.c_cflag &= ~PARENB; // Make 8n1
attr.c_cflag &= ~CSTOPB;
attr.c_cflag &= ~CSIZE;
attr.c_cflag |= CS8;
attr.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
attr.c_cflag &= ~CRTSCTS; // no flow control
attr.c_cc[VMIN] = 1; // read doesn't block
attr.c_cc[VTIME] = 5; // 0.5 seconds read timeout
// Make raw
cfmakeraw(&attr);
// Flush Port, then applies attributes
tcflush( fd, TCIFLUSH );
if ( tcsetattr ( fd, TCSANOW, &attr ) != 0)
{
std::cout << "Error: " << strerror(errno) << " from tcsetattr" << std::endl;
return 0;
}
//Write
int nw = write(fd, "A\r", 2);
if ( nw < 0)
{
std::cout << "Error: " << strerror(errno) << " from write" << std::endl;
return 0;
}
//Read
char buff[32];
memset( &buff, '\0', sizeof(buff) );
int nr = 0;
int spot = 0;
char ch = '\0';
do
{
nr = read(fd, &ch, 1);
if (nr < 0 )
{
int er = errno;
std::cout << "Error: " << er << " " << strerror(er) << " from read" << std::endl;
return 0;
}
sprintf(&buff[spot], "%c", ch);
spot += nr;
}
while( ch != '\r' && nr > 0 );
close(fd);
return 0;
}
端口上是否有设备会响应?
如果您在其上放置一个 TX-RX 跳线(关闭 DB-9 连接器的 2-3 个引脚),则可以保证您可以在写入后从端口读取(发送的内容)