RS485.c
#include "stm32f10x.h"
#include "RS485.h"
// 配置串口为RS485模式
void RS485_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
// 使能GPIO和USART时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
// 配置USART1_TX引脚为推挽输出
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置USART1_RX引脚为浮空输入
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置RS485芯片的使能引脚
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_SetBits(GPIOB, GPIO_Pin_5); //485芯片高电平
// 配置USART1为RS485模式
USART_InitStructure.USART_BaudRate = 9600;
USART_InitStructure.USART_WordLength = USART_WordLength_9b;//数据位
USART_InitStructure.USART_StopBits = USART_StopBits_1; //1位停止位
USART_InitStructure.USART_Parity = USART_Parity_Even;//偶校验
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件流控
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;//接收和发送
USART_Init(USART1, &USART_InitStructure);
USART_ClearFlag(USART1,USART_FLAG_RXNE);
USART_Cmd(USART1, ENABLE); //使能串口
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); //使能接收中断
USART_ITConfig(USART1,USART_IT_IDLE,ENABLE);
// NVIC_InitTypeDef NVIC_InitStruct;
// NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn;
// NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
// NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 3;
// NVIC_InitStruct.NVIC_IRQChannelSubPriority = 3;
// NVIC_Init(&NVIC_InitStruct);
// 使能USART1
USART_Cmd(USART1, ENABLE);
}
RS485.h
#ifndef __RS485_H
#define __RS485_H
#include "stm32f10x.h"
void RS485_Configuration(void);
#endif
配置完成就可以像串口一样正常使用,A接A,B接B。