【问题标题】:Linux Serial Port Blocked using termios.h configuration使用 termios.h 配置阻止 Linux 串行端口
【发布时间】:2013-12-07 04:09:42
【问题描述】:

我正在编写一个嵌入式 Linux 应用程序,它 (1) 打开与另一个设备的串行连接,(2) 发送已知命令,(3) 检查端口是否有传入字符(响应),直到检测到预期的响应短语或字符, (4) 重复第 2 步和第 3 步,直到发送一系列命令并收到响应,(5) 然后关闭端口。

我的应用程序会经历上述序列的一些循环,并且当通信突然停止并且我的软件由于我的内置超时逻辑而出现故障时,它会时不时地等待响应(读取) .

我的端口配置中是否有任何内容会由于发送特定字节(可能是由于电噪声)而导致端口被阻塞?

这是我打开端口的方式(通过 termios.h 显示配置):

struct termios options;

fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd == -1) {
    debug() << "Port open failed!"
    return FAIL;
}
debug() << "Port Opened Successful"
fcntl(fd, F_SETFL, 0);                                // This setting interacts with VMIN and VTIME below

// Get options
tcgetattr(fd, &options);

// Adjust Com port options

options.c_cflag |= (CLOCAL | CREAD);                  // Program will not "own" port, enable reading on port
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);   // Sets RAW input mode (does not treat input as a line of text with CR/LF ending)
options.c_oflag &= ~ OPOST;                        // Sets RAW ouput mode (avoids newline mapping to CR+LF characters)
options.c_iflag &= ~(IXON | IXOFF | IXANY);           // Turns off SW flow c

options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 10;

// Set options
tcsetattr(fd, TCSANOW, &options);

//return fd;
return SUCCEED;

我不明白为什么当我重新启动设备时,通信突然冻结然后又消失了。谢谢大家!

更多信息 - 这是我的读写函数:

int Comm::Receive(unsigned char* rBuf)
{
    int bytes;
    ioctl(fd, FIONREAD, &bytes);
    if (bytes >= 1)
    {
        bytes = read(fd, rBuf, 1);
        if (bytes < 0)
            return READ_ERR;
        return SUCCEED;
    }
    else
        return NO_DATA_AVAILABLE;
}


int Comm::Send(int xCt, unsigned char* xBuf)
{
    int bytes;
    if (fd == -1)
        return FAIL;
    bytes = write(fd, xBuf, xCt);
    if (bytes != xCt)
        return FAIL;
    else
        return SUCCEED;
}

【问题讨论】:

    标签: linux serial-port embedded-linux blocked termios


    【解决方案1】:

    欢迎来到串口的乐趣...

    想法 1:用 select () 包装你的 read 调用

    思路 2:在 tcsetattr 中取消设置 ICANON 标志,并设置一个 VTIME 属性以进行故意超时(然后,显然,处理它)

    想法 3:关于串行通信,没有什么是完美的。

    【讨论】:

      【解决方案2】:

      在向设备发送命令和从设备读取响应时,我也遇到了类似的问题。请参阅下面的 SOF 帖子以及对我的问题有效的答案。

      在这些情况下,我们必须关心我们将用于设备通信(发送和接收)的协议。如果我们可以成功发送命令并且我们没有收到来自设备的噪音响应,则表明发送到设备的数据包中有问题。首先检查协议规范,为一个简单的命令(比如发出哔声)创建一个字节数组并发送它。

      Send data to a barcode scanner over RS232 serial port

      如果您可以将完整的源代码与输出一起发布,我可以为您做点什么。

      享受代码。谢谢。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-21
        • 1970-01-01
        • 1970-01-01
        • 2016-10-24
        相关资源
        最近更新 更多