【STM32】STM32循环读取按键(点亮led和计数)

STM32循环读取按键

  • main.c
#include "stm32f10x.h"                  // Device header
#include "Delay.h"
#include "led.h"
#include "key.h"
#include "OLED.h"

int main(void) {
	OLED_Init();
	Key_Init();
	LED_Init();
	
	OLED_ShowString(1, 1, "Welcome Jun..");
	OLED_ShowString(2, 1, "Led Status:");
	OLED_ShowString(3, 1, "Key Count:");
	uint8_t key_press = 0, led = 0, cnt = 0;
	
	
	while(1) {
		key_press = 0;	// 定义按键是否按下
		if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_3) == 0)
		{
			Delay_ms(20);
			while (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_3) == 0);
			Delay_ms(20);
			key_press = 1;
			cnt ++;
		}
		// 按键按下则切换led状态
		if(key_press) led = (led == 0)? 1 : 0;
		if(led == 0) LED_A0_OFF();
		else	LED_A0_ON();
			
		OLED_ShowString(2, 12, (led == 1)? "ON " : "OFF");
		OLED_ShowNum(3, 11, cnt, 2);
	}
}

  • key.c
#include "stm32f10x.h"                  // Device header
#include "Delay.h"

void Key_Init(void)
{
	GPIO_InitTypeDef  GPIO_InitStructure;
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);       
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_Init(GPIOA,&GPIO_InitStructure);			
}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值