linux下恢复串口

Restoring serial port in linux

本文关键字:串口 恢复 linux      更新时间:2023-10-16

我试图通过串口与PLC进行通信,PLC控制着工业中的机械门。由于对这个主题没有很丰富的经验,而且很匆忙,我没有意识到存储旧设置并在程序退出时恢复它们的重要性。在更改术语结构中的一些字段后,即使在使用与我用于其他端口(ttyD0)的端口函数完全相同的端口打开后,我也不再能够从端口读取任何内容,该端口适用于这些设置。有什么建议我可以恢复ttyD1回到工作状态吗?

用于打开端口的代码如下:

int OpenPort()
{
    fd = open("/dev/ttyD0", O_RDWR | O_NOCTTY);
    if (fd < 0)
    {
        cerr << "open error " << errno << strerror(errno) << endl;
    }
    else
    {
        struct termios my_termios;
        fcntl(fd, F_SETFL, 0);
        tcgetattr(fd, &my_termios);
        //bzero(&my_termios, sizeof(my_termios));
        tcflush(fd, TCIFLUSH);      
        my_termios.c_cflag = B115200 | CS8 | CREAD | CLOCAL | HUPCL;
        //my_termios.c_lflag = ICANON;
        //cfsetospeed(&my_termios, B115200);
        tcsetattr(fd, TCSANOW, &my_termios); 
    }
    return fd;
}

只需复制您从第一个tcgetattr收到的结构体,并在退出时将其交给tcsetattr