2023版 STM32实战2 按键驱动(电路与代码都讲解)

常规电路(带上拉电阻)

阻值可选3.3/4.7/5.1/10 单位K

 

 

偷懒电路

利用GPIO内部的上拉模式

 

 

 

 

代码(直接拷贝使用)

 

这是一个按键控制灯亮灭的demo
为了新手方便我直接都写在了main.c文件

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include "stm32f10x.h"
 
 
void LED_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_GPIOE, ENABLE);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_Init(GPIOB, &GPIO_InitStructure);
    GPIO_Init(GPIOE, &GPIO_InitStructure);
}
 
void KEY_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE, ENABLE);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3|GPIO_Pin_4;
    GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPU;
    GPIO_Init(GPIOE, &GPIO_InitStructure);
}
 
void delay(u32 time)
{
    while(time--);
}
 
int main(void)
{  
    LED_Init();
    KEY_Init();
    while(1)
    {
        if( GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_3)==0 )
        {
            GPIO_ResetBits(GPIOB,GPIO_Pin_5);
        }
        else if( GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_4)==0 )
        {
            GPIO_SetBits(GPIOB,GPIO_Pin_5);
        }
    }
}

 

  

工程获取

三连后点击下方头像

 

posted @   日落悬崖  阅读(468)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示