为什么重启后串口读取不工作

Why serial port reading is not working after reboot?

本文关键字:工作 读取 串口 重启 为什么      更新时间:2023-10-16

从串行端口读取时出现问题。

问题是当我启动计算机时,应用程序没有接收到数据。如果我使用像jpnevulator这样的工具,我可以看到数据来了。在我杀死jpnevulator之后,我也可以从我的应用程序中读取数据。只有当我尝试在重启后运行应用程序时,它才会工作,直到我首先用其他工具(如jpnevulator)读取一些数据。

应用程序很大,所以我将只放置我认为相关的代码部分。

bool CSerial::SetPort(char *port){
    this->port = (char*) malloc(strlen(port));
    strcpy(this->port, port);
    return true;
}
bool CSerial::Setup(){
    if(!Open()){
        return false;
    }
    tcgetattr(fdPort, &options);
    cfsetispeed(&options, B115200);
    cfsetospeed(&options, B115200);
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;
    if(tcsetattr(fdPort, TCSANOW, &options)){
        return false;
    }
    return true;
}
bool CSerial::Open(){
    this->fdPort = open(this->port, O_RDWR | O_NOCTTY | O_NDELAY /*| O_NONBLOCK*/ );
    if(fdPort == -1){
        return false;
    }
    else{
        //fcntl(fdPort, F_SETFL, 0);
        fcntl(fdPort, F_SETFL, FNDELAY);
    }
    return true;
}

bool CSerial::ReadData(uint8_t *data, uint32_t length, int32_t *receivedDataBytes){
    int32_t temp_receivedDataBytes = -1;
    fd_set readFd;
    FD_ZERO(&readFd);
    FD_SET(fdPort, &readFd);
    struct timeval timeout;
    timeout.tv_sec = 0;
    timeout.tv_usec = 50000;
    int test;
    if(fcntl(fdPort, F_GETFD) != -1){
        while(test = select(fdPort + 1, &readFd, NULL, NULL, &timeout) == 1 && temp_receivedDataBytes == -1){
            FD_ZERO(&readFd);
            FD_SET(fdPort, &readFd);
            struct timeval timeout;
            timeout.tv_sec = 0;
            timeout.tv_usec = 50000;
            if(FD_ISSET(fdPort, &readFd))
                temp_receivedDataBytes = read(fdPort, data, length);
            else continue;
        }
        if(temp_receivedDataBytes < 0){
            return false;
        }
        if(temp_receivedDataBytes > 0){
            *receivedDataBytes = temp_receivedDataBytes;
            return true;
        }
    }
    return false;
}

我设法解决了这个问题。问题是jpnevulator在使用它进行阅读时为我设置端口,然后为我的应用程序保留设置。

为了解决这个问题,我设置了几乎所有的串口。

bool Serial::Setup(){
    if(!openPort()){
        return false;
    }
    tcgetattr(fdPort, &options);

    cfsetispeed(&options, B115200);
    cfsetospeed(&options, B115200);
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;
    options.c_cc[VMIN] = 1;
    options.c_cc[VTIME] = 0;

    options.c_oflag &= ~(OCRNL | ONLCR | ONLRET | ONOCR | OFILL | OLCUC | OPOST);

    options.c_iflag &= ~(IGNBRK | BRKINT | ICRNL | INLCR | PARMRK | INPCK | ISTRIP | IXON);
    options.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN | ISIG);
    if(tcsetattr(fdPort, TCSANOW, &options)){
        return false;
    }
    return true;
}