RDPUser
Posts: 140
Joined: Tue Jan 30, 2018 12:18 pm

GPIO access via bashscript and sysfs: Block until GPIO changes / interrupt handling

Sun Jul 14, 2019 12:43 pm

Via

Code: Select all

cd /sys/class/gpio
sudo echo 26 > export
cd gpio26/
sudo echo in > direction
cat value
the state of the GPIO pin can be read.
Now I want that "cat value" or a similiar command blocks until the GPIO value changes.
Already tried
sudo echo rising > edge but after that cat value still doesn't block.

Any ideas how to to it with simple file system?

User avatar
joan
Posts: 14257
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: GPIO access via bashscript and sysfs: Block until GPIO changes / interrupt handling

Sun Jul 14, 2019 1:40 pm

I am fairly sure you can't with the sysfs interface. You will need to write a program.

RDPUser
Posts: 140
Joined: Tue Jan 30, 2018 12:18 pm

Re: GPIO access via bashscript and sysfs: Block until GPIO changes / interrupt handling

Mon Jul 15, 2019 9:57 am

It is possible with sysfs interface https://raspberrypi.stackexchange.com/q ... terface-wi
But the question is is it possible with bash only?

User avatar
joan
Posts: 14257
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: GPIO access via bashscript and sysfs: Block until GPIO changes / interrupt handling

Mon Jul 15, 2019 10:25 am

Let me rephrase the answer. The sysfs interface (/sys/class/gpio) provides no way. You will have to write a program.

E.g.

Code: Select all

/* 2014-07-06
   wfi.c

   gcc -o wfi wfi.c

   ./wfi [gpio]
*/

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>
#include <poll.h>

#define GPIO 4

int main(int argc, char *argv[])
{
   char str[256];
   struct timeval tv;
   struct pollfd pfd;
   int fd, gpio;
   char buf[8];

   /*
      Prior calls assumed.
      sudo sh -c "echo 4      >/sys/class/gpio/export"
      sudo sh -c "echo in     >/sys/class/gpio/gpio4/direction"
      sudo sh -c "echo rising >/sys/class/gpio/gpio4/edge"
   */

   if (argc > 1) gpio = atoi(argv[1]);
   else          gpio = GPIO;

   sprintf(str, "/sys/class/gpio/gpio%d/value", gpio);

   if ((fd = open(str, O_RDONLY)) < 0)
   {
      fprintf(stderr, "Failed, gpio %d not exported.\n", gpio);
      exit(1);
   }

   pfd.fd = fd;

   pfd.events = POLLPRI;

   lseek(fd, 0, SEEK_SET);    /* consume any prior interrupt */
   read(fd, buf, sizeof buf);

   poll(&pfd, 1, -1);         /* wait for interrupt */

   lseek(fd, 0, SEEK_SET);    /* consume interrupt */
   read(fd, buf, sizeof buf);

   exit(0);
}

Return to “Advanced users”