STM32 시리얼 포트 제어
초기화 설정
//Clk 설정 - 순서 중요 (APB 클럭설정을 가장 먼저해야함)
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
//Configure USART1 Rx (PA10) as input floating
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// Configure USART1 Tx (PA9) as alternate function push-pull
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = baud_rate;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No ;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
//한문자 수신
unsigned char U0_GetByte(void)
{
while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET);
return (u8)USART1->DR;;
}
//한문자 전송
void U0_PutByte(unsigned char Data)
{
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
USART_SendData(USART1, Data);
}
void U0_printf(char *fmt,...)
{
va_list ap;
char string[256];
va_start(ap,fmt);
vsprintf(string,fmt,ap);
U0_PutStr(string);
va_end(ap);
}
전체 예제 소스는 첨부한 소스를 참고 하시고 아래 예제는 시리얼 포트로 '0', '1'문자를 보내 LED를 제어 하는 코드 입니다.
//=============================================================================
// STM32 EVM Module Test Program
// by nexp76() http://nexp.tistory.com/
// [main.c]
//=============================================================================
/*
- STM32 EVM Onboard LED Control
*/
#include "system.h"
#include "serial.h"
//-----------------------------------------------------------------------------
int main(void)
{
//System Init
SystemInit();
//LED Init
Led1Init();
Led1On();
//Serial Init
DebugInit(BAUD_115200);
DebugPrint("Serial Test Program.\r\n");
while (1)
{
switch(U0_GetByte())
{
case '0':
Led1Off();
DebugPrint("LED OFF\r\n");
break;
case '1':
Led1On();
DebugPrint("LED ON\r\n");
break;
}
}
}
//-----------------------------------------------------------------------------
USRT2 사용할때 초기화
STM32의 UART2는 APB1에 연결되어 있으므로 주의 필요..
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO | RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);