[007] [STM32] 以面向对象的思想编写按键程序

#mermaid-svg-R2XjVI6dNhh9UdXg .label{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);fill:#333;color:#333}#mermaid-svg-R2XjVI6dNhh9UdXg .label text{fill:#333}#mermaid-svg-R2XjVI6dNhh9UdXg .node rect,#mermaid-svg-R2XjVI6dNhh9UdXg .node circle,#mermaid-svg-R2XjVI6dNhh9UdXg .node ellipse,#mermaid-svg-R2XjVI6dNhh9UdXg .node polygon,#mermaid-svg-R2XjVI6dNhh9UdXg .node path{fill:#ECECFF;stroke:#9370db;stroke-width:1px}#mermaid-svg-R2XjVI6dNhh9UdXg .node .label{text-align:center;fill:#333}#mermaid-svg-R2XjVI6dNhh9UdXg .node.clickable{cursor:pointer}#mermaid-svg-R2XjVI6dNhh9UdXg .arrowheadPath{fill:#333}#mermaid-svg-R2XjVI6dNhh9UdXg .edgePath .path{stroke:#333;stroke-width:1.5px}#mermaid-svg-R2XjVI6dNhh9UdXg .flowchart-link{stroke:#333;fill:none}#mermaid-svg-R2XjVI6dNhh9UdXg .edgeLabel{background-color:#e8e8e8;text-align:center}#mermaid-svg-R2XjVI6dNhh9UdXg .edgeLabel rect{opacity:0.9}#mermaid-svg-R2XjVI6dNhh9UdXg .edgeLabel span{color:#333}#mermaid-svg-R2XjVI6dNhh9UdXg .cluster rect{fill:#ffffde;stroke:#aa3;stroke-width:1px}#mermaid-svg-R2XjVI6dNhh9UdXg .cluster text{fill:#333}#mermaid-svg-R2XjVI6dNhh9UdXg div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);font-size:12px;background:#ffffde;border:1px solid #aa3;border-radius:2px;pointer-events:none;z-index:100}#mermaid-svg-R2XjVI6dNhh9UdXg .actor{stroke:#ccf;fill:#ECECFF}#mermaid-svg-R2XjVI6dNhh9UdXg text.actor>tspan{fill:#000;stroke:none}#mermaid-svg-R2XjVI6dNhh9UdXg .actor-line{stroke:grey}#mermaid-svg-R2XjVI6dNhh9UdXg .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333}#mermaid-svg-R2XjVI6dNhh9UdXg .messageLine1{stroke-width:1.5;stroke-dasharray:2, 2;stroke:#333}#mermaid-svg-R2XjVI6dNhh9UdXg #arrowhead path{fill:#333;stroke:#333}#mermaid-svg-R2XjVI6dNhh9UdXg .sequenceNumber{fill:#fff}#mermaid-svg-R2XjVI6dNhh9UdXg #sequencenumber{fill:#333}#mermaid-svg-R2XjVI6dNhh9UdXg #crosshead path{fill:#333;stroke:#333}#mermaid-svg-R2XjVI6dNhh9UdXg .messageText{fill:#333;stroke:#333}#mermaid-svg-R2XjVI6dNhh9UdXg .labelBox{stroke:#ccf;fill:#ECECFF}#mermaid-svg-R2XjVI6dNhh9UdXg .labelText,#mermaid-svg-R2XjVI6dNhh9UdXg .labelText>tspan{fill:#000;stroke:none}#mermaid-svg-R2XjVI6dNhh9UdXg .loopText,#mermaid-svg-R2XjVI6dNhh9UdXg .loopText>tspan{fill:#000;stroke:none}#mermaid-svg-R2XjVI6dNhh9UdXg .loopLine{stroke-width:2px;stroke-dasharray:2, 2;stroke:#ccf;fill:#ccf}#mermaid-svg-R2XjVI6dNhh9UdXg .note{stroke:#aa3;fill:#fff5ad}#mermaid-svg-R2XjVI6dNhh9UdXg .noteText,#mermaid-svg-R2XjVI6dNhh9UdXg .noteText>tspan{fill:#000;stroke:none}#mermaid-svg-R2XjVI6dNhh9UdXg .activation0{fill:#f4f4f4;stroke:#666}#mermaid-svg-R2XjVI6dNhh9UdXg .activation1{fill:#f4f4f4;stroke:#666}#mermaid-svg-R2XjVI6dNhh9UdXg .activation2{fill:#f4f4f4;stroke:#666}#mermaid-svg-R2XjVI6dNhh9UdXg .mermaid-main-font{font-family:"trebuchet ms", verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-R2XjVI6dNhh9UdXg .section{stroke:none;opacity:0.2}#mermaid-svg-R2XjVI6dNhh9UdXg .section0{fill:rgba(102,102,255,0.49)}#mermaid-svg-R2XjVI6dNhh9UdXg .section2{fill:#fff400}#mermaid-svg-R2XjVI6dNhh9UdXg .section1,#mermaid-svg-R2XjVI6dNhh9UdXg .section3{fill:#fff;opacity:0.2}#mermaid-svg-R2XjVI6dNhh9UdXg .sectionTitle0{fill:#333}#mermaid-svg-R2XjVI6dNhh9UdXg .sectionTitle1{fill:#333}#mermaid-svg-R2XjVI6dNhh9UdXg .sectionTitle2{fill:#333}#mermaid-svg-R2XjVI6dNhh9UdXg .sectionTitle3{fill:#333}#mermaid-svg-R2XjVI6dNhh9UdXg .sectionTitle{text-anchor:start;font-size:11px;text-height:14px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-R2XjVI6dNhh9UdXg .grid .tick{stroke:#d3d3d3;opacity:0.8;shape-rendering:crispEdges}#mermaid-svg-R2XjVI6dNhh9UdXg .grid .tick text{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-R2XjVI6dNhh9UdXg .grid path{stroke-width:0}#mermaid-svg-R2XjVI6dNhh9UdXg .today{fill:none;stroke:red;stroke-width:2px}#mermaid-svg-R2XjVI6dNhh9UdXg .task{stroke-width:2}#mermaid-svg-R2XjVI6dNhh9UdXg .taskText{text-anchor:middle;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-R2XjVI6dNhh9UdXg .taskText:not([font-size]){font-size:11px}#mermaid-svg-R2XjVI6dNhh9UdXg .taskTextOutsideRight{fill:#000;text-anchor:start;font-size:11px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-R2XjVI6dNhh9UdXg .taskTextOutsideLeft{fill:#000;text-anchor:end;font-size:11px}#mermaid-svg-R2XjVI6dNhh9UdXg .task.clickable{cursor:pointer}#mermaid-svg-R2XjVI6dNhh9UdXg .taskText.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-R2XjVI6dNhh9UdXg .taskTextOutsideLeft.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-R2XjVI6dNhh9UdXg .taskTextOutsideRight.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-R2XjVI6dNhh9UdXg .taskText0,#mermaid-svg-R2XjVI6dNhh9UdXg .taskText1,#mermaid-svg-R2XjVI6dNhh9UdXg .taskText2,#mermaid-svg-R2XjVI6dNhh9UdXg .taskText3{fill:#fff}#mermaid-svg-R2XjVI6dNhh9UdXg .task0,#mermaid-svg-R2XjVI6dNhh9UdXg .task1,#mermaid-svg-R2XjVI6dNhh9UdXg .task2,#mermaid-svg-R2XjVI6dNhh9UdXg .task3{fill:#8a90dd;stroke:#534fbc}#mermaid-svg-R2XjVI6dNhh9UdXg .taskTextOutside0,#mermaid-svg-R2XjVI6dNhh9UdXg .taskTextOutside2{fill:#000}#mermaid-svg-R2XjVI6dNhh9UdXg .taskTextOutside1,#mermaid-svg-R2XjVI6dNhh9UdXg .taskTextOutside3{fill:#000}#mermaid-svg-R2XjVI6dNhh9UdXg .active0,#mermaid-svg-R2XjVI6dNhh9UdXg .active1,#mermaid-svg-R2XjVI6dNhh9UdXg .active2,#mermaid-svg-R2XjVI6dNhh9UdXg .active3{fill:#bfc7ff;stroke:#534fbc}#mermaid-svg-R2XjVI6dNhh9UdXg .activeText0,#mermaid-svg-R2XjVI6dNhh9UdXg .activeText1,#mermaid-svg-R2XjVI6dNhh9UdXg .activeText2,#mermaid-svg-R2XjVI6dNhh9UdXg .activeText3{fill:#000 !important}#mermaid-svg-R2XjVI6dNhh9UdXg .done0,#mermaid-svg-R2XjVI6dNhh9UdXg .done1,#mermaid-svg-R2XjVI6dNhh9UdXg .done2,#mermaid-svg-R2XjVI6dNhh9UdXg .done3{stroke:grey;fill:#d3d3d3;stroke-width:2}#mermaid-svg-R2XjVI6dNhh9UdXg .doneText0,#mermaid-svg-R2XjVI6dNhh9UdXg .doneText1,#mermaid-svg-R2XjVI6dNhh9UdXg .doneText2,#mermaid-svg-R2XjVI6dNhh9UdXg .doneText3{fill:#000 !important}#mermaid-svg-R2XjVI6dNhh9UdXg .crit0,#mermaid-svg-R2XjVI6dNhh9UdXg .crit1,#mermaid-svg-R2XjVI6dNhh9UdXg .crit2,#mermaid-svg-R2XjVI6dNhh9UdXg .crit3{stroke:#f88;fill:red;stroke-width:2}#mermaid-svg-R2XjVI6dNhh9UdXg .activeCrit0,#mermaid-svg-R2XjVI6dNhh9UdXg .activeCrit1,#mermaid-svg-R2XjVI6dNhh9UdXg .activeCrit2,#mermaid-svg-R2XjVI6dNhh9UdXg .activeCrit3{stroke:#f88;fill:#bfc7ff;stroke-width:2}#mermaid-svg-R2XjVI6dNhh9UdXg .doneCrit0,#mermaid-svg-R2XjVI6dNhh9UdXg .doneCrit1,#mermaid-svg-R2XjVI6dNhh9UdXg .doneCrit2,#mermaid-svg-R2XjVI6dNhh9UdXg .doneCrit3{stroke:#f88;fill:#d3d3d3;stroke-width:2;cursor:pointer;shape-rendering:crispEdges}#mermaid-svg-R2XjVI6dNhh9UdXg .milestone{transform:rotate(45deg) scale(0.8, 0.8)}#mermaid-svg-R2XjVI6dNhh9UdXg .milestoneText{font-style:italic}#mermaid-svg-R2XjVI6dNhh9UdXg .doneCritText0,#mermaid-svg-R2XjVI6dNhh9UdXg .doneCritText1,#mermaid-svg-R2XjVI6dNhh9UdXg .doneCritText2,#mermaid-svg-R2XjVI6dNhh9UdXg .doneCritText3{fill:#000 !important}#mermaid-svg-R2XjVI6dNhh9UdXg .activeCritText0,#mermaid-svg-R2XjVI6dNhh9UdXg .activeCritText1,#mermaid-svg-R2XjVI6dNhh9UdXg .activeCritText2,#mermaid-svg-R2XjVI6dNhh9UdXg .activeCritText3{fill:#000 !important}#mermaid-svg-R2XjVI6dNhh9UdXg .titleText{text-anchor:middle;font-size:18px;fill:#000;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-R2XjVI6dNhh9UdXg g.classGroup text{fill:#9370db;stroke:none;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);font-size:10px}#mermaid-svg-R2XjVI6dNhh9UdXg g.classGroup text .title{font-weight:bolder}#mermaid-svg-R2XjVI6dNhh9UdXg g.clickable{cursor:pointer}#mermaid-svg-R2XjVI6dNhh9UdXg g.classGroup rect{fill:#ECECFF;stroke:#9370db}#mermaid-svg-R2XjVI6dNhh9UdXg g.classGroup line{stroke:#9370db;stroke-width:1}#mermaid-svg-R2XjVI6dNhh9UdXg .classLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.5}#mermaid-svg-R2XjVI6dNhh9UdXg .classLabel .label{fill:#9370db;font-size:10px}#mermaid-svg-R2XjVI6dNhh9UdXg .relation{stroke:#9370db;stroke-width:1;fill:none}#mermaid-svg-R2XjVI6dNhh9UdXg .dashed-line{stroke-dasharray:3}#mermaid-svg-R2XjVI6dNhh9UdXg #compositionStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-R2XjVI6dNhh9UdXg #compositionEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-R2XjVI6dNhh9UdXg #aggregationStart{fill:#ECECFF;stroke:#9370db;stroke-width:1}#mermaid-svg-R2XjVI6dNhh9UdXg #aggregationEnd{fill:#ECECFF;stroke:#9370db;stroke-width:1}#mermaid-svg-R2XjVI6dNhh9UdXg #dependencyStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-R2XjVI6dNhh9UdXg #dependencyEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-R2XjVI6dNhh9UdXg #extensionStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-R2XjVI6dNhh9UdXg #extensionEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-R2XjVI6dNhh9UdXg .commit-id,#mermaid-svg-R2XjVI6dNhh9UdXg .commit-msg,#mermaid-svg-R2XjVI6dNhh9UdXg .branch-label{fill:lightgrey;color:lightgrey;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-R2XjVI6dNhh9UdXg .pieTitleText{text-anchor:middle;font-size:25px;fill:#000;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-R2XjVI6dNhh9UdXg .slice{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-R2XjVI6dNhh9UdXg g.stateGroup text{fill:#9370db;stroke:none;font-size:10px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-R2XjVI6dNhh9UdXg g.stateGroup text{fill:#9370db;fill:#333;stroke:none;font-size:10px}#mermaid-svg-R2XjVI6dNhh9UdXg g.statediagram-cluster .cluster-label text{fill:#333}#mermaid-svg-R2XjVI6dNhh9UdXg g.stateGroup .state-title{font-weight:bolder;fill:#000}#mermaid-svg-R2XjVI6dNhh9UdXg g.stateGroup rect{fill:#ECECFF;stroke:#9370db}#mermaid-svg-R2XjVI6dNhh9UdXg g.stateGroup line{stroke:#9370db;stroke-width:1}#mermaid-svg-R2XjVI6dNhh9UdXg .transition{stroke:#9370db;stroke-width:1;fill:none}#mermaid-svg-R2XjVI6dNhh9UdXg .stateGroup .composit{fill:white;border-bottom:1px}#mermaid-svg-R2XjVI6dNhh9UdXg .stateGroup .alt-composit{fill:#e0e0e0;border-bottom:1px}#mermaid-svg-R2XjVI6dNhh9UdXg .state-note{stroke:#aa3;fill:#fff5ad}#mermaid-svg-R2XjVI6dNhh9UdXg .state-note text{fill:black;stroke:none;font-size:10px}#mermaid-svg-R2XjVI6dNhh9UdXg .stateLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.7}#mermaid-svg-R2XjVI6dNhh9UdXg .edgeLabel text{fill:#333}#mermaid-svg-R2XjVI6dNhh9UdXg .stateLabel text{fill:#000;font-size:10px;font-weight:bold;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-R2XjVI6dNhh9UdXg .node circle.state-start{fill:black;stroke:black}#mermaid-svg-R2XjVI6dNhh9UdXg .node circle.state-end{fill:black;stroke:white;stroke-width:1.5}#mermaid-svg-R2XjVI6dNhh9UdXg #statediagram-barbEnd{fill:#9370db}#mermaid-svg-R2XjVI6dNhh9UdXg .statediagram-cluster rect{fill:#ECECFF;stroke:#9370db;stroke-width:1px}#mermaid-svg-R2XjVI6dNhh9UdXg .statediagram-cluster rect.outer{rx:5px;ry:5px}#mermaid-svg-R2XjVI6dNhh9UdXg .statediagram-state .divider{stroke:#9370db}#mermaid-svg-R2XjVI6dNhh9UdXg .statediagram-state .title-state{rx:5px;ry:5px}#mermaid-svg-R2XjVI6dNhh9UdXg .statediagram-cluster.statediagram-cluster .inner{fill:white}#mermaid-svg-R2XjVI6dNhh9UdXg .statediagram-cluster.statediagram-cluster-alt .inner{fill:#e0e0e0}#mermaid-svg-R2XjVI6dNhh9UdXg .statediagram-cluster .inner{rx:0;ry:0}#mermaid-svg-R2XjVI6dNhh9UdXg .statediagram-state rect.basic{rx:5px;ry:5px}#mermaid-svg-R2XjVI6dNhh9UdXg .statediagram-state rect.divider{stroke-dasharray:10,10;fill:#efefef}#mermaid-svg-R2XjVI6dNhh9UdXg .note-edge{stroke-dasharray:5}#mermaid-svg-R2XjVI6dNhh9UdXg .statediagram-note rect{fill:#fff5ad;stroke:#aa3;stroke-width:1px;rx:0;ry:0}:root{--mermaid-font-family: '"trebuchet ms", verdana, arial';--mermaid-font-family: "Comic Sans MS", "Comic Sans", cursive}#mermaid-svg-R2XjVI6dNhh9UdXg .error-icon{fill:#522}#mermaid-svg-R2XjVI6dNhh9UdXg .error-text{fill:#522;stroke:#522}#mermaid-svg-R2XjVI6dNhh9UdXg .edge-thickness-normal{stroke-width:2px}#mermaid-svg-R2XjVI6dNhh9UdXg .edge-thickness-thick{stroke-width:3.5px}#mermaid-svg-R2XjVI6dNhh9UdXg .edge-pattern-solid{stroke-dasharray:0}#mermaid-svg-R2XjVI6dNhh9UdXg .edge-pattern-dashed{stroke-dasharray:3}#mermaid-svg-R2XjVI6dNhh9UdXg .edge-pattern-dotted{stroke-dasharray:2}#mermaid-svg-R2XjVI6dNhh9UdXg .marker{fill:#333}#mermaid-svg-R2XjVI6dNhh9UdXg .marker.cross{stroke:#333}

