电路
- S3和S4通过跳线帽连接到P3.6和P3.7口。
- S5直接连接到P4.4口。
![](https://img-blog.csdnimg.cn/direct/c2172441c53246408091c72dabc6854e.png)
代码
![](https://img-blog.csdnimg.cn/direct/be3a651e5b584794b35952005ae1a7b4.png)
#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);
}
}
}