• STM32单片机入门学习(五)-按钮控制LED


    按钮和LED接线

    LED负极接B12,正极接VCC

    按钮一端接B13,一端接GND,按下为低电平,松开为高电平

    如图:

    主程序代码:main.c
    1. #include "stm32f10x.h"
    2. #include "Delay.h" //delay函数所在头文件
    3. #include "LED.h"
    4. #include "KEY.h"
    5. int main(void)
    6. {
    7. int isdown;
    8. LED_Init(); //初始化LED
    9. LED_OFF(); //默认LED灭
    10. KEY_Init(); //初始化KEY
    11. while(1)
    12. {
    13. isdown = Key_IsDown(); //循环判断按钮是否被按下
    14. if(isdown == 1)
    15. {
    16. LED_ON();
    17. }
    18. else
    19. {
    20. LED_OFF();
    21. }
    22. }
    23. }
     LED.h和LED.c

    LED.h

    1. #ifndef __LED_H
    2. #define __LED_H
    3. void LED_Init(void);
    4. void LED_ON(void);
    5. void LED_OFF(void);
    6. #endif

    LED.c

    1. #include "stm32f10x.h"
    2. void LED_Init(void)
    3. {
    4. RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //设置时钟
    5. GPIO_InitTypeDef GPIOInitStruct;
    6. GPIOInitStruct.GPIO_Mode = GPIO_Mode_Out_PP; //推挽模式
    7. GPIOInitStruct.GPIO_Pin = GPIO_Pin_12; //B12
    8. GPIOInitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    9. GPIO_Init(GPIOB, &GPIOInitStruct);
    10. GPIO_SetBits(GPIOB, GPIO_Pin_12); // 不亮
    11. }
    12. void LED_ON(void)
    13. {
    14. GPIO_ResetBits(GPIOB, GPIO_Pin_12); // 亮
    15. }
    16. void LED_OFF(void)
    17. {
    18. GPIO_SetBits(GPIOB, GPIO_Pin_12); // 不亮
    19. }

    KEY.h和KEY.c

    KEY.h

    1. #ifndef __KEY_H
    2. #define __KEY_H
    3. void KEY_Init(void);
    4. unsigned char Key_IsDown(void);
    5. #endif

    KEY.c

    1. #include "stm32f10x.h"
    2. #include "Delay.h"
    3. //初始化KEY
    4. void KEY_Init(void)
    5. {
    6. RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //设置时钟
    7. GPIO_InitTypeDef GPIOInitStruct;
    8. GPIOInitStruct.GPIO_Mode = GPIO_Mode_IPU; //上拉模式
    9. GPIOInitStruct.GPIO_Pin = GPIO_Pin_13; //B13
    10. GPIOInitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    11. GPIO_Init(GPIOB, &GPIOInitStruct);
    12. }
    13. //判断key是否被按下
    14. uint8_t Key_IsDown(void)
    15. {
    16. uint8_t isdown = 0;
    17. if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_13) == 0) //判断是否按下
    18. {
    19. Delay_ms(20); //消抖
    20. if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_13) == 0) //判断是否确实被按钮
    21. {
    22. isdown = 1;
    23. }
    24. else
    25. {
    26. isdown = 0;
    27. }
    28. }
    29. else
    30. {
    31. isdown = 0;
    32. }
    33. return isdown;
    34. ;
    35. }
    整体工程文件如下:

  • 相关阅读:
    [springboot专栏]redis分布式锁实现及常见问题解析
    【Try to Hack】ip地址
    -0001-11-30 00:00:00 如何处理返回‘-0001-11-30 00:00:00‘的MySQl null日期
    RabbitMQ 简介
    TiDB系列之:认识TiDB数据库,使用TiUP部署TiDB集群,同时部署TiCDC的详细步骤
    Arm32进行远程调试
    【数据结构】模拟实现string
    Spring Boot 整合SpringSecurity和JWT和Redis实现统一鉴权认证
    DDD - 一文读懂DDD领域驱动设计
    1Panel 升级 Halo报错
  • 原文地址:https://blog.csdn.net/veray/article/details/133713842