generated from hulk/gd32e23x_template_cmake_vscode
66 lines
2.2 KiB
C
66 lines
2.2 KiB
C
#include "uart.h"
|
||
#include "gd32e23x_usart.h"
|
||
#include "gd32e23x_rcu.h"
|
||
#include "gd32e23x_gpio.h"
|
||
#include "board_config.h"
|
||
|
||
|
||
void uart0_init(void) {
|
||
/* 使能 GPIOA 和 USART0 时钟 */
|
||
rcu_periph_clock_enable(RS485_GPIO_RCU);
|
||
rcu_periph_clock_enable(RS485_RCU);
|
||
|
||
/* 配置 PA2 为 USART0_TX,PA3 为 USART0_RX */
|
||
gpio_af_set(RS485_GPIO_PORT, GPIO_AF_1, RS485_TX_PIN | RS485_RX_PIN | RS485_EN_PIN);
|
||
|
||
gpio_mode_set(RS485_GPIO_PORT, GPIO_MODE_AF, GPIO_PUPD_PULLUP, RS485_TX_PIN | RS485_RX_PIN);
|
||
gpio_output_options_set(RS485_GPIO_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, RS485_TX_PIN | RS485_RX_PIN);
|
||
|
||
gpio_mode_set(RS485_GPIO_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, RS485_EN_PIN);
|
||
gpio_output_options_set(RS485_GPIO_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, RS485_EN_PIN);
|
||
|
||
/* 配置波特率、数据位、停止位等 */
|
||
usart_deinit(RS485_PHY);
|
||
usart_baudrate_set(RS485_PHY, RS485_BAUDRATE);
|
||
usart_receive_config(RS485_PHY, USART_RECEIVE_ENABLE);
|
||
usart_transmit_config(RS485_PHY, USART_TRANSMIT_ENABLE);
|
||
|
||
usart_driver_assertime_config(RS485_PHY, 0x01);
|
||
usart_driver_deassertime_config(RS485_PHY, 0x01);
|
||
|
||
usart_rs485_driver_enable(RS485_PHY);
|
||
|
||
usart_enable(RS485_PHY);
|
||
|
||
// TODO NVIC
|
||
}
|
||
|
||
static uart_printf_port_t g_printf_port = UART_PRINTF_USART0;
|
||
|
||
void uart_set_printf_port(uart_printf_port_t port) {
|
||
g_printf_port = port;
|
||
}
|
||
|
||
// printf 重定向,支持多串口
|
||
int __io_putchar(int ch) {
|
||
switch (g_printf_port) {
|
||
case UART_PRINTF_USART0:
|
||
while (usart_flag_get(USART0, USART_FLAG_TBE) == RESET) {}
|
||
usart_data_transmit(USART0, (uint8_t)ch);
|
||
break;
|
||
case UART_PRINTF_USART1:
|
||
while (usart_flag_get(USART1, USART_FLAG_TBE) == RESET) {}
|
||
usart_data_transmit(USART1, (uint8_t)ch);
|
||
break;
|
||
case UART_PRINTF_BOTH:
|
||
while (usart_flag_get(USART0, USART_FLAG_TBE) == RESET) {}
|
||
usart_data_transmit(USART0, (uint8_t)ch);
|
||
while (usart_flag_get(USART1, USART_FLAG_TBE) == RESET) {}
|
||
usart_data_transmit(USART1, (uint8_t)ch);
|
||
break;
|
||
default:
|
||
break;
|
||
}
|
||
return ch;
|
||
}
|