单片机用2个IO扫描4个按键函数

u8 Button1Count=0;
u8 Button1Status=0;
u8 Button2Count=0;
u8 Button2Status=0;
u8 Button3Count=0;
u8 Button3Status=0;
u8 Button4Count=0;
u8 Button4Status=0;

#define DLY 500
#define DEBOUNCE 14

void ScanButton(void)
{
u8 temp1,temp2;
u8 flag2=0;
u8 flag1=0;


//-----------------------------------
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7 |GPIO_Pin_6;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}

GPIO_SetBits(GPIOB,GPIO_Pin_6);
GPIO_SetBits(GPIOB,GPIO_Pin_7);
Delay(DLY);
temp1=GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_6);
temp2=GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_7);

if( (temp1!=1)&&(temp2==1) )
{
flag2=1;
if( (Button1Count++ >=DEBOUNCE)&&(Button1Status==0) )
{
Uart2Print(0x22);
Button1Status=1;
}
}
else
{
flag2=0;
Button1Count=0;
Button1Status=0;
}


if( (temp2!=1)&&(temp1==1) )
{
flag1=1;
if( (Button2Count++ >=DEBOUNCE)&&(Button2Status==0) )
{
Uart2Print(0x11);
Button2Status=1;
}
}
else
{
flag1=0;
Button2Count=0;
Button2Status=0;
}


//-------------------------------------
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 ;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}

GPIO_SetBits(GPIOB,GPIO_Pin_7);
GPIO_ResetBits(GPIOB,GPIO_Pin_6);
Delay(DLY);
temp1=GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_6);
temp2=GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_7);

if( (temp2!=1) &&(flag1==0) )
{
if( (Button4Count++ >=DEBOUNCE)&&(Button4Status==0) )
{
Uart2Print(0x44);
Button4Status=1;
}
}
else
{
Button4Count=0;
Button4Status=0;
}



//-------------------------------------
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7 ;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}

GPIO_SetBits(GPIOB,GPIO_Pin_6);
GPIO_ResetBits(GPIOB,GPIO_Pin_7);
Delay(DLY);
temp1=GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_6);
temp2=GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_7);

if( (temp1!=1) && (flag2==0) )
{
if( (Button3Count++ >=DEBOUNCE)&&(Button3Status==0) )
{
Uart2Print(0x33);
Button3Status=1;

}
}
else
{
Button3Count=0;
Button3Status=0;
}

}

相关文档
最新文档