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)//超級不精確的軟延時(shí)
{
intj;
while(i--)
{
for(j=0;j<1500;j++)
{}
}
}
intmain(void)
{
u8keyflag=1;//按鍵進(jìn)入標(biāo)志,防止一次按鍵多次判斷的簡易做法
RCC_APB2ENR=1<<2;//打開PA時(shí)鐘,默認(rèn)啟用內(nèi)部8M時(shí)鐘
GPIOA_CRH&=0XFFFFFFF0;//準(zhǔn)備配置PA8,PA8是LED0
GPIOA_CRH|=0X00000003;//PA8推挽輸出
GPIOA_ODR|=1<<8;//PA8輸出高,即先關(guān)閉led
GPIOA_CRH&=0XFF0FFFFF;//準(zhǔn)備配置PA13,PA13是KEY0
GPIOA_CRH|=0X00800000;//配置PA13為帶上拉下拉輸入
while(1)
{
if(!checkBit(GPIOA_IDR,13))//鍵被按下的話,執(zhí)行l(wèi)ed反轉(zhuǎn)
{
if(keyflag)
{
keyflag=0;
GPIOA_ODR=revBit(GPIOA_ODR,8);//第8位反轉(zhuǎn),revBit是宏
}
}
else
{
keyflag=1;
}
delay(10);//簡易消抖
}
}
//checkBit和revBit都是關(guān)于位的宏
//#defineBIT(n)(1<<(n))
//#definerevBit(val,n)((val)^(BIT(n)))
//#definecheckBit(val,n)(((val)&(BIT(n)))>>(n))