2023版 STM32实战2 按键驱动(电路与代码都讲解)

常规电路(带上拉电阻)

阻值可选3.3/4.7/5.1/10 单位K

偷懒电路

利用GPIO内部的上拉模式

代码(直接拷贝使用)

这是一个按键控制灯亮灭的demo
为了新手方便我直接都写在了main.c文件

c 复制代码
#include "stm32f10x.h"


void LED_Init(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_GPIOE, ENABLE);
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_Init(GPIOB, &GPIO_InitStructure);
	GPIO_Init(GPIOE, &GPIO_InitStructure);
}

void KEY_Init(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE, ENABLE);
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3|GPIO_Pin_4;
	GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPU;
	GPIO_Init(GPIOE, &GPIO_InitStructure);
}

void delay(u32 time)
{
	while(time--);
}

int main(void)
{	
	LED_Init();
	KEY_Init();
	while(1)
	{
		if( GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_3)==0 )
		{
			GPIO_ResetBits(GPIOB,GPIO_Pin_5);
		}
		else if( GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_4)==0 )
		{
			GPIO_SetBits(GPIOB,GPIO_Pin_5);
		}
	}
}

工程获取

三连后点击下方头像

相关推荐
离凌寒3 小时前
一、在freertos上使用esp01s模块并配置使用sta模式进行数据通信传输测试。
单片机·freertos·esp01s
星期天27 小时前
1.1江科大之LED闪烁&LED流水灯&蜂鸣器
stm32·单片机·嵌入式硬件
梓德原7 小时前
【经验】MSP430编译器使用经验-IAR编辑框分框
单片机·嵌入式硬件·物联网
电子工程师-C518 小时前
基于51单片机的自动乒乓球发球机
单片机·嵌入式硬件·51单片机
玩转单片机与嵌入式8 小时前
在STM32F103单片机上跑通AI模型:为什么选正弦波作为Hello World?
人工智能·stm32·单片机
星期天29 小时前
1.2STM32江科大GPIO的输入(电路硬件连接)
单片机·嵌入式硬件·stm32江科大·gpio的输入·硬件电路的链接
Darken0310 小时前
标准外设库与HAL库有什么区别?都怎样去使用?如何区分?
单片机·嵌入式硬件·hal库与基本外设库
点灯master11 小时前
DAC8562的驱动设计开发
c语言·驱动开发·stm32
czhaii11 小时前
8051U深度入门到32位51大型实战
单片机
Hans_Rudle11 小时前
在香橙派(昇腾NPU)(kunpengpro/aipro)上部署自己的模型 -以Unet为例
嵌入式硬件·香橙派