Files
JYF_STC15W4K_wireless_charge/Lib/KeyScan.c

55 lines
1.4 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* KeyScan.c - 按键扫描模块 */
#include "KeyScan.h"
// 按键状态机结构体
typedef struct
{
uint8_t prev_state; // 前次状态
uint8_t edge_trigger; // 边沿触发标志
uint8_t scan_counter; // 扫描计数器
} KeyStateMachine;
static KeyStateMachine key_state = { 0xFF, 0x00, 0 };
/*******************************************
* 初始化函数
*******************************************/
void
Key_Init (void)
{
// 配置P2.4-P2.1为准双向口
P2M0 &= 0xE1;
P2M1 &= 0xE1;
// 初始化按键状态
key_state.prev_state = (KEY1 * 0x08) | (KEY2 * 0x04) | (KEY3 * 0x02) | KEY4;
}
/*******************************************
* 按键扫描函数
* 需在主循环中周期性调用
*******************************************/
void
Key_Scan (void)
{
const uint8_t current = (KEY1 * 0x08) | (KEY2 * 0x04) | (KEY3 * 0x02) | KEY4;
// 边沿检测
const uint8_t falling_edge
= (key_state.prev_state ^ current) & key_state.prev_state;
key_state.edge_trigger |= falling_edge; // 累积触发事件
key_state.prev_state = current; // 更新历史状态
}
/*******************************************
* 按键事件获取接口(供外部模块调用)
* 返回4位掩码对应KEY4-KEY1的触发状态
*******************************************/
uint8_t
Get_KeyEvents (void)
{
const uint8_t events = key_state.edge_trigger;
key_state.edge_trigger = 0; // 读取后清除标志
return events;
}