c - 让微 Controller 即使在等待时也总是注意到按下按钮(延迟)

标签 c button wait microcontroller stm32

我在这里使用的是 stm32l 发现微 Controller 。 首先,我为 LED 和用户按钮的 gpio 端口初始化端口。

我现在让它工作了,我现在的小程序让 LED 灯闪烁。 每次按下按钮时,等待时间都会变长,从而使 LED 闪烁时间变长。现在的问题是,一旦等待时间超过 4 秒或更长时间,微 Controller 就很难注意到按钮被按下了。 有没有办法让它总是注意到按下按钮

int main(void) {
        char *RCCp = (char*) 0x40023800;
        int *PAp = (int *) 0x40020000;
        int *PBp = (int *) 0x40020400;

        // RCC Config
        *((int*) (RCCp + 28)) |= 0x3f;
        *((int*) (RCCp + 32)) |= 1;

    // Pin config
        *PBp = 0x5000;
        *PAp = 0x0000;

        int speed = 100000;

            int i = 0;
            while (1) {
                while (i++ < speed); // Waiting time
                *(int*) (0x40020414) ^= 0xC0; 

                i = 0;

                if ((*(int*) (0x40020010) & 0x0001) != 0x0) {

                    speed = speed * 2;

                    if (speed > 400000) {

                        speed = 100000;
                    }

                }

            }


        return 0;
    }

最佳答案

向前迈出的一小步是在忙等待循环中轮询开关状态。像这样:

        int i = 0;
        while (1) {
            bool wasSwitchClosedThisPeriod = false;
            while (i++ < speed) {
                // Poll the switch to see if it is closed.
                if ((*(int*)(0x40020010) & 0x0001) != 0) {
                    wasSwitchClosedThisPeriod = true;
                }
            }

            *(int*) (0x40020414) ^= 0xC0; 

            i = 0;

            if (wasSwitchClosedThisPeriod) {

                speed = speed * 2;

                if (speed > 400000) {

                    speed = 100000;
                }

            }

        }

但是还有很大的改进空间。例如,您可能想要对开关进行去抖动。开关数据寄存器应该是易失的,即*(int volatile *)(0x40020010UL)。使用中断可以使代码更加灵活、高效,甚至允许您在微 Controller 等待时让其进入休眠状态(省电)。如果 GPIO 输入引脚可以配置为中断,那么您就不需要轮询开关。如果有可用的硬件定时器,那么您可以将其配置为在需要更换 LED 时中断。

关于c - 让微 Controller 即使在等待时也总是注意到按下按钮(延迟),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35397997/

相关文章:

c - 通过访问禁止的内存位置注入(inject)内存异常

Android Lollipop 应用程序没有响应

c - 处理 SIGCHLD 会将 EOF 返回给父亲,为什么?

编译一个可以以管理员身份运行的C程序,无需手动设置

C - 使用 unsigned int 是否只是糟糕的编码实践?

关闭管道和复制管道

php - 使用 onclick 按钮更新数据库信息

android - 按钮背景图像拉伸(stretch)(wrap_content 或 dp 使用)

java - 单击了哪个按钮。 Java、Netbeans

javascript - 在 Cypress 测试中,如果预期的 XHR 请求未发出 : waitUntil() with click XHR condition? ,如何重试按钮单击?