:root { --mermaid-font-family: "trebuchet ms", verdana, arial;}
#mermaid-svg-R2XjVI6dNhh9UdXg .summary_topic > * { fill:#7B68EE !important; stroke:#ccc !important; stroke-width:3px !important; color:#FFF !important; }
#mermaid-svg-R2XjVI6dNhh9UdXg .summary_topic tspan { fill:#FFF !important; }
#mermaid-svg-R2XjVI6dNhh9UdXg .topic0 > * { fill:#39f !important; stroke:#ccc !important; stroke-width:5px !important; color:#FFF !important; }
#mermaid-svg-R2XjVI6dNhh9UdXg .topic0 tspan { fill:#FFF !important; }
#mermaid-svg-R2XjVI6dNhh9UdXg .topic1 > * { fill:#7FFFAA !important; stroke:#3CB371 !important; stroke-width:2px !important; }
#mermaid-svg-R2XjVI6dNhh9UdXg .topic1 tspan { !important; }
#mermaid-svg-R2XjVI6dNhh9UdXg .topic2 > * { fill:#FFFAF0 !important; stroke:#FFA500 !important; stroke-width:1px !important; }
#mermaid-svg-R2XjVI6dNhh9UdXg .topic2 tspan { !important; }
#mermaid-svg-R2XjVI6dNhh9UdXg .topic4 > * { fill:#FFF0F5 !important; stroke:#FFB6C1 !important; stroke-width:1px !important; }
#mermaid-svg-R2XjVI6dNhh9UdXg .topic4 tspan { !important; }
#mermaid-svg-R2XjVI6dNhh9UdXg {
color: rgba(0, 0, 0, 0.75);
font: ;
}

