c++ - C、Linux 中的串口读取/打开错误

标签 c++ linux serial-port tty

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

  • 同步:异步方法
  • 通讯方式:全双工传输
  • 通信速度: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) 连接,并且我有权限。 它打开设备,发送(?)数据,但永远不会返回任何内容......

有人能指出我应该做什么吗?

最佳答案

试试这个:

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

关于c++ - C、Linux 中的串口读取/打开错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35486996/

相关文章:

c++ - 基类未定义

C++二叉搜索树去除段错误

linux - tar 命令不生成 .tar.gz 文件

c++ - C++ 中的 SQLite3 多线程 (linux)

c - 无法接收串口数据

c++ - C++17 中的 std::map::insert 更改

c++ - 如何在 C++ 中通过 FFmpeg 将原始文件转换为音频文件 (.wav)

linux - 从 Windows 服务器读取/写入文件到 HDFS

c++ - Qt - 如何在线程中从串口读取数据

c++ - QByteArray 转换为 char(不是 char* 或 constChar*)