Last active
January 4, 2023 09:39
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what does "Release" mean?