2016-07-08 37 views
0

我想用C++完成我的樹莓上的串口配置。我需要設置此參數: - 波特率38400, - 數據位8, - 無奇偶校驗, - 無握手。 閱讀工作正常,寫作並不總是正確的。 這裏是我的代碼:串口配置C++

int set_interface_attribs (int fd) 
{ 
    struct termios oldtio,newtio; 
    /* Save current settings */ 
    tcgetattr(fd,&oldtio); 
    /* clear struct for new settings */ 
    bzero(&newtio, sizeof(newtio)); 
    if (tcgetattr (fd, &oldtio) != 0) 
    {  
      std::cout<<"[WARNING]Error from tcgetattr: "<<errno<<" \n \r"<<std::endl; 
      return -1; 
    } 
newtio.c_cflag |= (CLOCAL | CREAD); 
newtio.c_cflag |= BAUDRATE; 
newtio.c_cflag &= ~CRTSCTS; 
/* Set no parity */ 
newtio.c_cflag &= ~(PARENB | PARODD); 
newtio.c_cflag &= ~CSTOPB; 
newtio.c_cflag &= ~CSIZE; /* Mask the character size bits */ 
newtio.c_cflag |= CS8; /* Select 8 data bits */ 
newtio.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); 
newtio.c_iflag &= ~(IXON | IXOFF | IXANY); 
    newtio.c_lflag = 0;    // no signaling chars, no echo, 
             // no canonical processing 
     newtio.c_oflag = 0;    // no remapping, no delays 
    newtio.c_cc[VMIN] = 0;   // read doesn't block 
    newtio.c_cc[VTIME] = 5;   // 0.5 seconds read timeout 
    /* Clear */ 
    tcflush(fd, TCIFLUSH); 
    /* Enable the settings */ 
    tcsetattr(fd,TCSANOW,&newtio); 
    if (tcsetattr (fd, TCSANOW, &newtio) != 0) 
    { 
        std::cout<<"[WARNING]Error from tcgetattr: "<<errno<<" \n \r"<<std::endl; 
      return -1; 
    } 
    return 0; 
    } 

有時候寫的消息是髒的或不完整的。配置是否正確?

回答

0

您的代碼不符合Setting Terminal Modes ProperlySerial Programming Guide for POSIX Operating Systems

試試這個代碼:

struct termios oldtio; 

int set_interface_attribs(int fd) 
{ 
    struct termios newtio; 
    speed_t spd; 
    int rc; 

    rc = tcgetattr(fd, &oldtio); 
    if (rc < 0) {  
     std::cout<<"[WARNING]Error from tcgetattr: "<<errno<<" \n \r"<<std::endl; 
      return -1; 
    } 
    newtio = oldtio; 

    spd = B38400; 
    cfsetospeed(&newtio, spd); 
    cfsetispeed(&newtio, spd); 

    cfmakeraw(&newtio); 
    newtio.c_cflag |= (CLOCAL | CREAD); 
    newtio.c_cflag &= ~CRTSCTS; 
    newtio.c_cflag &= ~CSTOPB; 

    /* pure timed read */ 
    newtio.c_cc[VMIN] = 0; 
    newtio.c_cc[VTIME] = 5; 
    /* Clear */ 
    tcflush(fd, TCIFLUSH); 
    /* Enable the settings */ 
    rc = tcsetattr(fd, TCSANOW, &newtio); 
    if (rc < 0) { 
     std::cout<<"[WARNING]Error from tcgetattr: "<<errno<<" \n \r"<<std::endl; 
     return -1; 
    } 
    return 0; 
} 

如果上面沒有幫助,然後發佈您的代碼試圖執行寫入操作。

順便說一句oldtio是爲了保留原始termios設置的副本,並且應該用於在串行端口關閉之前恢復串行端口。但是你的例程聲明oldtio爲本地,所以它沒有在初始化例程之外的範圍。