hc32l13x实现4x5矩阵键盘,一个ch455实现键盘灯光,具体实现代码
时间: 2023-12-21 12:03:48 浏览: 81
下面是一个简单的示例代码,实现了使用HC32L13x芯片控制4x5矩阵键盘,以及使用CH455芯片控制键盘灯光。
```c
#include "hc32l13x.h"
#define KEY_PORT GPIO_PORT_1
#define KEY_PIN GPIO_PIN_0
#define LED_PORT GPIO_PORT_2
#define LED_PIN GPIO_PIN_0
uint8_t key_map[4][5] = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20}
};
void key_init(void)
{
stc_gpio_config_t gpio_cfg;
Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE);
gpio_cfg.enDir = GpioDirIn;
gpio_cfg.enDrv = GpioDrvH;
gpio_cfg.enPuPd = GpioPu;
gpio_cfg.enOD = GpioOdDisable;
gpio_cfg.enCtrlMode = GpioAHPPad;
Gpio_Init(KEY_PORT, KEY_PIN, &gpio_cfg);
gpio_cfg.enDir = GpioDirOut;
gpio_cfg.enDrv = GpioDrvH;
gpio_cfg.enPuPd = GpioNoPuPd;
gpio_cfg.enOD = GpioOdDisable;
gpio_cfg.enCtrlMode = GpioAHPPad;
Gpio_Init(LED_PORT, LED_PIN, &gpio_cfg);
}
uint8_t key_scan(void)
{
uint8_t i, j;
uint8_t key_code = 0;
for (i = 0; i < 4; i++) {
Gpio_SetIO(LED_PORT, LED_PIN, TRUE);
for (j = 0; j < 5; j++) {
if (!Gpio_GetIO(KEY_PORT, KEY_PIN)) {
key_code = key_map[i][j];
break;
}
}
Gpio_SetIO(LED_PORT, LED_PIN, FALSE);
if (key_code != 0) {
break;
}
}
return key_code;
}
void ch455_init(void)
{
stc_gpio_config_t gpio_cfg;
Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE);
gpio_cfg.enDir = GpioDirOut;
gpio_cfg.enDrv = GpioDrvH;
gpio_cfg.enPuPd = GpioNoPuPd;
gpio_cfg.enOD = GpioOdDisable;
gpio_cfg.enCtrlMode = GpioAHPPad;
Gpio_Init(LED_PORT, LED_PIN, &gpio_cfg);
}
void ch455_set_led(uint8_t on)
{
Gpio_SetIO(LED_PORT, LED_PIN, on);
}
int main(void)
{
uint8_t key_code;
key_init();
ch455_init();
while (1) {
key_code = key_scan();
if (key_code != 0) {
ch455_set_led(TRUE);
} else {
ch455_set_led(FALSE);
}
}
return 0;
}
```
在上面的代码中,我们先定义了一个`key_map`数组,表示4x5矩阵键盘中每个按键对应的编号。在`key_init`函数中,我们初始化了HC32L13x的GPIO模块,将KEY_PIN设置为输入模式,并开启上拉电阻。在`key_scan`函数中,我们通过循环扫描矩阵键盘,当检测到按键按下时,返回按键编号。在`ch455_init`函数中,我们初始化了CH455的GPIO模块,将LED_PIN设置为输出模式。在`ch455_set_led`函数中,我们控制LED_PIN的电平,从而控制键盘灯光的亮灭。在主函数中,我们不断循环调用`key_scan`函数,当检测到按键按下时,就调用`ch455_set_led`函数点亮键盘灯光。
阅读全文