Skip to content

Instantly share code, notes, and snippets.

@rutles
Last active January 4, 2023 09:39
Show Gist options
  • Save rutles/6505809 to your computer and use it in GitHub Desktop.
Save rutles/6505809 to your computer and use it in GitHub Desktop.
Raspberry Pi GPIO polling by wait for event example. Most simple code. No count errors.
/*
gpio_poll.c
Raspberry Pi GPIO polling example.
Hardware: A switch (hardware pulluped) shall be connected to GPIO25.
Compile: cc gpio_poll.c -o gpio_poll
Execute: sudo ./gpio_poll.c
*/
#include <fcntl.h>
#include <stdio.h>
#include <poll.h>
int main(){
int i;
int fd;
int ret;
struct pollfd pfd;
char c;
//Enable gpio25
fd = open("/sys/class/gpio/export", O_WRONLY);
write(fd, "25", 2);
close(fd);
//Set gpio25 as input
fd = open("/sys/class/gpio/gpio25/direction", O_WRONLY);
write(fd, "in", 2);
close(fd);
//Set gpio25 interrupt
fd = open("/sys/class/gpio/gpio25/edge", O_WRONLY);
//write(fd, "falling", 7);
write(fd, "both", 4);
close(fd);
//Wait for event, repeat 10 times
fd = open("/sys/class/gpio/gpio25/value", O_RDONLY);
pfd.fd = fd;
pfd.events = POLLPRI;
for(i = 1; i <= 10; i++){
lseek(fd, 0, SEEK_SET);
ret = poll(&pfd, 1, 3000);
read(fd, &c, 1);
printf("%d: ", i);
if(ret == 0)
printf("Timeout\n");
else
if(c == '0')
printf("Push\n");
else
printf("Release\n", i, c);
}
close(fd);
//Disable gpio25
fd = open("/sys/class/gpio/unexport", O_WRONLY);
write(fd, "25", 2);
close(fd);
return(0);
}
@7-mb
Copy link

7-mb commented May 25, 2018

what does "Release" mean?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment