gpt4 book ai didi

c++ - 写入/dev/ttyS0 后读取 0 个字节

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:13:09 24 4
gpt4 key购买 nike

我一直在尝试通过/dev/ttyS 设备在 Linux 上执行串行通信,但是当我在写入后尝试从它们读取数据时,我没有读取到任何数据。

我有以下代码

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>

int main() {
printf("hello world\n");
int n;
int fd;
char c;
int bytes;

char buffer[10];
char *bufptr;
int nbytes;
int tries;
int x;
struct termios options;

fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY);
if(fd == -1) {
perror("open_port: Unable to open:");
} else

tcgetattr(fd, &options);

// Set the baudrate, same speed for both I/O
cfsetispeed(&options, B150);
cfsetospeed(&options, B150);

// Enable reading
options.c_cflag |= (CLOCAL | CREAD);

// Set 'RAW' mode
cfmakeraw(&options);

// Set byte size
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;

// Set parity
// options.c_cflag &= ~PARENB;
options.c_cflag |= PARENB;
options.c_cflag |= PARODD;
options.c_cflag &= ~CSTOPB;

// Set StopBits, @Linux no OneHalf is supproted, so OneHalf and Two are the same
options.c_cflag &= ~CSTOPB;

// Set Handshake options
// options.c_iflag |= CRTSCTS;
// options.c_iflag &= ~CRTSCTS;
// options.c_cflag &= ~( IXON | IXOFF | IXANY );
options.c_cflag |= IXON | IXOFF | IXANY;

// Set Timeouts
options.c_cc[VMIN] = 0; // read() will return after receiving character
options.c_cc[VTIME] = 10; // == 0 - infinite timeout, != 0 - sets timeout in deciseconds

tcsetattr(fd, TCSANOW, &options);
tcflush(fd, TCIOFLUSH);

bytes = write(fd, "ATZ\r",4);
printf(" wrote %d bytes\n", bytes);
bufptr = buffer;

bytes = read(fd, bufptr, sizeof(buffer));
printf("number of bytes read is %d\n", bytes);
perror ("read error:");

for (x = 0; x < 10 ; x++) {
c = buffer[x];
printf("%d ",c);
}

tcflush(fd, TCIOFLUSH);
close(fd);
printf("\n");
return (0);
}

程序输出如下

hello world
wrote 4 bytes
number of bytes read is 0
read error:: Success
0 0 0 0 0 0 0 0 0 0

虽然我希望它能读取我刚写的 4 个字符,但它似乎读取了 0 个字节。如果我将 VTIME 设置为 0,则永远读取 block 。我尝试执行 echo/dev/ttyS0 但没有输出。知道是什么原因造成的吗?如何解决?

最佳答案

您的代码显然没问题,除了以下事实:

  • 您调用 perror("read error"); 在调用 printf(3) 之后, 而不是在 read(2) 之后 因此可能的错误(如果发生)被屏蔽到对 read(2) 的调用调用printf(3) .如果要打印读取字符数,保存errno的值和来自 read(2) 的返回值打电话前printf(3) ,然后,如果返回的错误为负,则调用 perror(3) .

  • 无论如何。 c_cc[VTIME] = 10施加一秒超时,这对于重置调制解调器来说太过分了。您的线路设置是:

    CS8, Parity ODD, one STOP bit, and 150 baudrate

    通常,调制解调器会响应 ATZ\r命令重置后,这需要一些时间(通常超过一秒)并且以默认调制解调器速度(因为您已重置它)并且不是这个速度您已发送 AT命令。

    出于这个原因,重置调制解调器通常是盲目的,然后您发送一个简单的 AT\r命令,为了请求 \r\nOK\r\n回复。 AT\r的答案命令通常是即时的,而不是作为对重置命令的响应,并让调制解调器根据接收到的字符调整其通信设置。

    调制解调器总是在 A 时调整它们的速度和 T接收到序列,通过对以高采样频率接收到的方波脉冲进行采样,然后它们将速度切换到检测到的速度并通常进行速度转换(使得可以以不同于远程协商的速度与调制解调器通信)

关于c++ - 写入/dev/ttyS0 后读取 0 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58537101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com