赞
踩
有两个按键,分别控制两个LED灯。当按键按下后,灯的亮暗状态改变。实物如下图所示:
由图可知,按键一端直接接地,故另一端所对应IO引脚的输入模式应该为上拉输入模式。
- #include "stm32f10x.h" // Device header
- #include "Delay.h"
-
- unsigned int KEY() //判断按键是否按下
- {
- unsigned int Key;
-
- if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1)==0)
- {
- Delay_ms(10);
- while(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1)==0);//等待按键松手
- Delay_ms(10);
- Key=1;
- }
- if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_11)==0)
- {
- Delay_ms(10);
- while(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_11)==0);//等待按键松手
- Delay_ms(10);
- Key=2;
- }
-
- return Key;
- }
-
- void LED1_Turn() //LED1灯的亮暗翻转
- {
- if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_1)==0)
- {
- GPIO_WriteBit(GPIOA, GPIO_Pin_1, Bit_SET);
- }
- else
- {
- GPIO_WriteBit(GPIOA, GPIO_Pin_1, Bit_RESET);
- }
- }
-
- void LED2_Turn() //LED1灯的亮暗翻转
- {
- if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_2)==0)
- {
- GPIO_WriteBit(GPIOA, GPIO_Pin_2, Bit_SET);
- }
- else
- {
- GPIO_WriteBit(GPIOA, GPIO_Pin_2, Bit_RESET);
- }
- }
-
- int main()
- {
- uint16_t KeyNum;
-
- //开启时钟
- RCC_APB2PeriphResetCmd(RCC_APB2Periph_GPIOA,ENABLE);
- RCC_APB2PeriphResetCmd(RCC_APB2Periph_GPIOB,ENABLE);
-
- //IO引脚PA1、PA2初始化,推挽输出模式
- GPIO_InitTypeDef GPIO_InitStruct_Out;
- GPIO_InitStruct_Out.GPIO_Pin=GPIO_Pin_1|GPIO_Pin_2;
- GPIO_InitStruct_Out.GPIO_Speed=GPIO_Speed_2MHz;
- GPIO_InitStruct_Out.GPIO_Mode=GPIO_Mode_Out_PP;
-
- GPIO_Init(GPIOA, &GPIO_InitStruct_Out);
-
- //IO引脚PB1、PB11初始化,上拉输入模式
- GPIO_InitTypeDef GPIO_InitStruct_In;
- GPIO_InitStruct_In.GPIO_Pin=GPIO_Pin_1|GPIO_Pin_11;
- GPIO_InitStruct_In.GPIO_Speed=GPIO_Speed_2MHz;
- GPIO_InitStruct_In.GPIO_Mode=GPIO_Mode_IPU;
-
- GPIO_Init(GPIOB, &GPIO_InitStruct_In);
-
- while(1)
- {
- KeyNum=KEY();
- if(KeyNum==1){LED1_Turn();}
- if(KeyNum==2){LED2_Turn();}
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。