STM32
CubeMX配置
按键管理框架
按键驱动层
按键驱动框架层
按键管理层
应用示例

本文为百问网&韦东山【物联网智能家居实战训练营】课程笔记

声明:本项目参考:MultiButton


1 CubeMX配置

在这里插入图片描述

  1. RCC:配置HSE为晶体/陶瓷谐振器
  2. SYS:Debug选择SW模式
  3. 时钟:选择HSE作为PLL时钟源,将其改为8MHz(默认),然后选择PLLCLK作为系统时钟源,设为系统时钟为72MHz
  4. 按键引脚:PA0(wk_up)下拉输入,PA15(key1)和PC5(key0)上拉输入
  5. LED引脚:PA8(红灯)和PD2(黄灯)设为推挽输出,默认输出高电平
  6. TIM6:向上计数模式(TIM6&7只支持向上计数),psc = 72 - 1,arr = 1000 - 1,即1ms更新中断,然后配置NVIC使能TIM6全局中断
  7. USART1:TX-PA9,RX-PA10,用于打印按键触发事件信息
  8. 以单独的c/h文件生成MDK工程

2 按键管理框架

2.1 按键驱动层

按键底层驱动通过CubeMX配置相应引脚GPIO模式,然后调用HAL库初始化:

void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOC_CLK_ENABLE();

  GPIO_InitStruct.Pin = WKUP_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLDOWN;
  HAL_GPIO_Init(WKUP_GPIO_Port, &GPIO_InitStruct);

  GPIO_InitStruct.Pin = KEY0_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  HAL_GPIO_Init(KEY0_GPIO_Port, &GPIO_InitStruct);

  GPIO_InitStruct.Pin = KEY1_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  HAL_GPIO_Init(KEY1_GPIO_Port, &GPIO_InitStruct);
}

