1回答

0收藏

【望月追忆】带你入门STM32F0之三:按键----查询方式

STMCU STMCU 4534 人阅读 | 1 人回复 | 2012-12-07

按键查询方式,无非就是读按键对应引脚的电平,下面直接贴代码
1.按键引脚初始化
  1. void KEY_Init(void)
  2. {
  3.         /* GPIOC Periph clock enable */
  4.         GPIO_InitTypeDef  GPIO_InitStructure;
  5.         RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOF, ENABLE);

  6.   /* Configure PF6 and PF7 in input pushpull mode */
  7.         GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
  8.   GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
  9.   GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  10.         GPIO_InitStructure.GPIO_Speed =GPIO_Speed_Level_2;
  11.   GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
  12.   GPIO_Init(GPIOF, &GPIO_InitStructure);
  13. }
复制代码
2.读取按键引脚电平
  1. uint8_t ReadKeyValue(void)
  2. {
  3.         uint8_t key_value = 0xFF;
  4.         if(GPIO_ReadInputDataBit(GPIOF, GPIO_Pin_6) == Bit_RESET)
  5.         {
  6.                 SysTick_Delay_nms(10);
  7.                 if(GPIO_ReadInputDataBit(GPIOF, GPIO_Pin_6) == Bit_RESET)
  8.                 {
  9.                         key_value = KEY1;
  10.                 }
  11.         }
  12.        
  13.         if(GPIO_ReadInputDataBit(GPIOF, GPIO_Pin_7) == Bit_RESET)
  14.         {
  15.                 SysTick_Delay_nms(10);
  16.                 if(GPIO_ReadInputDataBit(GPIOF, GPIO_Pin_7) == Bit_RESET)
  17.                 {
  18.                         key_value = KEY2;
  19.                 }
  20.         }
  21.        
  22.         return key_value;
  23. }
复制代码
3.按键控制小灯
  1. LED_Init();
  2.         KEY_Init();

  3.   while (1)
  4.   {
  5.                 if(ReadKeyValue() == KEY1)
  6.                 {
  7.                         LED_Ctrl(LED1, LED_ON);
  8.                         LED_Ctrl(LED2, LED_OFF);
  9.                 }
  10.                
  11.                 if(ReadKeyValue() == KEY2)
  12.                 {
  13.                         LED_Ctrl(LED1, LED_OFF);
  14.                         LED_Ctrl(LED2, LED_ON);
  15.                 }
  16.   }
复制代码
分享到:
回复

使用道具 举报

回答|共 1 个

倒序浏览

沙发

MMzhang-319191

发表于 2012-12-11 14:04:15 | 只看该作者

坐个沙发
心中有曲自然嗨!!!
您需要登录后才可以回帖 注册/登录

本版积分规则

关闭

站长推荐上一条 /3 下一条