简体   繁体   中英

Restoring serial port in linux

I was trying to communicate through a serial port with a PLC controlling a mechanical gate for a task in the industry. Being not very experienced with this topic and being in a hurry I was not aware of the importance of storing the old settings and restoring them on program exit. After changing some fields in the termios struct I was no longer able to read anything from the port even after using the exact same opening of port function that I use for the other port (ttyD0) which works fine for those settings. Any suggestions how I can restore ttyD1 back to a working state?

The code used for opening the port is as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM