Stm32按键和输出差不多
PA1为LED供给正电,PB5放置按键,按键一端接PB5,另一端接负极
void Key_Init(void){RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //APB2总线连接着GPIOBGPIO_InitStructur.GPIO_Mode = GPIO_Mode_IPU;GPIO_InitStructur.GPIO_Pin = GPIO_Pin_5;GPIO_InitStructur.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(GPIOB, &GPIO_InitStructur);//写入
}
初始化为上拉输入输入HZ不用管,GPIOA和GPIOB都连接在APB2总线上,开启对应时钟才能进一步使用
这里初始化PB5为输入,PB3不知道啥原因不能作为输入端口
读输入值
GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_5)
这个函数返回的是一个uint8_t范围为[0 ~ 255),一般用它装小范围的int类型数据
按键扫描代码
uint8_t check(void){uint8_t keynum = 0;//初始化0if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_5) == 0){Delay_ms(10);//消抖while(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_5) == 0);//等待松按键keynum = 1;}return keynum;//记得返回值
}
完整代码
#include "stm32f10x.h" // Device header
#include "Delay.h"TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_OCInitTypeDef TIM_OCInitStructuer;//结构体
GPIO_InitTypeDef GPIO_InitStructur;//定义变量结构体void GPIOA_Init(void){RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);GPIO_InitStructur.GPIO_Mode = GPIO_Mode_AF_PP;GPIO_InitStructur.GPIO_Pin = GPIO_Pin_0; //GPIO_Pin_15;GPIO_InitStructur.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(GPIOA, &GPIO_InitStructur);
}void PWM_Init(void){ //pwm波形配置TIM_OCStructInit(&TIM_OCInitStructuer);//给不需要配置的结构体成员赋予初始值TIM_OCInitStructuer.TIM_OCMode = TIM_OCMode_PWM1; //输出比较模式TIM_OCInitStructuer.TIM_OCPolarity = TIM_OCPolarity_High; //极性TIM_OCInitStructuer.TIM_OutputState = TIM_OutputState_Enable; //输出使能TIM_OCInitStructuer.TIM_Pulse = 0; //CCR,频率1kHZ,占空比50%的PWM波形TIM_OC1Init(TIM2, &TIM_OCInitStructuer);//配置GPIOA端口通道
}/*定时器定时中断代码*/void Timer_Init(void)//使用TM2定时器
{RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);GPIOA_Init();TIM_InternalClockConfig(TIM2);TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;TIM_TimeBaseInitStructure.TIM_Period = 100 - 1; //ARRTIM_TimeBaseInitStructure.TIM_Prescaler = 720 - 1; //PSCTIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStructure);PWM_Init();TIM_Cmd(TIM2, ENABLE);//启动定时器
}/*CCR控制灯的亮度在运行过程中不断更改CCR的值来达到呼吸效果*/ //CCR[0~100]值越大灯越亮void PWM_setcompare1(uint16_t compare){TIM_SetCompare1(TIM2, compare);
}uint8_t i;
uint8_t j;void Led_light(void){for(j = 0; j < 3; j ++){ for(i = 0; i <= 100; i ++){PWM_setcompare1(i);Delay_ms(8);}for(i = 0; i <= 100; i ++){PWM_setcompare1(100 - i);Delay_ms(8);}}}void Key_Init(void){RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //APB2总线连接着GPIOBGPIO_InitStructur.GPIO_Mode = GPIO_Mode_IPU;GPIO_InitStructur.GPIO_Pin = GPIO_Pin_5;GPIO_InitStructur.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(GPIOB, &GPIO_InitStructur);//写入
}uint8_t check(void){uint8_t keynum = 0;//初始化0if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_5) == 0){Delay_ms(10);//消抖while(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_5) == 0);//等待松按键keynum = 1;}return keynum;//记得返回值
}int main(void){Timer_Init();Key_Init();while(1){if(check() == 1){Led_light();}}
}
效果:按一下按键松开,Led呼吸三次