【问题标题】:Clear data at serial port in Linux in C?在C中的Linux中清除串行端口的数据?
【发布时间】:2010-03-28 03:19:55
【问题描述】:

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

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 包含的读写代码如下:

Parse and read data frame in C?

并得到了问题:

为了使用串口进行测试,我使用 socat (https://help.ubuntu.com/community/VirtualSerialPort) 在 Linux 上创建了一对串口并使用这些端口测试我的程序。

程序第一次发送数据,程序接收到数据就ok了。但是,如果我再次读取甚至将新数据重新写入串口,返回数据始终为空,直到我停止虚拟串口并重新启动它,然后写入和读取数据都可以,但仍然,只有一次。

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

有人有什么想法吗?

【问题讨论】:

  • 我看到一个错误(可能与您的问题无关):在验证 iIn1 > 0 之前不要分配给 result[iIn-1]
  • 您能解释一下为什么吗?顺便说一句,我写了 iIn 0

标签: c linux serial-port baud-rate


【解决方案1】:

您的评论或代码有误:

// 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);

【讨论】:

    猜你喜欢
    • 2010-10-30
    • 2012-09-10
    • 2013-06-05
    • 1970-01-01
    • 2014-10-01
    • 2011-05-03
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    相关资源
    最近更新 更多