# 错误操作,此提交无法运行
This commit is contained in:
@ -1,22 +1,55 @@
|
||||
/* KeyScan.c - 按键扫描模块 */
|
||||
#include "KeyScan.h"
|
||||
|
||||
void main() {
|
||||
Key_Init(); // 初始化按键模块
|
||||
Timer0_Init(); // 配置1ms定时器
|
||||
|
||||
while(1) {
|
||||
// 在定时器中断服务例程中调用Key_Scan()
|
||||
if(Get_KeyEvents()) {
|
||||
// 执行按键处理逻辑
|
||||
uint8_t keys = Get_KeyEvents();
|
||||
if(keys & 0x08) { /* KEY1处理 */ }
|
||||
if(keys & 0x04) { /* KEY2处理 */ }
|
||||
// ...其他按键处理
|
||||
}
|
||||
}
|
||||
// 按键状态机结构体
|
||||
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;
|
||||
}
|
||||
|
||||
// // Timer0中断服务函数
|
||||
// void Timer0_ISR() interrupt 1 {
|
||||
// Key_Scan(); // 定时扫描按键
|
||||
// }
|
||||
/*******************************************
|
||||
* 按键扫描函数
|
||||
* 需在主循环中周期性调用
|
||||
*******************************************/
|
||||
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;
|
||||
}
|
Reference in New Issue
Block a user