2016年7月20日 星期三

STM32F411xC 基礎教學 : Button與 LED使用方式

本篇基於STM32F411xC平台,記錄板端Button與Led的使用方式。

實驗說明:
按下Button1(PD2)點亮Led2(PC0),Button2(PC12)點亮Led5(PC1)。

Button 初始化:

//button1:PD2
//button2:PC12

void Btn_Init(void) {

  GPIO_InitTypeDef GPIO_InitStructure;

  RCC_AHB1PeriphClockCmd( RCC_AHB1Periph_GPIOD, ENABLE );

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;

  GPIO_Init( GPIOD, &GPIO_InitStructure );

  RCC_AHB1PeriphClockCmd( RCC_AHB1Periph_GPIOC, ENABLE );

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;

  GPIO_Init( GPIOC, &GPIO_InitStructure );
}

LED 初始化:

//LED2:PC0
//LED5:PC1
//LED3:PC2
//LED4:PC3

void gpio_led_config( void )
{
  GPIO_InitTypeDef GPIO_InitStructure;

  RCC_AHB1PeriphClockCmd( RCC_AHB1Periph_GPIOC, ENABLE );

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;

GPIO_Init( GPIOC, &GPIO_InitStructure );
}


Main function:

int main(void)
{

  RCC_ClocksTypeDef RCC_Clocks;
  RCC_GetClocksFreq(&RCC_Clocks);

  Btn_Init();
  gpio_led_config();

  while ( 1 ) {

   //Sw1
   if (GPIO_ReadInputDataBit(GPIOD, GPIO_Pin_2) == 0){
   //turn on PC0:LED2
   GPIO_SetBits(GPIOC, GPIO_Pin_0);
   }else{
   //turn off PC0:LED2
   GPIO_ResetBits(GPIOC, GPIO_Pin_0);
   }

   //Sw2
   if (GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_12) == 0){
   GPIO_SetBits(GPIOC, GPIO_Pin_1);
   }else{
   GPIO_ResetBits(GPIOC, GPIO_Pin_1);
   }
  }

}

沒有留言:

張貼留言