如下是根据项目经过验证的结果,不多说,直接上代码。
建立物理按键程序,很简单如下:
按键初始化:
hj_key_init(void)
按键扫描:
uint8_t hj_key_scan(uint8_t mode)
下面是物理按键代码:
#include "hj_key.h"
#define KEY0 gpio_read(key1_GPIO_Port, key1_Pin)
#define KEY1 gpio_read(key2_GPIO_Port, key2_Pin)
#define KEY2 gpio_read(key3_GPIO_Port, key3_Pin)
#define KEY0_PRES 1
#define KEY1_PRES 2
#define KEY2_PRES 3
void hj_key_init(void)
{
gpio_set_input( key1_GPIO_Port, key1_Pin, GPIO_MODE_IT_RISING);
gpio_set_input( key2_GPIO_Port, key2_Pin, GPIO_MODE_IT_RISING);
gpio_set_input( key3_GPIO_Port, key3_Pin, GPIO_MODE_IT_RISING);
gpio_set_event_enable(key1_EXTI_IRQn);
gpio_set_event_enable(key2_EXTI_IRQn);
gpio_set_event_enable(key3_EXTI_IRQn);
}
uint8_t hj_key_scan(uint8_t mode)
{
static uint8_t key_up = 1;
if (mode == 1)
key_up = 1;
if(key_up&&(KEY0==0||KEY1==1||KEY2==0))
{
key_up=0;
if(KEY0==0)
return KEY0_PRES;
else if(KEY1==1)
return KEY1_PRES;
else if(KEY2==0)
return KEY2_PRES;
}else if(KEY0 == 1 && KEY1 == 0 && KEY2 == 1)
key_up=1;
return 0;
}
最后需要对接touchgfx接口,我们需要继承 ButtonController 类,我将建立 hj_keycontroller.hpp,代码如下:
#ifndef TARGET_HJ_KEYCONTROLLER_HPP_
#define TARGET_HJ_KEYCONTROLLER_HPP_
#include <platform/driver/button/ButtonController.hpp>
namespace touchgfx
{
class KeyController : public ButtonController
{
public:
KeyController();
virtual ~KeyController();
virtual void init();
virtual bool sample(uint8_t& key);
};
}
#endif /* TARGET_HJ_KEYCONTROLLER_HPP_ */
然后实现类的方法,代码如下:
#include "hj_keycontroller.hpp"
#include "hj_key.h"
using namespace touchgfx;
KeyController::KeyController()
{
}
KeyController::~KeyController()
{
}
void KeyController::init()
{
}
bool KeyController::sample(uint8_t& key)
{
uint8_t keyValue = hj_key_scan(0);
if(keyValue !=0)
{
key = keyValue;
return true;
}
return false;
}
最后,由于博主时间关系,不能更加详细描述原理,更多详细的需要了解,请私信我,欢迎交流~