0
我想通過串行連接使用read()函數。串行讀()沒有返回一個值沒有數據接收
我初始化串行端口具有下列設置:
bool HardwareSerial::begin(speed_t speed) {
int USB = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY);
if (USB == 1) {
std::cout << "\n Error! in Opening ttyUSB0\n" << std::endl;
} else {
std::cout << "\n ttyUSB0 Opened Successfully\n" << std::endl;
}
struct termios tty;
struct termios tty_old;
memset(&tty, 0, sizeof tty);
// Error Handling
if (tcgetattr(USB, &tty) != 0) {
std::cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
}
//Save old tty parameters
tty_old = tty;
// Set Baud Rate
cfsetospeed(&tty, (speed_t) speed);
cfsetispeed(&tty, (speed_t) speed);
// Setting other Port Stuff
tty.c_cflag &= ~PARENB; // Make 8n1
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_iflag &= ~(IXON | IXOFF | IXANY);
tty.c_iflag &= ~(ICANON | ECHO | ECHOE | ISIG);
tty.c_cflag &= ~CRTSCTS; // no flow control
tty.c_cc[VMIN] = 1; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
// Make raw
cfmakeraw(&tty);
//Flush Port, then applies attributes
tcflush(USB, TCIFLUSH);
if (tcsetattr(USB, TCSANOW, &tty) != 0) {
std::cout << "Error " << errno << " from tcsetattr" << std::endl;
}
_USB = USB;
return true;
}
然後我定期調用類成員讀()函數調用流中讀取:
int HardwareSerial::read() {
int n = 0;
char buf;
n = ::read(_USB, &buf, 1);
std::cout << std::hex << static_cast<int> (buf) << " n:";
std::cout << n << std::endl;
}
雖然端口接收數據的讀()按預期工作並打印傳入字節。但是,如果我停止發送字節,程序會掛起,直到某些字節未收到。 我期望::讀取將返回0,但它不會返回任何內容並等待傳入的數據。在收到新數據後,程序繼續工作,並且:: read返回1;
那麼我在配置中錯過了什麼? 我試過不同的VMIN和VTIME,但結果是一樣的。