uart_init
void uart_init(void){
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
//TX
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin = UART_TX_PIN;
GPIO_Init(UART_TX_GRP, &GPIO_InitStructure);
//RX
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Pin = UART_RX_PIN;
GPIO_Init(UART_RX_GRP, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = UART_BUADRATE;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
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(UARTx, &USART_InitStructure);
USART_ITConfig(UARTx, USART_IT_RXNE, ENABLE); //接收满中断
USART_ITConfig(UARTx, USART_IT_TXE, DISABLE); //发送空中断
USART_Cmd(UARTx, ENABLE);
}
nvic_init
void UartNvicInit(void){
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = UART_PREEMPTION_PRIORITY;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = UART_SUB_PRIORITY;
NVIC_InitStructure.NVIC_IRQChannel = UARTx_IRQn;
NVIC_Init(&NVIC_InitStructure);
}
stm32f10x_it.c
void UARTx_IRQHandler(void){
u16 tmp_head;
if(USART_GetITStatus(USARTx, USART_IT_RXNE) != RESET){
g_uart_recvbuf[g_uart_recvtail] = USART_ReceiveData(USARTx);
g_uart_recvtail = (g_uart_recvtail + 1) % UART_RX_BUFSIZE;
}
if(USART_GetITStatus(UARTx, USART_IT_TXE) != RESET){
tmp_head = g_uart_sendhead;
if(tmp_head == g_uart_sendtail){
USART_ITConfig(UARTx, USART_IT_TXE, DISABLE);
}else{
USART_SendData(UARTx, g_uart_sendbuf[g_uart_sendhead]);
g_uart_sendhead = (g_uart_sendhead + 1) % UART_TX_BUFSIZE;
}
}
}
davice.c
void uart_recvmsg(void){
u8 ch;
u16 tmp_tail;
tmp_tail = g_uart_recvtail;
if(tmp_tail != g_uart_recvhead){
ch = g_uart_recvbuf[g_uart_recvhead];
// printf("%02x, ", ch);
g_uart_recvhead = (g_uart_recvhead + 1) % UART_RX_BUFSIZE;
tmp_tail = g_uart_recvtail;
}
}
void uart_sendbyte(u8 ch){
u16 tmp_tail;
tmp_tail = (g_uart_sendtail + 1) % UART_TX_BUFSIZE;
while(tmp_tail == g_uart_sendhead);
g_uart_sendbuf[g_uart_sendtail] = ch;
g_uart_sendtail = tmp_tail;
USART_ITConfig(UARTx, USART_IT_TXE, ENABLE);
}