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);
		}
	}
}

工程获取

三连后点击下方头像

相关推荐
自由的好好干活32 分钟前
UBI镜像文件打包与编辑
linux·嵌入式硬件
F133168929571 小时前
5G矿山车载监控终端山河矿卡定位监控终端
stm32·单片机·嵌入式硬件·5g·51单片机·硬件工程
小郭团队1 小时前
1_5_五段式SVPWM (传统算法反正切+DPWM1)算法理论与 MATLAB 实现详解
人工智能·嵌入式硬件·算法·dsp开发
vsropy2 小时前
keil5无法注释中文
stm32·单片机
csdn_te_download_0042 小时前
Keil5安装教程 基于C51 安装教程与配置完全指南
stm32·单片机·嵌入式硬件
ベadvance courageouslyミ2 小时前
51单片机相关
单片机·51单片机·定时器·pwm·蜂鸣器·中断·独立按键
送外卖的工程师3 小时前
STM32F103 驱动 BMP280 气压温湿度传感器 + OLED 显示教程
stm32·单片机·嵌入式硬件·mcu·物联网·proteus·rtdbs
2501_927773073 小时前
嵌入式51单片机——中断
stm32·单片机·嵌入式硬件
玩转以太网3 小时前
WIZnet以太网单片机选型指南
单片机·嵌入式硬件·以太网
tianyazhichiC4 小时前
stm32f103 标准外设库下载
stm32·单片机·嵌入式硬件