从 gpio 输入读取的字节数为零

number bytes read from gpio input is zero

我在尝试读取 gpio 输出引脚时出现了一些奇怪的行为。 我得到第一次读取 return 1(读取 1 个字节),但所有下一次读取都来自同一个 gpio return 0。我认为它应该始终读取 1,因为总有一些东西可以读取输入引脚。

gpio = 8;
fd = open("/sys/class/gpio/export", O_WRONLY);
sprintf(buf, "%d", gpio);
rc = write(fd, buf, strlen(buf));
if (rc == -1)
    printf("failed in write 17\n");
close(fd);
sprintf(buf, "/sys/class/gpio/gpio%d/direction", gpio);
fd = open(buf, O_WRONLY);
rc = write(fd, "in", 2);
if (rc == -1)
    printf("failed in write 18\n");
close(fd);
sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio);
gpio_tdo = open(buf, O_RDWR);
rc = read(gpio_tdo, &value, 1);   <-- rc here is 1

rc = read(gpio_tdo, &value, 1);   <-- rc here is 0

rc = read(gpio_tdo, &value, 1);   <-- rc here is 0

从gpio输入读取一个字节应该总是return 1 ?

来自man read

On files that support seeking, the read operation commences at the current file offset, and the file offset is incremented by the number of bytes read. If the current file offset is at or past the end of file, no bytes are read, and read() returns zero.

所以可能你需要在二读之前执行lseek,像这样:

read(gpio_tdo, &value, 1);
lseek(gpio_tdo, 0, SEEK_SET);
read(gpio_tdo, &value, 1);

您的第二个选择是关闭文件并在执行第二个操作之前重新打开它 read:

close(gpio_tdo);
gpio_tdo = open(buf, O_RDWR);
read(gpio_tdo, &value, 1);

但这似乎有点开销。我会选择第一个选项 (lseek)。

有用的阅读:gpio in sysfs