详细文档
一、硬件介绍
我使用的是扩展板上的独立按键,使用板载的按键需自行更改管脚
二、原理讲解
按键的触发我们采用的是下降沿中断的方式,按键不按下的时候默认是搞电平,当我们按键按下的时候引脚被拉低,此时产生一个下降沿,然后就可以去执行中断回调函数了。
三、代码
1.头文件
/*
* Copyright (c) 2006-2020, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2021-02-11 冷月枫 the first version
*/
#include "rtthread.h"
#ifndef APPLICATIONS_KEY_KEY_H_
#define APPLICATIONS_KEY_KEY_H_
#define KEY1_PIN GET_PIN(A,1) // 扩展板按键
#define KEY2_PIN GET_PIN(A,2) // 扩展板按键
#define KEY3_PIN GET_PIN(A,3) // 扩展板按键
#define KEYUser_PIN GET_PIN(H,4) // 板载的按键
void Key_init();
#endif /* APPLICATIONS_KEY_KEY_H_ */
2.源文件
/*
* Copyright (c) 2006-2020, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2021-02-11 冷月枫 the first version
*/
#include "key.h"
#include "rtdevice.h"
#include "drv_common.h"
#include "rtthread.h"
#include "LED.h"
/* 按键中断回调函数 */
void Key_handler()
{
static uint8_t i = 0;
LED3_ONOFF(i % 2);
i ++;
}
/* 按键初始化 */
void Key_init()
{
rt_pin_mode(KEY1_PIN, PIN_MODE_INPUT); // 输入模式
rt_pin_mode(KEY2_PIN, PIN_MODE_INPUT); // 输入模式
rt_pin_mode(KEY3_PIN, PIN_MODE_INPUT_PULLUP); // 输入模式
/* 配置中断 */
/* 绑定中断 */
rt_pin_attach_irq(KEY1_PIN, PIN_IRQ_MODE_FALLING , Key_handler, RT_NULL); // 下降沿触发
/* 使能中断 */
rt_pin_irq_enable(KEY1_PIN, PIN_IRQ_ENABLE);
}
四、效果
可运行代码自行操作。