STM32学习-6-[GPIO]按键实验

关于模板什么的可以参考上一个实验

先让灯亮起来
image

再读取按键的状态
image

这是关于几个模式对应的宏定义
image

最后代码如下

#include "stm32f10x.h"

int main(void)
{
	RCC_APB2PriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);	// 开启GPIOC的时钟

	// 对灯进行初始化
	GPIO_InitTypeDef GPIO_InitStruct_LED = {0};	// 定义结构体
	GPIO_InitStruct_LED.GPIO_Pin = GPIO_Pin_0;
	GPIO_InitStruct_LED.GPIO_Mode = GPIO_Mode_Out_PP;	// 推挽输出
	GPIO_InitStruct_LED.GPIO_Speed = GPIO_Speed_2MHz;
	GPIO_Init(GPIOC, &GPIO_InitStruct_LED);	// 对引脚进行初始化

	// 对按键进行初始化
	GPIO_InitTypeDef GPIO_InitStruct_Key = {0};	// 定义结构体
	GPIO_InitStruct_Key.GPIO_Pin = GPIO_Pin_1;
	GPIO_InitStruct_Key.GPIO_Mode = GPIO_Mode_IPU;	// 推挽输出
	GPIO_InitStruct_Key.GPIO_Speed = GPIO_Speed_2MHz;
	GPIO_Init(GPIOC, &GPIO_InitStruct_Key);	// 对引脚进行初始化

	while(1)
	{
		if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_1) == Bit_RESET){	// 按键按下 因为上拉模式,所以默认情况为高电平,按下的时候接地,为低电平
			GPIO_WriteBit(GPIOA, GPIO_Pin_0, Bit_SET);	// 灯亮
		}else{	// 按键松开
			GPIO_WriteBit(GPIOA, GPIO_Pin_0, Bit_RESET);	// 灯灭
		}
	}
}

posted @ 2026-08-28 17:08  灵垚克府  阅读(4)  评论(0)    收藏  举报