2.2 按键驱动框架层

按键驱动框架比较简单,将获取IO电平的HAL库函数二次封装一下即可:

uint8_t wkup_key_read_pin(void)
{
    return HAL_GPIO_ReadPin(WKUP_GPIO_Port, WKUP_Pin);
}

uint8_t key0_read_pin(void)
{
    return HAL_GPIO_ReadPin(KEY0_GPIO_Port, KEY0_Pin);
}

uint8_t key1_read_pin(void)
{
    return HAL_GPIO_ReadPin(KEY1_GPIO_Port, KEY1_Pin);
}

2.3 按键管理层

2.3.1 按键对象状态

enum key_state {
    Init_None_State = 0,        /* 初始未按下状态 */
    Init_Press_State,           /* 初次按下状态 */
    Press_Check_State,          /* 连击检查状态 */
    Continuous_Press_State,     /* 连续按下状态 */
    Long_Press_State,           /* 长按状态 */
};

2.3.2 按键对象事件

enum key_event { 
    Press_Down = 0,             /* 按键按下,每次按下都触发 */
    Press_Up,                   /* 按键弹起,每次松开都触发 */
    Singe_Click,                /* 单击触发(仅触发一次) */
    Double_Click,               /* 双击触发(仅触发一次) */
    Short_Press_Repeat,         /* 每次短按时都会触发(按下次数>=2) */
    Long_Press_Start,           /* 首次进入长按状态触发(仅触发一次) */
    Long_Press_Hold,            /* 长按保持状态触发(每经过一个循环长按间隔触发一次) */
    Event_Sum,                  /* 事件总数 */
    None_Press                  /* 未按下 */
};

