本文介绍了Linux的串行读抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从我的串口读取使用下面的C code。我可以成功地写入监听计算机(耶!),但读抛出错误(code 11 - 资源暂时不可用)。我也注意到我的邮件/ dmesg的日志没有关于故障的任何信息,等等。所以这是很好的。

  // A的一堆INCLUDES存在这里....在了codeINT FD = 0;
INT状态= 0;
诠释运行= 1;
炭缓冲器[100];
CHAR消息[7];无效的主要(){
    FD = 1;    FD =打开(/开发/ ttyM0,O_RDWR | O_NOCTTY);    如果(FD == -1)
    {
        PERROR(open_port:无法打开/ dev / ttyS0来);
    }
    其他
    {
        而(运行< 20)
        {
            sprintf的(消息,测试%d个\\ r,即运行);
            状态=写(FD,消息,6);            如果(状态℃下)
            {
                的printf(写入状态=%d个\\ n%S \\ n,错误号,字符串错误(错误));
            }
            状态=读(FD,缓冲液,8); //这引发错误(11)。我的连接设备正在写测试/ R            如果(状态℃下)
            {
                的printf(错误读取状态=%d个\\ n%S \\ n,错误号,字符串错误(错误));
                //关闭(FD);
                运行=跑+ 1;
            }
            其他
            {
                的printf(%S \\ n \\ r,即缓冲);
            }
            睡眠(2);
        }
        关闭(FD);
    }} // END MAIN

这是我为我的串口设置。我试图在9600 8位,无奇偶校验,1个停止位为读/写。我觉得我的设置是正确的。

 须藤的stty -a -f /开发/ ttyM0
速度9600波特;行0;列0;行= 0;
INTR = ^ C;退出= ^ \\;擦除= ^?;杀= ^ U; EOF = ​​^ D; EOL =<民主基金取代; EOL2 =<民主基金取代;
动开关= LT;民主基金取代;开始= ^ Q;停止= ^ S;停赛= ^ Z; rprnt = ^ R; WERASE = ^ W; LNEXT = ^ V;
冲水= ^ O;分= 1;时间= 0;
-parenb -parodd CS8 HUPCL -cstopb CREAD CLOCAL -crtscts
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr ICRNL IXON -ixoff -iuclc -ixany
-imaxbel -iutf8
OPOST -olcuc -ocrnl ONLCR -onocr -onlret -ofill -ofdel NL0 CR0 TAB0 BS0 VT0 FF0
ISIG ICANON IEXTEN回声ECHOE ECHOK -echonl -noflsh -xcase -tostop -echoprt ECHOCTL ECHOKE

任何帮助将非常AP preciated。谢谢!


解决方案

Looks like termios is setup for canonical input (based on the icanon in the stty output). In canonical (aka cooked) mode, the characters received from the serial port are processed before being made available to the user program using read().

Per the Linux man page:

Your termios also has icrnl set, which means that a carriage return is translated to newline on input (unless igncr is set, which is not since it has a preceding hyphen). Both eol and eol2 are undefined (which are the default values).

So for your setup, an end-of-line is defined as a newline or a carriage return (or cntl-D at the start of the line). Verify that your remote device is actually sending a CR or LF control character to terminate the line. Your comment in the code indicates that it is not (i.e. "/r" is not a carriage return).


To properly use the text returned by read() as a string, set the request for one less than the allocated buffer size (to ensure room for appending a null terminator). Then after a good return, use the returned byte count as the index to store the string terminator.

        status = read(fd, buffer, sizeof(buffer) - 1);
        if (status < 0) {
            /* handle error condition */
        } else {
            buffer[status] = '\0';
            printf("%s\n\r", buffer);
        }

这篇关于Linux的串行读抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 16:09
查看更多