1: After reading STM32 Chinese data sheet, I believe we have some understanding of the USART serial communication, learning time 51 also have contact, use the serial port as long as the principle is very simple to figure out
Data transmission and reception process can be intuitively seen from FIG.
USART serial communication involves several important registers
Status register 1 :)
2) Data Register
3) baud rate register
Example: To set a bit rate of 9600, the DIV is 468.75, then the register 12 to be kept high value: 468, the value stored in the lower 4 bits: 16 = 0.75 * 12 (decimal converted to hexadecimal decimals) ; Finally, the integer and fractional splice: BRR = 468 << 4 + 12; (the detailed process can be referred to the source code;)
4) Control Register 1:
5) Control Register 2:
Primarily the stop bits, the polarity of the clock, clock enable
6) Control Register 3:
It relates to the hardware flow control, DMA configuration, etc.
send data:
Receive data:
Related Programs:
Interrupt function:
void USART1_IRQHandler(void)
{
static u8 ch;
USART_ClearFlag(USART1 , USART_FLAG_TC);
if(USART_GetITStatus(USART1, USART_IT_RXNE) != Bit_RESET)
{
ch=USART_ReceiveData(USART1);
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == Bit_RESET); USART_SendData(USART1, ch);
while(USART_GetFlagStatus(USART1, USART_FLAG_TC));
}
}
The main program:
int main ()
{
usart_init();
while(1);
}
Configuration Program:
void usart_init()
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
USART_DeInit(USART1);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOC|RCC_APB2Periph_AFIO|RCC_APB2Periph_USART1,ENABLE);
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);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA,&GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = 9600;
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_Tx | USART_Mode_Rx;
USART_Init(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
USART_ITConfig (USART1,USART_IT_RXNE,ENABLE);
USART_ClearFlag(USART1,USART_FLAG_TC);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
NVIC_InitStructure.NVIC_IRQChannel=USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority=0;
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_Init(&NVIC_InitStructure);
}