Raspberry Pi GPIO自动使用Linux IOCTL自动重置为0

发布于 2025-01-24 20:55:10 字数 1084 浏览 2 评论 0原文

我的继电器连接到由Raspberry Pi 4上晶体管驱动的GPIO26。当将逻辑引脚设置为0时,继电器通常关闭(将电流输送到LED)。但是,在我的许多项目中,我曾经设置1或0,以简单地打开和关闭LED。但是,随着该继电器通常以逻辑GPIO设置为0关闭,每当我尝试编写1(这次以将其关闭)时,只要我关闭描述符,继电器恢复了其原始状态,而LED再次打开。

我的问题是:如何在应用程序寿命期间打开文件描述符的情况下如何保持逻辑值?

这是我通常的代码:

int
gpio_write(int devfd, unsigned int pin, int value)
{
    struct gpio_v2_line_request req = {
        .offsets[0] = pin,
        .config.flags = GPIO_V2_LINE_FLAG_OUTPUT,
        .num_lines = 1
    };
    struct gpio_v2_line_values val = {
        .bits = value,
        .mask = 1
    };

    if (ioctl(devfd, GPIO_V2_GET_LINE_IOCTL, &req) < 0)
        return -1;
    if (ioctl(req.fd, GPIO_V2_LINE_SET_VALUES_IOCTL, &val) < 0) {
        close(req.fd);
        return -1;
    }

    // <- HERE the value stays to what I've set (either 0 or 1).

    close(req.fd);

    // <- HERE the relay gets back to its original state (mandatory 0).
    // And for some reason, it also reverts to input.

    return 0;
}

关于GPIOS配置,我在 /boot/config.txt中没有任何奇特的幻想。

I have a relay connected to GPIO26 driven by a transistor on a Raspberry Pi 4. When the logical pin is set to 0, the relay is normally closed (delivering current to a led). However, in many of my projects I used to set 1 or 0 to simply turn on and off the led. However, with that relay normally closed with a logical GPIO set to 0 it looks like every time I try to write 1 (this time to turn it off) as long as I close the descriptor the relay get back to its original state and the led turn on again.

My question is: how can I keep the logical value without having the file descriptor open during the application lifetime?

This is my usual code:

int
gpio_write(int devfd, unsigned int pin, int value)
{
    struct gpio_v2_line_request req = {
        .offsets[0] = pin,
        .config.flags = GPIO_V2_LINE_FLAG_OUTPUT,
        .num_lines = 1
    };
    struct gpio_v2_line_values val = {
        .bits = value,
        .mask = 1
    };

    if (ioctl(devfd, GPIO_V2_GET_LINE_IOCTL, &req) < 0)
        return -1;
    if (ioctl(req.fd, GPIO_V2_LINE_SET_VALUES_IOCTL, &val) < 0) {
        close(req.fd);
        return -1;
    }

    // <- HERE the value stays to what I've set (either 0 or 1).

    close(req.fd);

    // <- HERE the relay gets back to its original state (mandatory 0).
    // And for some reason, it also reverts to input.

    return 0;
}

I don't have anything fancy in my /boot/config.txt regarding GPIOs configuration.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文