零基础RT-thread第二节:按键控制
我这里依然使用的是野火开发板,F767芯片。
这一节写一下按键控制LED亮灭。
这是按键以及LED的原理图。
按键对应的引脚不按下时是低电平,按下后是高电平。
LED是在低电平点亮。
接下来是key.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文件
/** 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文件:
// 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也不能正常点亮。然后我胡乱调试,突然间就可以了 ,具体是什么原因也没有找到,很可惜没有发现到底问题出在哪里。
不管怎么说,实验最后还是成功了。