零基础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也不能正常点亮。然后我胡乱调试,突然间就可以了 ,具体是什么原因也没有找到,很可惜没有发现到底问题出在哪里。

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

相关推荐
Navigator_Z1 小时前
LeetCode //C - 757. Set Intersection Size At Least Two
c语言·算法·leetcode
Jay_5159 小时前
C语言环形数组(循环队列)详解:原理、实现与应用
c语言·学习·嵌入式·环形数组
jmlinux9 小时前
从 C 语言计算器到串口屏应用
c语言·开发语言
阿让啊10 小时前
Notepad++如何列选
c语言·嵌入式硬件·notepad++
Archer-10 小时前
解决STM32H7系列串口DMA发送一次卡死
stm32·单片机·嵌入式硬件
通信.萌新11 小时前
【stm32f4】ADC实验(stm32hal库)
stm32·单片机·嵌入式硬件
Mr-Apple11 小时前
使用STM32设置GPIO中断
stm32·单片机·嵌入式硬件
ScilogyHunter13 小时前
vscode的c工程配置文件详解
c语言·ide·vscode
jasonslaex13 小时前
stm32传感器通用驱动代码
驱动开发·stm32·嵌入式硬件