2.3.3 按键对象句柄结构体

struct key_handle
{
    uint16_t tick;                                          	  /* 按键系统时间片 */
    uint8_t repeat_cnt     : 4;                             	  /* 按键短按次数 */
    uint8_t event   	   : 4;                             	  /* 触发事件 */
    uint8_t state          : 3;                             	  /* 按键状态 */
    uint8_t debounce_tick  : 3;                             	  /* 消抖时间片 */
    uint8_t active_level   : 1;                                   /* 按键有效按下电平 */
    uint8_t key_level      : 1;                             	  /* 按键引脚当前电平 */
    uint8_t (* pin_read)(void);                         	      /* 获取按键引脚电平 */
    void (* event_callback[Event_Sum])(struct key_handle* key);   /* 按键事件回调函数 */
    struct key_handle* next;                                      /* 单向链表next指针 */
};
typedef struct key_handle *key_handle_t;

2.3.4 初始化按键对象

static key_handle_t _key_slist_head = NULL;  // 按键管理单链表头结点

/**
 * @brief   初始化按键对象
 * @param   key             按键对象句柄
 * @param   gpio_pin_read   获取按键电平函数指针
 * @param   active_level    按键按下有效电平
 * @return  0: succeed -1: failed
 */
int8_t key_init(struct key_handle *key, uint8_t (*gpio_pin_read)(void), uint8_t active_level)
{
    if (key == NULL)
        return -1;
    memset(key, 0, sizeof(struct key_handle));
    key->event = None_Press;
    key->active_level = active_level;
    key->pin_read = gpio_pin_read;
    key->key_level = key->pin_read();

    return 0;
}

