stm32f103c8t6使用4x4矩阵制作多级菜单的代码hal库
时间: 2024-05-12 19:12:26 浏览: 107
STM32F103C8T6是一款常用的ARM Cortex-M3单片机,使用HAL库可以方便地进行编程。下面是使用4x4矩阵制作多级菜单的代码示例:
```c
#include "stm32f1xx_hal.h"
//定义菜单项结构体
typedef struct
{
char *name;
void (*action)(void);
struct MenuItem *subMenu;
} MenuItem;
//定义菜单数组
MenuItem mainMenu[] = {
{"Item1", NULL, NULL},
{"Item2", NULL, NULL},
{"SubMenu1", NULL, subMenu1},
{"SubMenu2", NULL, subMenu2}
};
MenuItem subMenu1[] = {
{"SubItem1", action1, NULL},
{"SubItem2", action2, NULL},
{"SubSubMenu1", NULL, subSubMenu1},
};
MenuItem subMenu2[] = {
{"SubItem3", action3, NULL},
{"SubItem4", action4, NULL},
};
MenuItem subSubMenu1[] = {
{"SubSubItem1", action5, NULL},
{"SubSubItem2", action6, NULL},
};
//定义矩阵按键对应的GPIO口和引脚
GPIO_TypeDef *rowPorts[] = {GPIOA, GPIOA, GPIOA, GPIOA};
uint16_t rowPins[] = {GPIO_PIN_0, GPIO_PIN_1, GPIO_PIN_2, GPIO_PIN_3};
GPIO_TypeDef *colPorts[] = {GPIOA, GPIOA, GPIOA, GPIOA};
uint16_t colPins[] = {GPIO_PIN_4, GPIO_PIN_5, GPIO_PIN_6, GPIO_PIN_7};
//读取矩阵按键状态
uint16_t readKeyState()
{
uint16_t keyState = 0;
for (int i = 0; i < 4; i++)
{
HAL_GPIO_WritePin(rowPorts[i], rowPins[i], GPIO_PIN_RESET);
for (int j = 0; j < 4; j++)
{
if (HAL_GPIO_ReadPin(colPorts[j], colPins[j]) == GPIO_PIN_RESET)
{
keyState |= 1 << (i * 4 + j);
}
}
HAL_GPIO_WritePin(rowPorts[i], rowPins[i], GPIO_PIN_SET);
}
return keyState;
}
//显示菜单项
void displayMenuItem(MenuItem *menu)
{
printf("%s\n", menu->name);
}
//显示菜单
void displayMenu(MenuItem *menu)
{
int i = 0;
while (menu[i].name != NULL)
{
displayMenuItem(&menu[i]);
i++;
}
}
//选择菜单项
void selectMenuItem(MenuItem *menu)
{
uint16_t keyState = 0;
while (keyState == 0)
{
keyState = readKeyState();
}
int i = 0;
while (menu[i].name != NULL)
{
if (keyState & (1 << i))
{
if (menu[i].action != NULL)
{
menu[i].action();
}
else if (menu[i].subMenu != NULL)
{
selectMenuItem(menu[i].subMenu);
}
break;
}
i++;
}
}
//主函数
int main(void)
{
HAL_Init();
//初始化GPIO口和引脚
GPIO_InitTypeDef GPIO_InitStruct = {0};
for (int i = 0; i < 4; i++)
{
GPIO_InitStruct.Pin = rowPins[i];
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(rowPorts[i], &GPIO_InitStruct);
HAL_GPIO_WritePin(rowPorts[i], rowPins[i], GPIO_PIN_SET);
GPIO_InitStruct.Pin = colPins[i];
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(colPorts[i], &GPIO_InitStruct);
}
while (1)
{
displayMenu(mainMenu);
selectMenuItem(mainMenu);
}
}
```
以上是使用HAL库实现的STM32F103C8T6多级菜单代码,该代码可以通过4x4矩阵键盘进行选择操作。相关问题如下: