//busclk unit is 1Khz
void uart_init (UART_TypeDef *UART,uint32 busclk,uint32 baud)
{
uint16 BRR=0;
//enable clock
RCC->AHBENR |= RCC_AHBENR_GPIOB; //enablePORTB clock
RCC->AHBENR |= RCC_AHBENR_GPIOC; //enablePORTC clock
if(UART == UART1)
RCC->APB2ENR |= RCC_APB2ENR_UART1;
else
RCC->APB1ENR |= RCC_APB1ENR_UART2;
//pin mux
if(UART == UART1)
{
//UART1_TX -> B6
GPIOB->AFRL &= ~GPIO_AFRL_AFR6;
GPIOB->AFRL |= (GPIO_AF_MODE0 << GPIO_AFRL_AFR6_Pos);
GPIOB->CRL &= ~(GPIO_CNF_MODE_MASK << GPIO_CRL_CNF_MODE_6_Pos);
GPIOB->CRL |= (GPIO_CNF_MODE_AF_PP << GPIO_CRL_CNF_MODE_6_Pos);
//UART1_RX -> B7
GPIOB->AFRL &= ~GPIO_AFRL_AFR7;
GPIOB->AFRL |= (GPIO_AF_MODE0 << GPIO_AFRL_AFR7_Pos);
GPIOB->CRL &= ~(GPIO_CNF_MODE_MASK << GPIO_CRL_CNF_MODE_7_Pos);
GPIOB->CRL |= (GPIO_CNF_MODE_FLOATING << GPIO_CRL_CNF_MODE_7_Pos);
}
else
{
//UART2_TX -> C4
GPIOC->AFRL &= ~GPIO_AFRL_AFR4;
GPIOC->AFRL |= (GPIO_AF_MODE3 << GPIO_AFRL_AFR4_Pos);
GPIOC->CRL &= ~(GPIO_CNF_MODE_MASK << GPIO_CRL_CNF_MODE_4_Pos);
GPIOC->CRL |= (GPIO_CNF_MODE_AF_PP << GPIO_CRL_CNF_MODE_4_Pos);
//UART2_RX -> C5
GPIOC->AFRL &= ~GPIO_AFRL_AFR5;
GPIOC->AFRL |= (GPIO_AF_MODE0 << GPIO_AFRL_AFR5_Pos);
GPIOC->CRL &= ~(GPIO_CNF_MODE_MASK << GPIO_CRL_CNF_MODE_5_Pos);
GPIOC->CRL |= (GPIO_CNF_MODE_FLOATING << GPIO_CRL_CNF_MODE_5_Pos);
}
//reset uart module
if(UART == UART1)
{
RCC->APB2RSTR |= RCC_APB2RSTR_UART1;
RCC->APB2RSTR &= ~(RCC_APB2RSTR_UART1);
}
else
{
RCC->APB1RSTR |= RCC_APB1RSTR_UART2;
RCC->APB1RSTR &= ~(RCC_APB1RSTR_UART2);
}
/* Configure the UART for 8-bit mode, no parity , 1 stop*/
UART->CCR = UART_CCR_CHAR_8b;
/* Calculate baud settings */
BRR = busclk*1000/baud/16;
UART->BRR = BRR;
/* Enable receiver and transmitter */
UART->GCR |= UART_GCR_RX;//Enable receiver
UART->GCR |= UART_GCR_TX;//Enable transmitter
//enable rx interrupt
UART1->IER |= UART_IER_RX;
//enable uart
UART->GCR |= UART_GCR_UART;
if(UART1 == UART)
{
NVIC_SetPriority(UART1_IRQn,3);
NVIC_EnableIRQ(UART1_IRQn);
}
else
{
NVIC_SetPriority(UART2_IRQn,3);
NVIC_EnableIRQ(UART2_IRQn);
}
}
void UART1_IRQHandler(void)
{
uint8 tmp=0;
if(UART1->ISR & UART_ISR_RX)
{
UART1->ICR = UART_ICR_RX;//clear receive interrupt
tmp = base->RDR;
}
}
|