我正在尝试使用poll()函数获取基于gpio的中断,这些中断在beaglebone gpio上工作。下面是我的代码,但简而言之:
当我把插脚接地时,什么也没有发生(如预期的那样)。
当我将pin连接到high时,会产生一个中断。然而,它要么永远不会清除,要么再生得非常快。我实现了一个计数,当它上升时,在几秒钟内计数器就远远超过10000。我的设置有遗漏吗?问题可能出在main()函数中,但为了完整起见,我包含了其他函数。
谢谢你的帮助,
查尔斯

#define SYSFS_GPIO_DIR "/sys/class/gpio"
#define MAX_BUF 64

int gpio_export(unsigned int gpio)
{
    int fd, len;
    char buf[MAX_BUF];

    fd = open(SYSFS_GPIO_DIR "/export", O_WRONLY);
    if (fd < 0) {
        perror("gpio/export");
        return fd;
    }

    len = snprintf(buf, sizeof(buf), "%d", gpio);
    write(fd, buf, len);
    close(fd);

    return 0;
}

int gpio_set_dir(unsigned int gpio, unsigned int direction)
{
    int fd, len;
    char buf[MAX_BUF];

    len = snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR  "/gpio%d/direction", gpio);

    fd = open(buf, O_WRONLY);
    if (fd < 0) {
        perror("gpio/direction");
        return fd;
    }

    if (direction)
        write(fd, "out", 4);
    else
        write(fd, "in", 3);

    close(fd);
    return 0;
}

int gpio_set_edge(unsigned int gpio, char *edge)
{
    int fd, len;
    char buf[MAX_BUF];

    len = snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/edge", gpio);

    fd = open(buf, O_WRONLY);
    if (fd < 0) {
        perror("gpio/set-edge");
        return fd;
    }

    write(fd, edge, strlen(edge) + 1);
    close(fd);
    return 0;
}

int gpio_fd_open(unsigned int gpio)
{
    int fd, len;
    char buf[MAX_BUF];

    len = snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio);

    fd = open(buf, O_RDONLY | O_NONBLOCK );
    if (fd < 0) {
        perror("gpio/fd_open");
    }
    return fd;
}

int gpio_fd_close(int fd)
{
    return close(fd);
}

int main()
{
    struct pollfd fdset;
    int nfds = 1;
    int gpio_fd, timeout, rc;
    char *buf[MAX_BUF];
    unsigned int gpio;
    int len;
    char* c;


    gpio = 26;

    gpio_export(gpio);
    gpio_set_dir(gpio, 0);
    gpio_set_edge(gpio, "rising");
    gpio_fd = gpio_fd_open(gpio);

    timeout = 1;

    while (1) {
        memset((void*)&fdset, 0, sizeof(fdset));

        fdset.fd = gpio_fd;
        fdset.events = POLLPRI | POLLERR;

        len = read(fdset.fd, c, 1);

        rc = poll(&fdset, nfds, timeout);

        //printf("POLLPRI is %02x, POLLERR is %02x\r\n", POLLPRI, POLLERR);

        if (rc < 0) {
            printf("\npoll() failed!\n");
            return -1;
        }

        if (rc == 0) {
            printf(".");
        }

        if (fdset.revents & POLLPRI) {
            if (len==-1)
            {
                printf("Hex of revents is %02x, return code is %02x\r\n", fdset.revents, rc);
            }
            len = read(fdset.fd, buf, MAX_BUF);
        }

        if (fdset.revents & POLLERR)
        {
            printf("errno: %d", errno);
        }
    }

    gpio_fd_close(gpio_fd);
    return 0;
}

最佳答案

我在beaglebone black上重新安装了debian映像,它现在可以正常工作了。我不知道为什么它以前不工作,但它看起来像是一个操作系统的问题。

10-07 19:23
查看更多