【问题标题】:Serial port read/open error in C, LinuxC、Linux 中的串行端口读取/打开错误
【发布时间】:2016-02-18 16:26:20
【问题描述】:

我在为要打开的串行端口选择正确设置时遇到问题。 我掌握的信息如下:

  • 同步:异步方法
  • 通讯方式:全双工传输
  • 通信速度:9600 bps(比特每秒)
  • 传输代码:8位数据
  • 数据配置:起始位 1,数据 8 位 + 奇偶校验 1,停止位 1
  • 错误控制:水平 (CRC) 和垂直(偶数)奇偶校验
  • 1 字节配置 在此连接时,PC 不应使用控制信号(DTR、DSR、RTS 和 CTS)。

我所拥有的是这样的:

bool configurePort(void)   {
    struct termios port_settings;
    bzero(&port_settings, sizeof(port_settings));

    tcgetattr(fd, &port_settings);

    cfsetispeed(&port_settings, B9600);
    cfsetospeed(&port_settings, B9600);

    port_settings.c_cflag &= ~CSIZE;
    port_settings.c_cflag |= CS8;

    // parity bit
    //port_settings.c_cflag &= ~PARENB;
    //port_settings.c_cflag &= ~PARODD;
    // hardware flow
    port_settings.c_cflag &= ~CRTSCTS;
    // stop bit
    //port_settings.c_cflag &= ~CSTOPB;

    port_settings.c_iflag = IGNBRK;
    port_settings.c_iflag &= ~(IXON | IXOFF | IXANY);
    port_settings.c_lflag = 0;
    port_settings.c_oflag = 0;

    port_settings.c_cc[VMIN] = 1;   
    port_settings.c_cc[VTIME] = 0;
    port_settings.c_cc[VEOF] = 4;   

    tcsetattr(fd, TCSANOW, &port_settings);


    return true;
}

尝试了各种修改,但似乎没有任何效果。

设备通过 USB 串行 (ttyUSB0) 连接,我有权限。 它打开设备,发送(?)数据,但永远不会得到任何回报......

谁能指点我应该怎么做?

【问题讨论】:

  • 您的评论不具建设性,与问题无关。而且,这更像是 C 而不是 C++
  • 您需要测试 tcgetattr()tcsetattr() 的返回码,尤其是在遇到问题时。也许它没有在示例中完成,但检查返回码是编写健壮代码的正确方法。您尚未指定这是否是规范 I/O。在原始模式下定义 VEOF 是不合逻辑的。你还没有设置平价。学习Setting Terminal Modes ProperlySerial Programming Guide for POSIX Operating Systems

标签: c++ linux serial-port tty


【解决方案1】:

试试这个:

bool configurePort(void)   {
    struct termios port_settings;
    bzero(&port_settings, sizeof(port_settings));

    if(tcgetattr(fd, &port_settings) < 0) {
        perror("tcgetattr");
        return false;
    }

    cfmakeraw(&port_settings);

    cfsetispeed(&port_settings, B9600);
    cfsetospeed(&port_settings, B9600);

    //input
    port_settings.c_iflag &= ~(IXON | IXOFF | IXANY); //disable flow control

    //local
    port_settings.c_lflag = 0;  // No local flags

    //output
    port_settings.c_oflag |= ONLRET;
    port_settings.c_oflag |= ONOCR;
    port_settings.c_oflag &= ~OPOST;


    port_settings.c_cflag &= ~CRTSCTS; // Disable RTS/CTS    
    port_settings.c_cflag |= CREAD; // Enable receiver
    port_settings.c_cflag &= ~CSTOPB;


    tcflush(fd, TCIFLUSH);


    if(tcsetattr(fd, TCSANOW, &port_settings) < 0) {
        perror("tcsetattr");
        return false;
    }

    int iflags = TIOCM_DTR;
    ioctl(fd, TIOCMBIC, &iflags); // turn off DTR

    return true;
} //configure port

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    相关资源
    最近更新 更多