当我尝试读取我的 Linux 设备上的串行接口(interface)时,我遇到了问题。 这是我打开端口的方式:
string port = /dev/ttyMFD1;
struct termios tio;
struct termios stdio;
fd_set rdset;
memset(&stdio, 0, sizeof(stdio));
stdio.c_iflag = 0;
stdio.c_oflag = 0;
stdio.c_cflag = 0;
stdio.c_lflag = 0;
stdio.c_cc[VMIN] = 1;
stdio.c_cc[VTIME] = 0;
tcsetattr(STDOUT_FILENO, TCSANOW, &stdio);
tcsetattr(STDOUT_FILENO, TCSAFLUSH, &stdio);
fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
memset(&tio, 0, sizeof(tio));
tio.c_iflag = 0;
tio.c_oflag = 0;
tio.c_cflag = CS8 | CREAD | CLOCAL;
tio.c_lflag = 0;
tio.c_cc[VMIN] = 1;
tio.c_cc[VTIME] = 2;
serial_port = open(port.c_str(), O_RDWR | O_NONBLOCK);
cfsetospeed(&tio, B115200);
cfsetispeed(&tio, B115200);
tcsetattr(serial_port, TCSANOW, &tio);
现在我使用以下代码写入端口(“str”中包含十六进制值):
char str[] = { 0xAA, 0x00, 0x3D, 0x01, 0x0C, 0x00 };
write(serial_port, str, strlen(str));
现在我想从我的 UART 连接芯片获得响应:
while(1)
{
unsigned char theByte;
int n = 0;
n = read(serial_port, theByte, 1);
cout << theByte << "\n" ;
usleep(100000);
}
当我调试时,返回值没有帮助。当我连接调试终端并执行
od -x < /dev/ttyMFD1
然后控制台上的输出就可以了。但是如果我在调试时查看“theByte”,我没有得到任何打印的十六进制值。
最佳答案
改变
n = read(serial_port, theByte, 1);
到
n = read(serial_port, &theByte, 1);
否则你不会得到任何结果......
关于c++ - 在 Linux 下从 C++ 中的串行接口(interface)读取字节的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35919461/