2.3.5 注册按键

/**
 * @brief   注册按键:将按键对象插入到按键管理链表中
 * @param   key 按键对象句柄
 * @return  0: succeed -1: failed
 */
int8_t key_handle_register(struct key_handle *key)
{
    struct key_handle *key_slist_node = _key_slist_head;  // 获取头指针的地址 (无头结点单链表)

    if (key == NULL)
        return -1;

    // 尾插(不带头结点的单链表, 头指针需做特殊判断)
    if (_key_slist_head == NULL) // 头指针为空==表空
    {
        _key_slist_head = key;
        key->next = NULL;
        return 0;
    }

    while(key_slist_node)
    {
        if (key_slist_node == key) return -1;       // 重复注册
        if(key_slist_node->next == NULL) break;     // 已经遍历到最后一个节点,必须在此跳出循环, 否则key_slist_node==NULL
        key_slist_node = key_slist_node->next;
    }
    key_slist_node->next = key;  
    key->next = NULL; 

    return 0;
}

2.3.6 脱离按键

/**
 * @brief   脱离按键:将按键对象从按键管理链表中脱离
 * @param   key 按键对象句柄
 * @return  0: succeed -1: failed
 */
int8_t key_handle_detach(struct key_handle *key)
{
    // 解1级引用指向指针变量, 解2级引用指向指针变量所指向的变量 
    struct key_handle **key_slist_node = &_key_slist_head;  // 指向头指针, 直接操作原指针变量(不然最后无法修改头指针)
    struct key_handle *node_temp;
    if (key == NULL || _key_slist_head == NULL)
        return -1;

    while(*key_slist_node && *key_slist_node != key)
    {
        node_temp = *key_slist_node;
        if((*key_slist_node)->next == NULL) break;
        key_slist_node = &node_temp->next;     // 不能直接解1级引用赋值,会破坏原链表
    }

    if (*key_slist_node != key)
        return -1;
    *key_slist_node = (*key_slist_node)->next;

    return 0;
}

