在 Linux 下从 C++ 中的串行接口读取字节的问题

Problems with reading Bytes from serial interface in C++ under Linux

我在尝试读取 linux 设备上的串行接口时遇到问题。 这是我打开端口的方式:

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);

否则你不会得到任何结果...