初级会员

- 积分
- 66
- 金钱
- 66
- 注册时间
- 2018-7-12
- 在线时间
- 21 小时
|
1金钱
本帖最后由 hank 于 2018-8-21 11:57 编辑
我的逻辑是:1.将按键端口设为上拉
2.将键盘公共端接GND,另一条线接GPIO,当按键按下的时候,GPIO应该连接GND,呈现低电平
3.KeyScan()函数内部,使用GPIO_ReadInputDataBit()函数读取相应的GPIO,如果是低电平,函数反回1
4.Main()函数,遇到KeyScan()返回1的情况,就执行Beep01(1)蜂鸣器程序,
5.执行一遍之后,使用GPIO_ReadInputDataBit()函数将GPIO置1,
按理说,逻辑没毛病啊,是不是?可一上电,无论有按没按,就是乱响,一点不受控制。
硬件接线
GPIP定义
[mw_shl_code=c,true]
//For KeyScan
#define KeyPortA_RCC RCC_APB2Periph_GPIOA
#define KeyPortA GPIOA
#define Key1 GPIO_Pin_8
#define KeyPortB_RCC RCC_APB2Periph_GPIOB
#define KeyPortB GPIOB
#define Key2 GPIO_Pin_12
#define Key3 GPIO_Pin_13
#define Key4 GPIO_Pin_14
#define Key5 GPIO_Pin_15
#define KeyPortC_RCC RCC_APB2Periph_GPIOC
#define KeyPortC GPIOC
#define Key6 GPIO_Pin_13
#define Key7 GPIO_Pin_14
#define Key8 GPIO_Pin_15
//蜂鸣器管脚定义
#define Beep_1_GPIO GPIOA
#define Beep_1_RCC RCC_APB2Periph_GPIOA
#define Beep_1_Pin GPIO_Pin_15
[/mw_shl_code]
端口定义和按键扫描函数
[mw_shl_code=c,true]void KEY_GPIO_Config(void)
{
GPIO_InitTypeDef KeyA;
GPIO_InitTypeDef KeyB;
GPIO_InitTypeDef KeyC;
KeyA.GPIO_Pin = Key1;
KeyA.GPIO_Mode = GPIO_Mode_IPU;
KeyA.GPIO_Speed = GPIO_Speed_50MHz;
RCC_APB2PeriphClockCmd(KeyPortA_RCC,ENABLE);
GPIO_Init(KeyPortA,&KeyA);
KeyB.GPIO_Pin = Key2 | Key3 | Key4 | Key5;
KeyB.GPIO_Mode = GPIO_Mode_IPU;
KeyB.GPIO_Speed = GPIO_Speed_50MHz;
RCC_APB2PeriphClockCmd(KeyPortB_RCC,ENABLE);
GPIO_Init(KeyPortB,&KeyB);
KeyC.GPIO_Pin = Key6 | Key7 | Key8;
KeyC.GPIO_Mode = GPIO_Mode_IPU;
KeyC.GPIO_Speed = GPIO_Speed_50MHz;
RCC_APB2PeriphClockCmd(KeyPortC_RCC,ENABLE);
GPIO_Init(KeyPortC,&KeyC);
GPIO_SetBits(KeyPortA,Key1);
GPIO_SetBits(KeyPortB,Key2 | Key3 | Key4 | Key5);
GPIO_SetBits(KeyPortC,Key6 | Key7 | Key8 );
}
u8 KeyScan(GPIO_TypeDef* GPIOx,u16 GPIO_Pin)
{
if(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin) == 0)
{
delay_ms(20);
if(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin) == 0)
{
return 1;
}
}
return 0;
}[/mw_shl_code]
Main函数:
[mw_shl_code=c,true] while(1)
{
if(KeyScan(KeyPortA,Key1))
{
GPIO_WriteBit(KeyPortA,Key1,1);
Beep01(1);
}
else if(KeyScan(KeyPortB,Key2))
{
GPIO_WriteBit(KeyPortB,Key2,1);
Beep01(2);
}
}[/mw_shl_code]
蜂鸣器函数和定义
[mw_shl_code=c,false]void Beep_GPIO_Config(void)
{
GPIO_InitTypeDef Beep1;
Beep1.GPIO_Pin = Beep_1_Pin;
Beep1.GPIO_Mode = GPIO_Mode_Out_PP;
Beep1.GPIO_Speed = GPIO_Speed_50MHz;
RCC_APB2PeriphClockCmd(Beep_1_RCC,ENABLE);
GPIO_Init(Beep_1_GPIO,&Beep1);
}
void Beep01(int on)
{
int i = 0;
if (on == 0)
{
GPIO_WriteBit(Beep_1_GPIO,Beep_1_Pin, Bit_SET);
}
else if(on == 1)
{
for(i = 0 ; i < 168 ; i ++)
{
GPIO_WriteBit(Beep_1_GPIO,Beep_1_Pin, Bit_RESET);
//PAout(12) = 0;
delay_us(100);
GPIO_WriteBit(Beep_1_GPIO,Beep_1_Pin, Bit_SET);
//PAout(12) = 1;
delay_us(100);
}
}
else if(on == 2)
{
for(i = 0 ; i < 168 ; i ++)
{
GPIO_WriteBit(Beep_1_GPIO,Beep_1_Pin, Bit_RESET);
//PAout(12) = 0;
delay_us(200);
GPIO_WriteBit(Beep_1_GPIO,Beep_1_Pin, Bit_SET);
//PAout(12) = 1;
delay_us(200);
}
}
}[/mw_shl_code]
|
|