2.3.7 注册事件回调函数

/**
 * @brief   注册按键事件触发回调函数
 * @param   key             按键对象句柄
 * @param   event           触发事件类型
 * @param   event_callback  事件回调函数
 * @return  0: succeed -1: failed
 */
int8_t key_event_callback_register(struct key_handle *key, uint8_t event, void (* event_callback)(key_handle_t key))
{
    if (key == NULL || event >= Event_Sum)
        return -1;
    key->event_callback[event] = event_callback;

    return 0;
}

2.3.8 按键状态机

在这里插入图片描述

状态符号 按键对象状态 含义
state0 Init_None_State 初始未按下状态
state1 Init_Press_State 初次按下状态
state2 Press_Check_State 连击检查状态
state3 Continuous_Press_State 连续按下状态
state5 Long_Press_State 长按状态
/**
 * @brief   处理所有按键对象的状态机
 * @param   key 按键对象句柄
 * @return  None
 */
static void key_handler(struct key_handle *key)
{
    uint8_t key_level_temp = key->pin_read();

    if(key->state != Init_None_State) key->tick++;

    /* 按键消抖(按键状态发生变化保持DEBOUNCE_TICK时间片开始保存按键引脚电平) */
    if(key_level_temp != key->key_level)
    {
        if(++(key->debounce_tick) >= Double_Click)
        {
            key->key_level = key_level_temp;
            key->debounce_tick = 0;
        }
    }
    else
    {
        key->debounce_tick = 0;
    }
        
    /* 按键状态机 */
    switch (key->state)
    {
    case Init_None_State:
        /* 初始态-> 初始按下态  Press_Down */
        if(key->key_level == key->active_level)   
        {
            key->event = (uint8_t)Press_Down;
            __KEY_EVENT_CALL(Press_Down);
            key->tick  = 0;
            key->repeat_cnt = 1;
            key->state  = Init_Press_State;
        }
        else
        {
            key->event = (uint8_t)None_Press;
        }    
        break;

    case Init_Press_State:
        /* 第一次按下松开:初始按下态->连击检查态  Press_Up */
        if(key->key_level != key->active_level)
        {
            key->event = (uint8_t)Press_Up;
            __KEY_EVENT_CALL(Press_Up);
            key->tick = 0;
            key->state = Press_Check_State;

        }
        /* 第一次按下后长按(>LONG_PRESS_START_TICK):初始按下态->长按态  Long_Press_Start */
        else if(key->tick > LONG_PRESS_START_TICK)
        { 
            key->event = (uint8_t)Long_Press_Start;
            __KEY_EVENT_CALL(Long_Press_Start);
            key->state = Long_Press_State;
        }
        break;

    case Press_Check_State:
        /* 松开后再次按下:连击检查态->连击态 Press_Down & Short_Press_Repeat */
        if(key->key_level == key->active_level)
        {
            key->event = (uint8_t)Press_Down;
            __KEY_EVENT_CALL(Press_Down);
            key->repeat_cnt++;
            __KEY_EVENT_CALL(Short_Press_Repeat);
            key->tick = 0;
            key->state = Continuous_Press_State;
        } 
        /* 松开后再次没有按下(>SHORT_PRESS_START_TICK):连击检查态->初始态 repeat_cnt=1: Singe_Click; repeat_cnt=2: Double_Click */
        else if(key->tick > SHORT_PRESS_START_TICK)
        {                
            if(key->repeat_cnt == 1)
            {
                key->event = (uint8_t)Singe_Click;
                __KEY_EVENT_CALL(Singe_Click);
            }
            /* 连击态松开后会返回此条件下触发  todo: <可以做n连击判断> */
            else if(key->repeat_cnt == 2)
            {
                key->event = (uint8_t)Double_Click;
                __KEY_EVENT_CALL(Double_Click);
            }
            key->state = Init_None_State;
        }
        break;

    case Continuous_Press_State:
        /* 连击后松开:连击态->连击检查态(< SHORT_PRESS_START_TICK)) : 连击态->初始态(>= SHORT_PRESS_START_TICK) */
        if(key->key_level != key->active_level)
        {
            key->event = (uint8_t)Press_Up;
            __KEY_EVENT_CALL(Press_Up);

            if(key->tick < SHORT_PRESS_START_TICK)
            {
                key->tick = 0;
                key->state = Press_Check_State;
            }
            else
            {
                key->state = Init_None_State;
            }
        }
        /* 连击后长按(>SHORT_TICKS): 连击态 -> 初始态 */
        else if(key->tick > SHORT_PRESS_START_TICK)
        {
            key->state = Init_Press_State;  // 可以回到Init_None_State/Init_Press_State
        }
        break;

    case Long_Press_State:
        /* 长按保持  Long_Press_Hold */
        if(key->key_level == key->active_level)
        {
            key->event = (uint8_t)Long_Press_Hold;
            if (key->tick % LONG_HOLD_CYCLE_TICK == 0)     
            {
                __KEY_EVENT_CALL(Long_Press_Hold);
            }
        }
        /* 长按松开:长按态-> 初始态 */
        else
        {
            key->event = (uint8_t)Press_Up;
            __KEY_EVENT_CALL(Press_Up);

            key->state = Init_None_State;
        }
        break;
    }  
}

