来源B站江科大stm32入门教程
按键控制LED
LED模块
LED初始化代码省略
用到了GPIO_ResetBits(); GPIO_SetBits();GPIO_ReadOutputDataBit()函数
void LED_ON(uint16_t GPIO_Pin)
{
if(GPIO_Pin==GPIO_Pin_1)
GPIO_ResetBits(GPIOA,GPIO_Pin_1);
else if(GPIO_Pin==GPIO_Pin_2)
GPIO_ResetBits(GPIOA,GPIO_Pin_2);
}
void LED_OFF(uint16_t GPIO_Pin)
{
if(GPIO_Pin==GPIO_Pin_1)
GPIO_SetBits(GPIOA,GPIO_Pin_1);
else if(GPIO_Pin==GPIO_Pin_2)
GPIO_SetBits(GPIOA,GPIO_Pin_2);
}
void LED_TURN(uint16_t GPIO_Pin)
{
if(GPIO_Pin==GPIO_Pin_1){
if(GPIO_ReadOutputDataBit(GPIOA,GPIO_Pin_1)==0){
GPIO_SetBits(GPIOA,GPIO_Pin_1);
}
else{
GPIO_ResetBits(GPIOA,GPIO_Pin_1);
}
}
if(GPIO_Pin==GPIO_Pin_2){
if(GPIO_ReadOutputDataBit(GPIOA,GPIO_Pin_2)==0){
GPIO_SetBits(GPIOA,GPIO_Pin_2);
}
else{
GPIO_ResetBits(GPIOA,GPIO_Pin_2);
}
}
}
按键模块
按键初始化模块省略。
用到了GPIO_ReadInputDataBit()函数
uint8_t Key_getNum(void)
{
uint8_t KeyNum=0;
if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1)==0){
//按键消抖
Delay_ms(20);
while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1)==0);
Delay_ms(20);
KeyNum=1;
}
else if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_11)==0){
Delay_ms(20);
while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_11)==0);
Delay_ms(20);
KeyNum=2;
}
return KeyNum;
}
主函数
uint8_t Key;
int main(void)
{
LED_Init();
Key_Init();
while(1)
{
Key=Key_getNum();
if(Key==1){
LED_TURN(GPIO_Pin_1);
}
if(Key==2){
LED_TURN(GPIO_Pin_2);
}
}
}
光敏传感器驱动蜂鸣器
实现功能:遮住光敏传感器蜂鸣器响
蜂鸣器模块
初始化代码省略
void Buzzer_ON(uint16_t GPIO_Pin)
{
GPIO_ResetBits(GPIOB,GPIO_Pin_12);
}
void Buzzer_OFF(uint16_t GPIO_Pin)
{
GPIO_SetBits(GPIOB,GPIO_Pin_12);
}
void Buzzer_TURN(uint16_t GPIO_Pin)
{
if(GPIO_ReadOutputDataBit(GPIOB,GPIO_Pin_12)==0){
GPIO_SetBits(GPIOB,GPIO_Pin_1);
}
else{
GPIO_ResetBits(GPIOB,GPIO_Pin_1);
}
}
光传感器模块
uint8_t Light_Get(void)
{
//遮住为高电平
return GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_13);
}
主函数
int main(void)
{
Buzzer_Init();
LightSensor_Init();
while(1)
{
if(Light_Get()==1){
Buzzer_ON(GPIO_Pin_12);
}
else{
Buzzer_OFF(GPIO_Pin_12);
}
}
}