Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C语言的Linux中清除串行端口上的数据?_C_Linux_Serial Port_Baud Rate - Fatal编程技术网

在C语言的Linux中清除串行端口上的数据?

在C语言的Linux中清除串行端口上的数据?,c,linux,serial-port,baud-rate,C,Linux,Serial Port,Baud Rate,我正在测试发送和接收程序,代码如下 main()函数如下所示: #include "lib.h" int fd; int initport(int fd) { struct termios options; // Get the current options for the port... tcgetattr(fd, &options); // Set the baud rates to 19200... cfsetispeed(&options,

我正在测试发送和接收程序,代码如下

main()函数如下所示:

#include "lib.h"

int fd;

int initport(int fd) {
    struct termios options;
    // Get the current options for the port...
    tcgetattr(fd, &options);
    // Set the baud rates to 19200...
    cfsetispeed(&options, B9600);
    cfsetospeed(&options, B9600);
    // Enable the receiver and set local mode...
    options.c_cflag |= (CLOCAL | CREAD);

    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;

    // Set the new options for the port...
    tcsetattr(fd, TCSANOW, &options);
    return 1;
}

int main(int argc, char **argv) {

    fd = open("/dev/pts/2", O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd == -1) {
        perror("open_port: Unable to open /dev/pts/1 - ");
        return 1;
    } else {
        fcntl(fd, F_SETFL, 0);
    }

    printf("baud=%d\n", getbaud(fd));
    initport(fd);
    printf("baud=%d\n", getbaud(fd));

    char sCmd[254];
    sCmd[0] = 0x41;
    sCmd[1] = 0x42;
    sCmd[2] = 0x43;
    sCmd[3] = 0x00;

    if (!writeport(fd, sCmd)) {
        printf("write failed\n");
        close(fd);
        return 1;
    }

    printf("written:%s\n", sCmd);

    usleep(500000);
    char sResult[254];
    fcntl(fd, F_SETFL, FNDELAY); 

    if (!readport(fd,sResult)) {
        printf("read failed\n");
        close(fd);
        return 1;
    }
    printf("readport=%s\n", sResult);
    close(fd);
    return 0;
}

lib.h包含读写代码,如下所示:

并得到了问题:

为了使用串行端口进行测试,我使用socat()在Linux上创建了一对串行端口,并使用这些端口测试我的程序

程序第一次发送数据和程序接收数据时正常。但是,如果我再次读取或甚至将新数据重新写入串行端口,则返回数据始终为空,直到我停止虚拟串行端口并再次启动它,则写入和读取数据正常,但仍然只有一次

(在实际情况中,发送部分将由另一个设备完成,我只是负责从串行端口读取数据。我编写这两个部分只是为了测试我的读取代码。)


有人有什么想法吗?

您的评论或代码有误:

// Set the baud rates to 19200... 
cfsetispeed(&options, B9600); 
cfsetospeed(&options, B9600); 
这说明它将把波特率设置为19200,但实际上它将波特率设置为9600。也许你想要这个:

// Set the baud rates to 19200... 
cfsetispeed(&options, B19200);
cfsetospeed(&options, B19200);

我看到一个bug(可能与您的问题无关):在验证
iIn1>0
之前,不要分配给
result[iIn-1]
,您能解释一下原因吗?顺便说一下,我写的是iIn<0而不是iIn>0