当前位置:   article > 正文

STM32实战篇:按键控制LED

STM32实战篇:按键控制LED

按键控制LED

功能要求

有两个按键,分别控制两个LED灯。当按键按下后,灯的亮暗状态改变。实物如下图所示:

由图可知,按键一端直接接地,故另一端所对应IO引脚的输入模式应该为上拉输入模式


实现代码

  1. #include "stm32f10x.h" // Device header
  2. #include "Delay.h"
  3. unsigned int KEY() //判断按键是否按下
  4. {
  5. unsigned int Key;
  6. if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1)==0)
  7. {
  8. Delay_ms(10);
  9. while(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1)==0);//等待按键松手
  10. Delay_ms(10);
  11. Key=1;
  12. }
  13. if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_11)==0)
  14. {
  15. Delay_ms(10);
  16. while(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_11)==0);//等待按键松手
  17. Delay_ms(10);
  18. Key=2;
  19. }
  20. return Key;
  21. }
  22. void LED1_Turn() //LED1灯的亮暗翻转
  23. {
  24. if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_1)==0)
  25. {
  26. GPIO_WriteBit(GPIOA, GPIO_Pin_1, Bit_SET);
  27. }
  28. else
  29. {
  30. GPIO_WriteBit(GPIOA, GPIO_Pin_1, Bit_RESET);
  31. }
  32. }
  33. void LED2_Turn() //LED1灯的亮暗翻转
  34. {
  35. if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_2)==0)
  36. {
  37. GPIO_WriteBit(GPIOA, GPIO_Pin_2, Bit_SET);
  38. }
  39. else
  40. {
  41. GPIO_WriteBit(GPIOA, GPIO_Pin_2, Bit_RESET);
  42. }
  43. }
  44. int main()
  45. {
  46. uint16_t KeyNum;
  47. //开启时钟
  48. RCC_APB2PeriphResetCmd(RCC_APB2Periph_GPIOA,ENABLE);
  49. RCC_APB2PeriphResetCmd(RCC_APB2Periph_GPIOB,ENABLE);
  50. //IO引脚PA1、PA2初始化,推挽输出模式
  51. GPIO_InitTypeDef GPIO_InitStruct_Out;
  52. GPIO_InitStruct_Out.GPIO_Pin=GPIO_Pin_1|GPIO_Pin_2;
  53. GPIO_InitStruct_Out.GPIO_Speed=GPIO_Speed_2MHz;
  54. GPIO_InitStruct_Out.GPIO_Mode=GPIO_Mode_Out_PP;
  55. GPIO_Init(GPIOA, &GPIO_InitStruct_Out);
  56. //IO引脚PB1、PB11初始化,上拉输入模式
  57. GPIO_InitTypeDef GPIO_InitStruct_In;
  58. GPIO_InitStruct_In.GPIO_Pin=GPIO_Pin_1|GPIO_Pin_11;
  59. GPIO_InitStruct_In.GPIO_Speed=GPIO_Speed_2MHz;
  60. GPIO_InitStruct_In.GPIO_Mode=GPIO_Mode_IPU;
  61. GPIO_Init(GPIOB, &GPIO_InitStruct_In);
  62. while(1)
  63. {
  64. KeyNum=KEY();
  65. if(KeyNum==1){LED1_Turn();}
  66. if(KeyNum==2){LED2_Turn();}
  67. }
  68. }

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/820095
推荐阅读
相关标签
  

闽ICP备14008679号