stm32笔记:按键输入(精简版)
扫描二维码
随时随地手机看文章
C代码
//GPIOA8是LED0
//GPIOA13是KEY0仅包含启动代码STM32F10x.s
#defineGPIOA_CRL(*(volatileunsignedlong*)(0x40000000+0x10000+0x0800+0x00))
#defineGPIOA_CRH(*(volatileunsignedlong*)(0x40000000+0x10000+0x0800+0x04))
#defineGPIOA_IDR(*(volatileunsignedlong*)(0x40000000+0x10000+0x0800+0x08))
#defineGPIOA_ODR(*(volatileunsignedlong*)(0x40000000+0x10000+0x0800+0x0C))
#defineRCC_APB2ENR(*(volatileunsignedlong*)(0x40000000+0x20000+0x1000+0x18))
voiddelay(unsignedlongi)//超级不精确的软延时
{
intj;
while(i--)
{
for(j=0;j<1500;j++)
{}
}
}
intmain(void)
{
u8keyflag=1;//按键进入标志,防止一次按键多次判断的简易做法
RCC_APB2ENR=1<<2;//打开PA时钟,默认启用内部8M时钟
GPIOA_CRH&=0XFFFFFFF0;//准备配置PA8,PA8是LED0
GPIOA_CRH|=0X00000003;//PA8推挽输出
GPIOA_ODR|=1<<8;//PA8输出高,即先关闭led
GPIOA_CRH&=0XFF0FFFFF;//准备配置PA13,PA13是KEY0
GPIOA_CRH|=0X00800000;//配置PA13为带上拉下拉输入
while(1)
{
if(!checkBit(GPIOA_IDR,13))//键被按下的话,执行led反转
{
if(keyflag)
{
keyflag=0;
GPIOA_ODR=revBit(GPIOA_ODR,8);//第8位反转,revBit是宏
}
}
else
{
keyflag=1;
}
delay(10);//简易消抖
}
}
//checkBit和revBit都是关于位的宏
//#defineBIT(n)(1<<(n))
//#definerevBit(val,n)((val)^(BIT(n)))
//#definecheckBit(val,n)(((val)&(BIT(n)))>>(n))