C++串口使用Write()只响应一次

标签 c++ serial-port

下面的所有代码都有效。我的设备响应,C,7 是重置。当我第二次运行它时,它没有响应。如果我手动关闭和打开我的设备,然后再次运行此脚本它会起作用。但如果我第二次按下按钮运行脚本,则不会。

RS232:57600,8,N,1

有什么想法吗?是否需要更多信息来解决此问题?

*此外,当我开始工作时,我将不得不使用 read() 函数来获取设备响应。基于以下代码,有人知道我需要使用的正确格式吗?抱歉,我是 C++ 的新手...我更喜欢 PHP。

*我也不知道1024对不对,不过好像还行吧……

#include <termios.h>

int fd;
struct termios options;
fd=open("/dev/tty.KeySerial1", O_RDWR | O_NOCTTY | O_NDELAY);
fcntl(fd, F_SETFL, 0);
tcgetattr(fd,&options);
options.c_ispeed=57600;
options.c_ospeed=57600;
options.c_cflag |= (CLOCAL | CREAD);
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_cflag &= ~CSTOPB;
options.c_lflag &= ~ECHO;
options.c_oflag &= ~ECHO;
options.c_oflag &= ~OPOST;
options.c_cflag |= CS8;
options.c_cflag |= CRTSCTS;
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] =10;
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&options);

write(fd, "C,7\r\n", 1024);

close(fd);

最佳答案

1024 实际上可能是您的问题。 write() 函数的第三个参数表示要写入的字节数:

ssize_t write(int fildes, const void *buf, size_t nbyte);

参见 man page for write()了解详情。

在您的情况下,数字应为 5,因为您要发送 5 个字符(“C”、“7”、“\r”和“\n”)。

通过提供值 1024,您实际上是通过串行 channel 发送另外 1019 个垃圾字符。

更新:

read() 函数具有几乎相同的参数:

ssize_t read(int fildes, void *buf, size_t nbyte);

请注意,您必须提供一个可写缓冲区作为第二个参数。例如,要读取 12 个字节,您可以使用:

char someData[12];
read(fd, someData, 12);

我不太确定如何确定您需要阅读的字符数,但函数返回的 ssize_t 数字会告诉您实际阅读了多少。

关于C++串口使用Write()只响应一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1609127/

相关文章:

c++ - int(x) 是做什么的?

c++ - 错误: expected primary-expression before ‘double’

linux - 如何修改netcat的输入流?

python - FT2232h/FT42232h 兼容全双工串行监视器

node.js - 无法在 Windows 10 上运行串口

linux - Linux中的TCP转串口用于Matlab访问

c++ - Libcurl 返回损坏的数据

c++ - 如何在 .dll 类方法参数中传递对象?

boost - 如何使用 asio 执行非阻塞读取?

c++ - 使用 std::vector.push_back() 时出现错误 C2280