#include "uart.h"
void uart_init(uart_def *uart)
{
USART_InitTypeDef USART_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
if (uart->uart_ptr == USART1)// 使能时钟
{
RCC_APB2PeriphClockCmd(uart->gpio_rx_rcc | uart->gpio_tx_rcc | uart->uart_rcc, ENABLE);
}
else // USART2 USART3 UART4 UART5
{
RCC_APB2PeriphClockCmd(uart->gpio_rx_rcc | uart->gpio_tx_rcc, ENABLE);
RCC_APB1PeriphClockCmd(uart->uart_rcc, ENABLE);
}
// tx gpio 复用推挽输出
GPIO_InitStructure.GPIO_Pin = uart->gpio_tx_pin;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(uart->gpio_tx, &GPIO_InitStructure);
//rx gpio 浮动输入
GPIO_InitStructure.GPIO_Pin = uart->gpio_rx_pin;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(uart->gpio_rx, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = uart->baudrate;
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(uart->uart_ptr, &USART_InitStructure);
if (uart->uart_ptr == USART1) //串口1开启空闲中断 20190715 nl668模块通讯
{
USART_ITConfig(USART1, USART_IT_IDLE, ENABLE);
// USART_DMACmd(USART1, USART_DMAReq_Rx, ENABLE); //开启串口DMA接收
}
else if(uart->uart_ptr == USART2) //串口2开启空闲中断 20190725 cc2530通讯
{
USART_ITConfig(USART2, USART_IT_IDLE, ENABLE);
}
// if(uart->uart_ptr != USART1) //串口1使用的DMA+串口空闲中断 不需要开启接收中断
USART_ITConfig(uart->uart_ptr, USART_IT_RXNE, ENABLE); //使能接收中断
USART_Cmd(uart->uart_ptr, ENABLE); //使能USARTx
NVIC_InitStructure.NVIC_IRQChannel = uart->irqn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
举例uart1的功能实现
static uart_def uart;
void uart1_init(uint32_t baudrate)
{
uart.uart_rcc = RCC_APB2Periph_USART1;
uart.uart_ptr = USART1;
uart.gpio_rx_rcc = RCC_APB2Periph_GPIOA;
uart.gpio_rx = GPIOA;
uart.gpio_rx_pin = GPIO_Pin_10;
uart.gpio_tx_rcc = RCC_APB2Periph_GPIOA;
uart.gpio_tx = GPIOA;
uart.gpio_tx_pin = GPIO_Pin_9;
uart.irqn = USART1_IRQn;
uart.baudrate = baudrate;
uart_init(&uart);
}
void uart1_writeb(uint8_t byte)
{
while (USART_GetFlagStatus(uart.uart_ptr, USART_FLAG_TC) == RESET);
USART_SendData(uart.uart_ptr, byte);
while (USART_GetFlagStatus(uart.uart_ptr, USART_FLAG_TXE) == RESET);
}
|