重启后为什么串口读取不起作用?

时间:2014-03-12 11:13:57

标签: c++ linux serial-port

从串口读取时出现问题。

问题是,当我启动计算机时,应用程序不会收到数据。 如果我使用像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;
}

1 个答案:

答案 0 :(得分:0)

我设法解决了这个问题。问题是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;

}
相关问题