STM32F有一些型号,可以直接驱动RS485的;在网上搜索了好多,没有现成的实例;好多提问,最佳答案是否定的,不能自动切换,需要用普通IO做RE 和 DE的驱动。本人使用GD32F330 实验,用RTS引脚实现自动切换;初始化代码分享出来供参考。这颗MCU和STM32F030和051系列管脚兼容,寄存器兼容。
/*
* File: USART.h
* Author: hai
*
* Created on November 22, 2020, 11:35 PM
*/
#ifndef USART_H
#define USART_H
#include "gd32f3x0.h"
/* definition for COM 1, connected to USART0 */
#define INVERTERCOM USART1
#define INVERTERCOM_CLK RCU_USART1
#define INVERTERCOM_TX_PIN GPIO_PIN_2
#define INVERTERCOM_RX_PIN GPIO_PIN_3
#define INVERTERCOM_RTS_PIN GPIO_PIN_1
#define INVERTERCOM_GPIO_PORT GPIOA
#define INVERTERCOM_GPIO_CLK RCU_GPIOA
#define INVERTERCOM_AF GPIO_AF_1
#define INVERTERCOM_BPS 38400U
#ifdef __cplusplus
extern "C" {
#endif
void com_init(uint32_t COM);
#ifdef __cplusplus
}
#endif
#endif /* USART_H */
#include "usart.h"
#include <stdio.h>
void com_init(uint32_t COM)
{
/* enable GPIO clock */
rcu_periph_clock_enable(INVERTERCOM_GPIO_CLK);
/* enable USART clock */
rcu_periph_clock_enable(INVERTERCOM_CLK);
/* connect port to USARTx_Tx_RTS */
gpio_af_set(INVERTERCOM_GPIO_PORT, INVERTERCOM_AF, INVERTERCOM_RTS_PIN|INVERTERCOM_TX_PIN|INVERTERCOM_RX_PIN);
/* configure USART Tx as alternate function push-pull */
gpio_mode_set(INVERTERCOM_GPIO_PORT,GPIO_MODE_AF,GPIO_PUPD_PULLUP,INVERTERCOM_RTS_PIN);
gpio_output_options_set(INVERTERCOM_GPIO_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_10MHZ,INVERTERCOM_RTS_PIN);
/* configure USART Tx as alternate function push-pull */
gpio_mode_set(INVERTERCOM_GPIO_PORT, GPIO_MODE_AF, GPIO_PUPD_PULLUP,INVERTERCOM_TX_PIN);
gpio_output_options_set(INVERTERCOM_GPIO_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_10MHZ,INVERTERCOM_TX_PIN);
/* configure USART Rx as alternate function push-pull */
gpio_mode_set(INVERTERCOM_GPIO_PORT, GPIO_MODE_AF, GPIO_PUPD_PULLUP,INVERTERCOM_RX_PIN);
gpio_output_options_set(INVERTERCOM_GPIO_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_10MHZ,INVERTERCOM_RX_PIN);
/* USART configure */
usart_deinit(COM);
usart_baudrate_set(COM,INVERTERCOM_BPS);
usart_rs485_driver_enable(COM); //驱动使能
usart_driver_deassertime_config(COM,0x1F); // DE (驱动使能)信号的置位与第一个字节的起始位之间的时间间隔0-0x1F
usart_driver_assertime_config(COM,0x1F); //定义一个发送信息最后一个字节的停止位与置低 DE(驱动使能)信号之间的时间间隔
usart_depolarity_config(COM,USART_DEP_LOW); //DE极性,根据硬件选择,这里硬件用三极管反向了
usart_transmit_config(COM, USART_TRANSMIT_ENABLE);
usart_receive_config(COM, USART_RECEIVE_ENABLE);
usart_enable(COM);
}
|