• 按键控制LED灯亮灭


    按键原理图:按键选用PE4

     创建两个文件一个.c文件一个.h文件来写按键的代码

    .c文件

    1. #include "Key.h"
    2. void Key_Init(void)
    3. {
    4. RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE,ENABLE);
    5. GPIO_InitTypeDef GPIO_InitStruct;
    6. GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU; //上拉输入
    7. GPIO_InitStruct.GPIO_Pin = GPIO_Pin_4;
    8. GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    9. GPIO_Init(GPIOE,&GPIO_InitStruct); //初始化PE端口
    10. }
    11. uint8_t key_scan(void)
    12. {
    13. if(GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_4) == KEY_ON) //判断按键的按下
    14. {
    15. while(GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_4) == KEY_ON); //确认按键的按下
    16. return KEY_ON; //返回1
    17. }
    18. else
    19. {
    20. return KEY_OFF; //返回0
    21. }
    22. }

    .h文件

    1. #ifndef __KEY_H
    2. #define __KEY_H
    3. #include "stm32f10x.h" // Device header
    4. #define KEY_ON 1 //宏定义
    5. #define KEY_OFF 0
    6. uint8_t key_scan(void);
    7. void Key_Init(void);
    8. #endif

    LED灯原理图: 选用PE5

     

    创建两个文件一个.c文件一个.h文件来写LED灯的代码

    .c文件

    1. #include "Led.h"
    2. void LED_Init(void)
    3. {
    4. RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE,ENABLE); //开启时钟
    5. GPIO_InitTypeDef GPIO_InitStruct; //定义GPIO结构体
    6. GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP; //推挽输出
    7. GPIO_InitStruct.GPIO_Pin = GPIO_Pin_5; //选用引脚5
    8. GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    9. GPIO_Init(GPIOE,&GPIO_InitStruct);
    10. GPIO_SetBits(GPIOE,GPIO_Pin_5); //上电默认熄灭
    11. }
    12. void LED_ON()
    13. {
    14. GPIO_ResetBits(GPIOE,GPIO_Pin_5); //灯亮
    15. }
    16. void LED_OFF()
    17. {
    18. GPIO_SetBits(GPIOE,GPIO_Pin_5); //灯灭
    19. }

     .h文件

    1. #ifndef __LED_H
    2. #define __LED_H
    3. #include "stm32f10x.h" // Device header
    4. void LED_Init(void);
    5. void LED_ON(void);
    6. void LED_OFF(void);
    7. #define LED1_TOGGLE {GPIOE->ODR ^=GPIO_Pin_5;} //绿灯状态翻转 异或操作
    8. #endif

    main函数

    1. #include "stm32f10x.h" // Device header
    2. #include "Key.h"
    3. #include "Led.h"
    4. int main(void)
    5. {
    6. LED_Init();
    7. Key_Init();
    8. while(1)
    9. {
    10. if(key_scan() == KEY_ON) //获取按键返回值
    11. {
    12. LED1_TOGGLE; //LED灯翻转
    13. }
    14. }
    15. }

     

  • 相关阅读:
    2022世界杯La‘eeb肖像,python海龟实现啦
    【前端】jquery获取data-*的属性值
    spring 单元测试注解
    轻松学会JavaScript事件
    RK3399平台入门到精通系列讲解(导读篇)21天学习挑战介绍
    thinkphp学习10-数据库的修改删除
    Go语言 Map
    一体式水利视频监控站 遥测终端视频图像水位水质水量流速监测
    网页下拉菜单
    用户登录模块---Druid+JDBC+Servlet
  • 原文地址:https://blog.csdn.net/m0_69211839/article/details/133972172