2.3.9 遍历调用按键对象

/**
 * @brief   每经过一个滴答周期调用一次按键处理函数(裸机放1ms中断, OS放线程或中断)
 * @param   None
 * @return  None
 */
void key_tick(void)
{
    struct key_handle *key_slist_node;
    static uint8_t tick_cnt = 0;

    if (++tick_cnt < CHECK_TICK)
        return;
    
    for (key_slist_node = _key_slist_head; key_slist_node != NULL; key_slist_node = key_slist_node->next)
    {
        key_handler(key_slist_node);
    }
    tick_cnt = 0;
}

注意:裸机环境下,函数必须在中断中(默认1ms,可修改)调用,上RTOS可以在线程上下文中检测。

3 应用示例

static struct key_handle _key0;
static void key0_event_callback(key_handle_t key)
{
    switch(key->event)
    {
    case Press_Down:
        UART_DEBUG("key0 press down");
    break;

    case Press_Up:
        UART_DEBUG("key0 press up");
    break;

    case Singe_Click:
        UART_DEBUG("key0 single click");
    break;

    case Double_Click:
        UART_DEBUG("key0 double click");
    break;

    case Short_Press_Repeat:
        UART_DEBUG("key0 short press repeat");
    break;

    case Long_Press_Start:
        UART_DEBUG("key0 long press start");
    break;

    case Long_Press_Hold:
        key_handle_detach(&_key0);
        UART_DEBUG("key0 long press hold");
    break;

    default:
    break;
    }
}

void key_test_sample(void)
{
    key_init(&_key0, key0_read_pin, GPIO_PIN_RESET);
    key_event_callback_register(&_key0, Press_Down,         key0_event_callback);
    key_event_callback_register(&_key0, Press_Up,           key0_event_callback);
    key_event_callback_register(&_key0, Singe_Click,        key0_event_callback);
    key_event_callback_register(&_key0, Double_Click,       key0_event_callback);
    key_event_callback_register(&_key0, Short_Press_Repeat, key0_event_callback);
    key_event_callback_register(&_key0, Long_Press_Start,   key0_event_callback);
    key_event_callback_register(&_key0, Long_Press_Hold,    key0_event_callback);
    key_handle_register(&_key0);
}

在定时器中断回调函数里检测:

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    if (htim->Instance == TIM6)
    {
        key_tick();
    }
}

串口打印信息:
在这里插入图片描述


代码已开源到gitee:以面向对象思想编写的按键管理框架

END

版权声明:本文为CSDN博主「柯西的彷徨」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/kouxi1/article/details/123008273

生成海报
点赞 0

柯西的彷徨

我还没有学会写个人说明!

暂无评论

发表评论

相关推荐

【STM32Cube笔记】2-STM32Cube安装教程

【STM32Cube笔记】系列文章目录 1-基于STM32的VSCode入门级教程前言 2-STM32Cube安装教程 3-STM32CubeIDE汉化 4-STM32Cube配置时钟设置 5-跑马灯引脚配置 6-Cortex-M7内核基本配

STM32F4最小系统硬件设计

对于硬件工程师来讲,想要入门STM32相关的开发,我想除了深入阅读一下STM32的数据手册外,最实用且有效的方法就是自己实际做一个STM32的最小系统板了。本文将以一个小的STM32F427VG的电路最