C 编写一个按钮,在按下时执行一次任务(锁存器)

标签 c button raspberry-pi debouncing

我对 c 和 Raspberry Pi 比较陌生,正在尝试简单的程序。我想要的是,当按下按钮时,它会 printfs 一次,并且在再次按下按钮之前不会再次 printf,即使按下按钮(某种闩锁)也是如此。我想也许添加第二个 while 循环可以解决这个问题,但有时它仍然检测不到按钮按下。

#include <bcm2835.h>
#include <stdio.h>
#define PIN RPI_GPIO_P1_11

int main()
{
    if(!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(PIN, BCM2835_GPIO_FSEL_INPT);

    while(1)
    {
        if(bcm2835_gpio_lev(PIN))
        {
            printf("The button has been pressed\n");
        }

       while(bcm2835_gpio_lev(PIN)){}
    }

    bcm2835_close();
    return 0;
}

最佳答案

你的逻辑是正确的,如果按钮是完美的,这会起作用。但他们不是。您必须去抖动按钮的信号。实现该目标的两种方法(结合使用效果最佳):

我。在按钮的两个引脚之间添加一个电容器(或尝试 an even more sophisticated button debouncer circuitry ),和/或

二。使用软件去抖动(伪 C):

while (1) {
    while (!button_pressed)
        ;

    printf("Button pressed!\n");


    while (elapsed_time < offset)
        ;
}

等等

编辑:正如@jerry 所指出的,当按住按钮时,以上内容无法“正确”工作。这里有几个 more professional code snippets您可以使用它来满足所有要求。

关于C 编写一个按钮,在按下时执行一次任务(锁存器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16306901/

相关文章:

python - raspberryPi python 包安装在哪里?

C 输入问题

c - 使用指针将数组传递给函数

c++ - 证明两点法有效(对和)

c - 从 WinForms (GDI+) 迁移到 WPF 时如何替换 DrawClosedCurve/FillClosedCurve?

android - postDelayed阻塞ui线程

html - 无法对齐多个按钮上的文本/链接 - 菜鸟级别

ubuntu - 如何使 Ubuntu Mate headless (headless)并在 Raspberry Pi 上自动登录?

ios - animateWithDuration 和 UIViewAnimationOptionsAllowUserInteraction

raspberry-pi - 如何更改树莓派的屏幕分辨率