【发布时间】:2017-06-10 01:17:25
【问题描述】:
我正在尝试从 BeagleBone Black 上的串行端口 (/dev/ttyS4) 读取数据,但我认为(?)这通常适用于所有 Linux 设备。
目前,我可以设置minicom,波特率为9600,数据为8N1,以正确读取串口。但是,如果我尝试直接cat /dev/ttyS4,我的终端中不会显示任何内容。我的代码也这样做,并返回一个Resource temporarily unavailable 错误,我怀疑这是cat 命令发生的情况。
如果我运行stty -F /dev/ttyS4,我会得到以下输出(据我所知,这与我的minicom 设置一致):
speed 9600 baud; line = 0;
intr = <undef>; quit = <undef>; erase = <undef>; kill = <undef>; eof = <undef>; start = <undef>; stop = <undef>; susp = <undef>; rprnt = <undef>; werase = <undef>; lnext = <undef>; flush = <undef>;
-brkint -imaxbel
-opost -onclr
-isig -iexten -echo -echoe -echok -echoctl -echoke
有趣的是,当我打开minicom 时,如果我启动我的程序,minicom 将停止打印任何内容,并且即使我停止我的程序也会保持这种状态。我需要再次打开串行设置(Ctrl-A、P)并关闭它以使minicom 恢复工作(似乎没有任何改变)。
我的代码如下:
int main() {
std::cout << "Starting..." << std::endl;
std::cout << "Connecting..." << std::endl;
int tty4 = open("/dev/ttyS4", O_RDWR | O_NOCTTY | O_NDELAY);
if (tty4 < 0) {
std::cout << "Error opening serial terminal." << std::endl;
}
std::cout << "Configuring..." << std::endl;
struct termios oldtio, newtio;
tcgetattr(tty4, &oldtio); // save current serial port settings
bzero(&newtio, sizeof(newtio)); // clear struct for new settings
newtio.c_cflag = B9600 | CS8 | CREAD | CLOCAL;
newtio.c_iflag = IGNPAR | ICRNL;
newtio.c_oflag = 0;
newtio.c_lflag = ICANON;
tcflush(tty4, TCIFLUSH);
tcsetattr(tty4, TCSANOW, &newtio);
std::cout << "Reading..." << std::endl;
while (true) {
uint8_t byte;
int status = read(tty4, &byte, 1);
if (status > 0) {
std::cout << (char)byte;
} else if (status == -1) {
std::cout << "\tERROR: " << strerror(errno) << std::endl;
}
}
tcsetattr(tty4, TCSANOW, &oldtio);
close(tty4);
}
编辑:按照 Adafruit 的将 python 与 BeagleBone 结合使用的教程,我已经让串行端口正常工作(在 python 中)。在这一点上,我确定 我 做错了什么;问题是什么。我更喜欢使用 C++ 而不是 python,所以让它工作会很棒。
【问题讨论】:
-
我看到了几个可能的问题,但您的问题是什么?
-
我应该如何修改我的c++程序才能成功从串口读取?
标签: c++ linux serial-port termios