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

时间:2016-03-10 14:38:20

标签: c++ linux serial-port

当我尝试读取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&lt;的/ dev / ttyMFD1

然后控制台上的输出就可以了。但是我没有得到任何印刷的十六进制值如果我看到&#34; theByte&#34;在调试时。

1 个答案:

答案 0 :(得分:0)

更改

n = read(serial_port, theByte, 1);

n = read(serial_port, &theByte, 1);

否则你没有得到任何结果......