linux-beaglebone black gpio select无法正常工作
作者:互联网
我试图检测gpio引脚何时从低变高,并且遇到麻烦.从我读过的书中,我应该可以通过以下方式将引脚配置为输入:
# echo in > /sys/class/gpio/gpio51/direction
# echo rising > /sys/class/gpio/gpio51/edge
接下来,我尝试运行一个使用select等待上升沿的c程序.代码看起来像这样(注意,我注释掉了尝试读取文件的尝试,因为如果您未设置O_NONBLOCK,则读取会被阻止):
#include<stdio.h>
#include<fcntl.h>
#include <sys/select.h>
int main(void) {
int fd = open("/sys/class/gpio/gpio51/value", O_RDONLY & ~O_NONBLOCK);
//int fd = open("/sys/class/gpio/gpio51/value", O_RDONLY | O_NONBLOCK);
//unsigned char buf[2];
//int x = read(fd, &buf, 2);
//printf("%d %d: %s\n", fd, x, buf);
fd_set exceptfds;
int res;
FD_ZERO(&exceptfds);
FD_SET(fd, &exceptfds);
//printf("waiting for %d: %s\n", exceptfds);
res = select(fd+1,
NULL, // readfds - not needed
NULL, // writefds - not needed
&exceptfds,
NULL); // timeout (never)
if (res > 0 && FD_ISSET(fd, &exceptfds)) {
printf("finished\n");
}
return 0;
}
无论引脚的状态如何(高电平或低电平),程序都会立即退出.有人能看到我的操作方式有问题吗?
PS.我有一个使用poll()执行此操作的python库,并且python可以按预期工作.我将引脚拉低,调用python,它将阻塞,将引脚拉高,代码继续.因此,我认为linux gpio驱动程序不是问题.
解决方法:
我想到了.在select调用返回之前,您必须读取文件描述符.这是一个有效的示例:
#include<stdio.h>
#include<fcntl.h>
#include <sys/select.h>
#define MAX_BUF 64
int main(void) {
int len;
char *buf[MAX_BUF];
int fd = open("/sys/class/gpio/gpio51/value", O_RDONLY);
fd_set exceptfds;
int res;
FD_ZERO(&exceptfds);
FD_SET(fd, &exceptfds);
len = read(fd, buf, MAX_BUF); //won't work without this read.
res = select(fd+1,
NULL, // readfds - not needed
NULL, // writefds - not needed
&exceptfds,
NULL); // timeout (never)
if (res > 0 && FD_ISSET(fd, &exceptfds)) {
printf("finished\n");
}
return 0;
}
标签:gpio,select,beagleboneblack,linux 来源: https://codeday.me/bug/20191030/1965151.html