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

工程获取

三连后点击下方头像

相关推荐
破晓单片机6 小时前
068、STM32项目分享:智能小区门禁系统
stm32·单片机·嵌入式硬件
H__Rick7 小时前
C51单片机学习-DAY3
单片机·学习·mongodb
望眼欲穿的程序猿8 小时前
Hello World
嵌入式硬件·rust
bkspiderx8 小时前
Windows DLL核心技术:深入理解__declspec(dllexport)与__declspec(dllimport)
windows·stm32·单片机·dllimport·dllexport·windows dll·__declspec
m0_547486668 小时前
《ARM Cortex-M4嵌入式应用技术——基于STM32F407、STM32CubeMX与Proteus》全套PPT课件
arm开发·stm32·proteus
ACP广源盛139246256739 小时前
GSV5600@ACP#多接口协议转换芯片,物理 AI 便携终端的互联核心
大数据·人工智能·分布式·嵌入式硬件·spark
望眼欲穿的程序猿9 小时前
ESP32-S3 定时器中断
单片机·嵌入式硬件
电气_空空9 小时前
基于 LabVIEW 的深海气密采水器测控系统
单片机·嵌入式硬件·毕业设计·labview
星夜夏空9910 小时前
STM32单片机学习(37) —— PWR和BKP
stm32·单片机·学习
牛牛,牛10 小时前
榨干最后一微安:STM32 的低功耗设计与中断唤醒机制深度剖析
单片机·嵌入式硬件