我這里依然使用的是野火開發板,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也不能正常點亮。然后我胡亂調試,突然間就可以了 ,具體是什么原因也沒有找到,很可惜沒有發現到底問題出在哪里。
不管怎么說,實驗最后還是成功了。