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

工程获取

三连后点击下方头像

相关推荐
2301_793121041 小时前
基于单片机的水平角度仪系统设计
单片机·嵌入式硬件
KaifuZeng2 小时前
通信与接口协议面试十、PCIe
单片机·嵌入式硬件·面试·通信与接口协议
lzx186488437022 小时前
【AH8966】可替代 KP3211 非隔离 AC110220V转12V 0.5A 降压转换芯片
人工智能·单片机·嵌入式硬件·集成测试·硬件工程·ic
csg11073 小时前
PIC单片机防破解:从硬件到软件的全面防护
单片机·嵌入式硬件·物联网·自动化
电化学仪器白超4 小时前
低阻域 ADC 与参考源选型理论分析
人工智能·python·单片机·嵌入式硬件·自动化
小小的代码里面挖呀挖呀挖4 小时前
杰理蓝牙耳机开发--LE Audio与游戏耳机应用
笔记·单片机·物联网·学习
张海森-1688204 小时前
怎么算进程 总共运行时间
单片机
bu_shuo5 小时前
STM32-BOOT的三种启动方式
stm32·单片机·嵌入式硬件
YYRAN_ZZU5 小时前
Lattice 自定义IP业务逻辑核
嵌入式硬件·fpga开发
AI的探索之旅6 小时前
从 Ubuntu 14.04 到 24.04:TI AM335x 开发环境完整迁移与 Agent 接管方案
linux·数据库·嵌入式硬件·ubuntu·postgresql