零基础RT-thread第二节:按键控制

我这里依然使用的是野火开发板,F767芯片。

这一节写一下按键控制LED亮灭。

这是按键以及LED的原理图。

按键对应的引脚不按下时是低电平,按下后是高电平。

LED是在低电平点亮。

接下来是key.c:

c 复制代码
/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2025-06-13     c       the first version
 */

#include "key.h"

/* 初始化按键引脚 */
void key_init(void)
{
    rt_pin_mode(KEY1_PIN, PIN_MODE_INPUT);
    rt_pin_mode(KEY2_PIN, PIN_MODE_INPUT);
}

/* 获取指定按键状态 */
rt_bool_t key_state_get(rt_base_t pin)
{
    if(rt_pin_read(pin))
    {
        while(rt_pin_read(pin));
        return 1;
    }
    else {
        return 0;
    }
}

然后是key.h文件

c 复制代码
/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2025-06-13     c       the first version
 */
#ifndef APPLICATIONS_KEY_H_
#define APPLICATIONS_KEY_H_

#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>

#define KEY1_PIN GET_PIN(A, 0)
#define KEY2_PIN GET_PIN(C, 13)


void key_init(void);

rt_bool_t key_state_get(rt_base_t pin);

#endif /* APPLICATIONS_KEY_H_ */

最后是main.c文件:

c 复制代码
// main.c
#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>
#include <key.h>

#define DBG_TAG "main"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

#define LED_R_PIN    GET_PIN(H, 10)  // PH10 (122)
#define LED_G_PIN    GET_PIN(H, 11)  // PH11 (123)
#define LED_B_PIN    GET_PIN(H, 12)  // PH12 (124)

static rt_base_t led_r_stat = PIN_LOW;
static rt_base_t led_g_stat = PIN_HIGH;
static rt_base_t led_b_stat = PIN_HIGH;

int main(void)
{
    LOG_I("System startup!");

    rt_pin_mode(LED_R_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(LED_G_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(LED_B_PIN, PIN_MODE_OUTPUT);

    rt_pin_write(LED_G_PIN, led_g_stat);
    rt_pin_write(LED_B_PIN, led_b_stat);

    while (1)
    {
        if (key_state_get(KEY1_PIN)) {//key1控制红灯 
            led_r_stat = (led_r_stat == PIN_LOW) ? PIN_HIGH : PIN_LOW;
            rt_pin_write(LED_R_PIN, led_r_stat);
        }
        if (key_state_get(KEY2_PIN)) {//key2控制绿灯
            led_g_stat = (led_g_stat == PIN_LOW) ? PIN_HIGH : PIN_LOW;
            rt_pin_write(LED_G_PIN, led_g_stat);
        }
        rt_thread_mdelay(500);
    }
    return RT_EOK;
}

这段代码很简单,但其实我在写代码时遇到了很多问题,按键一直不管用,LED也不能正常点亮。然后我胡乱调试,突然间就可以了 ,具体是什么原因也没有找到,很可惜没有发现到底问题出在哪里。

不管怎么说,实验最后还是成功了。

相关推荐
czhaii40 分钟前
STC32G144K246,高速PWM@240Mhz 运行测试
stm32·单片机·fpga开发
小龙报1 小时前
《数组和函数的实践游戏---扫雷游戏(基础版附源码)》
c语言·开发语言·windows·游戏·创业创新·学习方法·visual studio
炸膛坦客1 小时前
Cortex-M3-STM32F1 开发:(十一)ARM Cortex-M 内核中的 MPU 和 FPU
arm开发·stm32·嵌入式硬件
逐步前行2 小时前
C数据结构--线性表(顺序表|单链表|双向链表)
c语言·数据结构·链表
草莓工作室3 小时前
数据结构13:排序
c语言·数据结构·排序算法
屈冠成3 小时前
C语言数组:编辑世界的坚固桥梁
c语言·开发语言·算法
应用市场3 小时前
STM32卡尔曼滤波算法详解与实战应用
人工智能·stm32·算法
zyq99101_13 小时前
树与二叉树的奥秘全解析
c语言·数据结构·学习·1024程序员节
AICodeThunder4 小时前
【S组篇】C++知识点总结(1):并查集基础
c语言·数据结构·c++·算法·图论
傲世(C/C++,Linux)4 小时前
C标准库-时间函数
c语言