06 - GPIO输入按键检测

电路

  • S3和S4通过跳线帽连接到P3.6和P3.7口。
  • S5直接连接到P4.4口。

代码

  • 程序使用了最简单的延时消抖。

  • main.c
#define _MAIN_C
#include "config.h"
#include "STC8G_H_Delay.h"
#include "STC8G_H_GPIO.h"
#include "main.h"

#define D1 P03
#define D2 P02
#define D3 P01
#define D4 P00

#define KEY1 P36
#define KEY2 P37
#define K P44

/**
 * GPIO口初始化
 */
void GPIO_config(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.Mode = GPIO_PullUp;
	GPIO_InitStructure.Pin = GPIO_Pin_LOW;
	GPIO_Inilize(GPIO_P0, &GPIO_InitStructure);
	
	GPIO_InitStructure.Mode = GPIO_PullUp;				// P3.6和P3.7端口设置为准双向口
	GPIO_InitStructure.Pin = GPIO_Pin_6 | GPIO_Pin_7;
	GPIO_Inilize(GPIO_P3, &GPIO_InitStructure);
	
	GPIO_InitStructure.Mode = GPIO_PullUp;				// P4.4端口设置为准双向口
	GPIO_InitStructure.Pin = GPIO_Pin_4;
	GPIO_Inilize(GPIO_P4, &GPIO_InitStructure);
	
	
	
	P_SW2 &= 0x80;		// 将EAXFR位置1,以访问在XDATA区域的扩展SFR
	
//	P3PU |= 0x40;		// 使能P3.6端口内部的4.1K上拉电阻
//	P3PU |= 0x80;		// 使能P3.7端口内部的4.1K上拉电阻
//	P4PU |= 0x10;		// 使能P4.4端口内部的4.1K上拉电阻
	
	P6_PULL_UP_ENABLE(GPIO_Pin_6 | GPIO_Pin_7);		// 使能P3.6和P3.7端口内部的4.1K上拉电阻
	P4_PULL_UP_ENABLE(GPIO_Pin_4);
	
	P_SW2 &= 0x7F;		// 静止访问XFR	
}

void main()
{
	GPIO_config();

	while (1)
	{
		if (K == 0)
		{
			delay_ms(10);
			if (K == 0)
			{
				D1 = 0;
			}
			while (!K);
			D1 = 1;
		}
		
		if (KEY1 == 0)
		{
			delay_ms(10);
			if (KEY1 == 0)
			{
				D2 = ~D2;		// D2状态取反
			}
			while (!KEY1);
		}
		
		if (KEY2 == 0)
		{
			delay_ms(10);
			if (KEY2 == 0)
			{
				D3 = !D3;
			}
			while (!KEY2);
		}
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值