3

I have some strange behaviour when trying to read gpio output pin. I get that the first read return 1 (1 bytes read), but all next read from same gpio return 0. I would assume that it should always read 1, because there is always something to read from input pin.

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

Should the read of one byte from the gpio input always return 1 ?

ransh
  • 1,589
  • 4
  • 30
  • 56

1 Answers1

3

From 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.

So probably you need to execute lseek before second reading, like this:

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

The second choice you have is to close file and reopen it before doing second read:

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

But it seems like a bit overhead. I'd go with first option (lseek).

Useful reading: gpio in sysfs

Sam Protsenko
  • 14,045
  • 4
  • 59
  • 75