ホーム > ARM >

STM32ディスカバリの開発

USARTのサンプルプログラム

文字列の送信

/* USART1の初期設定を行う関数 */
void USART_Configuration(void)
{
  GPIO_InitTypeDef GPIO_InitStruct;
  USART_InitTypeDef USART_InitStruct;
  USART_ClockInitTypeDef USART_ClockInitStruct;

  /* バスクロック設定 */
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO | RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE);

  /* GPIO設定 */
  GPIO_StructInit(&GPIO_InitStruct);
  GPIO_InitStruct.GPIO_Pin   = GPIO_Pin_9;
  GPIO_InitStruct.GPIO_Mode  = GPIO_Mode_AF_PP;
  GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOA, &GPIO_InitStruct);

  GPIO_InitStruct.GPIO_Pin  = GPIO_Pin_10;
  GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  GPIO_Init(GPIOA, &GPIO_InitStruct);

  /* USART設定 */
  USART_ClockStructInit(&USART_ClockInitStruct);
  USART_ClockInitStruct.USART_Clock = USART_Clock_Enable;
  USART_ClockInit(USART1, &USART_ClockInitStruct);

  USART_DeInit(USART1);
  USART_StructInit(&USART_InitStruct);
  USART_InitStruct.USART_BaudRate            = 115200;
  USART_InitStruct.USART_WordLength          = USART_WordLength_8b;
  USART_InitStruct.USART_Parity              = USART_Parity_No;
  USART_InitStruct.USART_StopBits            = USART_StopBits_1;
  USART_InitStruct.USART_Mode                = USART_Mode_Tx | USART_Mode_Rx;
  USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  USART_Init(USART1, &USART_InitStruct);

  USART_Cmd(USART1, ENABLE);
}

/* USART1で文字列の送信を行う関数 */
void USART_SendString(const char *str)
{
  const char *ptr = str;
  while (*ptr != '\0')
  {
    while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET) {
    }
    USART_SendData(USART1, *ptr);
    ptr++;
  }
}

int main(void)
{
  USART_Configuration();
  USART_SendString("OK\r\n");
}

文字列の受信

/* USART1で一文字の送信を行う関数 */
void USART_SendChar(char c)
{
  while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET) {
  }
  USART_SendData(USART1, c);
}

/* 割り込みの設定を行う関数 */
void NVIC_Configuration(void)
{
  NVIC_InitTypeDef NVIC_InitStruct;

  /* USART受信割り込み設定 */
  NVIC_InitStruct.NVIC_IRQChannel                   = USART1_IRQn;
  NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
  NVIC_InitStruct.NVIC_IRQChannelSubPriority        = 0;
  NVIC_InitStruct.NVIC_IRQChannelCmd                = ENABLE;
  NVIC_Init(&NVIC_InitStruct);

  USART_ClearITPendingBit(USART1, USART_IT_RXNE);
  USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
}

/*
  USART受信 割り込みハンドラ
  受信した文字をエコーして返す
*/
void USART1_IRQHandler(void)
{
  char data;
  if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
  {
    data = (char)USART_ReceiveData(USART1);
    if (data == '\r') {
      USART_SendString("\r\n");
    } else {
      USART_SendChar(data);
    }
  }
}