PY32F003F18之RS485通讯

PY32F003F18将USART2连接到RS485芯片,和其它RS485设备实现串口接收后再转发的功能。

一、测试电路

PY32F003F18之RS485通讯_第1张图片

二、测试程序

#include "USART2.h"
#include "stdio.h"  //getchar(),putchar(),scanf(),printf(),puts(),gets(),sprintf()
#include "string.h" //使能strcpy(),strlen(),memset()
#include "delay.h"
#include "MyUSART.h"

//PA0 ------> USART2_TX
//PA1 ------> USART2_RX

uint8_t USART2_TX_Buffer[USART2_TX_Buffer_Size]; //USART2发送缓冲区数组;
uint8_t USART2_TX_Buffer_Send_Index=0;          //USART2_TX_Buffer[]的发送索引值;
uint8_t USART2_TX_Buffer_Load_Index=0;          //USART2_TX_Buffer[]的装载索引值
uint8_t USART2_TX_Completed_Flag;
uint8_t USART2_TX_Overtime_Conter;//USART2发送超时计数器

uint8_t USART2_RX_Buffer[USART2_RX_Buffer_Size]; //USART2接收缓冲区数组
uint8_t USART2_RX_Buffer_Load_Index;          //USART2_RX_Buffer[]的装载索引值
uint8_t USART2_RX_Time_Count;                 //USART2接收时间计数器
uint8_t USART2_RX_Completed_Flag;

void USART2_GPIO_Config(void);
void USART2_NVIC_Cpnfig(void);
void USART2_Mode_Config(uint32_t baudrate);
void USART2_Init(uint32_t baudrate);
void USART2_Load_Send_Data(void);

void RS485_Enable_Output_Init(void)
{
  GPIO_InitTypeDef  GPIO_InitStructure;

  __HAL_RCC_GPIOB_CLK_ENABLE();//使能GPIOB时钟

  //初始化GPIOB5
  GPIO_InitStructure.Pin = GPIO_PIN_5;                  //选择第5脚
  GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP;        //设置引脚工作模式为推挽输出方式
  GPIO_InitStructure.Pull = GPIO_PULLUP;                //配置引脚使能上拉
  GPIO_InitStructure.Speed = GPIO_SPEED_FREQ_VERY_HIGH; //配置GPIO速度为极高

  HAL_GPIO_Init(GPIOB, &GPIO_InitStructure);
	//根据GPIO_InitStructure结构变量指定的参数初始化GPIOB的外设寄存器

	RS485_ENABLE_PIN_Output_High();
}

//函数功能:USART2的IO口配置,PA0是为USART2_TX,PA1是USART2_RX
void USART2_GPIO_Config(void) 
{
  GPIO_InitTypeDef  GPIO_InitStructureure;

  __HAL_RCC_USART2_CLK_ENABLE();//使能USART2外设时钟
  __HAL_RCC_GPIOA_CLK_ENABLE(); //使能GPIOA时钟

  GPIO_InitStructureure.Pin = GPIO_PIN_0;     //选择第0脚,PA0是为USART2_TX
  GPIO_InitStructureure.Mode = GPIO_MODE_AF_PP;            //复用功能推挽模式
  GPIO_InitStructureure.Pull = GPIO_PULLUP;                //引脚上拉被激活
  GPIO_InitStructureure.Speed = GPIO_SPEED_FREQ_VERY_HIGH; //引脚速度为最高速
  GPIO_InitStructureure.Alternate = GPIO_AF9_USART2;       //将引脚复用为USART2
  HAL_GPIO_Init(GPIOA, &GPIO_InitStructureure);
	//根据GPIO_InitStructureure结构变量指定的参数初始化GPIOA的外设寄存器
	//将PA0初始化为USART2_TX

  GPIO_InitStructureure.Pin = GPIO_PIN_1;     //选择第1脚,PA1是USART2_RX
  GPIO_InitStructureure.Mode = GPIO_MODE_AF_PP;            //复用功能推挽模式
  GPIO_InitStructureure.Pull = GPIO_PULLUP;                //引脚上拉被激活
  GPIO_InitStructureure.Speed = GPIO_SPEED_FREQ_VERY_HIGH; //引脚速度为最高速
  GPIO_InitStructureure.Alternate = GPIO_AF9_USART2;       //将引脚复用为USART2
  HAL_GPIO_Init(GPIOA, &GPIO_InitStructureure);
	//根据GPIO_InitStructureure结构变量指定的参数初始化GPIOA的外设寄存器
	//将PA1初始化为USART2_RX
}

//函数功能:设置串口2中断优先级为0x01
void USART2_NVIC_Cpnfig(void)
{
  HAL_NVIC_SetPriority(USART2_IRQn, 0x01, 0);
	//设置串口2中断优先级为0x01,0无意义.USART2_IRQn表示中断源为串口2
}

//函数功能:波特率为115200,数字为8位,停止位为1位,无奇偶校验,允许发送和接收数据,允许接收和发送中断,并使能串口
void USART2_Mode_Config(uint32_t baudrate)
{
	UART_HandleTypeDef UART_HandleStructureure;
	HAL_StatusTypeDef retData;

  __HAL_RCC_USART2_CLK_ENABLE();//使能USART2外设时钟

  UART_HandleStructureure.Instance          = USART2;              //接口为USART2
  UART_HandleStructureure.Init.BaudRate     = baudrate;            //波特率为115200bps
  UART_HandleStructureure.Init.WordLength   = UART_WORDLENGTH_8B;  //串口字长度为8
  UART_HandleStructureure.Init.StopBits     = UART_STOPBITS_1;     //串口停止位为1位
  UART_HandleStructureure.Init.Parity       = UART_PARITY_NONE;    //串口无需奇偶校验
  UART_HandleStructureure.Init.HwFlowCtl    = UART_HWCONTROL_NONE; //串口无硬件流程控制
  UART_HandleStructureure.Init.Mode         = UART_MODE_TX_RX;     //串口工作模式为发送和接收模式
	retData=HAL_UART_Init(&UART_HandleStructureure);
	//根据UART_HandleStructureure型结构初始化USART2
  if ( retData!= HAL_OK)//串口初始化失败
  {
  }
//USART_ITConfig(USART2,UART_IT_PE,ENABLE);
//	__HAL_UART_ENABLE_IT(&UART_HandleStructureure, UART_IT_PE);
//	//串口接收数据时,使能奇偶校验错误时产生中断,Enable the UART Parity Error Interrup

//	USART_ITConfig(USART2,UART_IT_ERR,ENABLE);
//	__HAL_UART_ENABLE_IT(&UART_HandleStructureure, UART_IT_ERR);
//	//串口接收数据时,使能帧错误、噪音错误和溢出错误时产生中断
//	//Enable the UART Error Interrupt: (Frame error, noise error, overrun error)

	USART_ITConfig(USART2,UART_IT_RXNE,ENABLE);
//	__HAL_UART_ENABLE_IT(&UART_HandleStructureure, UART_IT_RXNE);
	开启串口接收中断
	//串口接收数据时,使能"接收数据寄存器不为空"则产生中断(位RXNE=1)
	//Enable the UART Data Register not empty Interrupt

/在串口中断服务函数中发送数据配置开始//
//	USART_ITConfig(USART2,UART_IT_TXE,ENABLE);
//	__HAL_UART_ENABLE_IT(&UART_HandleStructureure, UART_IT_TXE);
	//串口发送数据时,使能"串口发送数据寄存器为空"产生中断(位TXE=1)
	//Enable the UART Transmit data register empty Interrupt

	USART_ITConfig(USART2,UART_IT_TXE,DISABLE);
//	__HAL_UART_DISABLE_IT(&UART_HandleStructureure, UART_IT_TXE);
	//串口发送数据时,不使能"串口发送数据寄存器为空"产生中断(位TXE=0)
	//Disable the UART Transmit Complete Interrupt

//  USART_ITConfig(USART2,UART_IT_TC,ENABLE);
//  __HAL_UART_ENABLE_IT(&UART_HandleStructureure, UART_IT_TC);
	//串口发送数据时,使能"串口发送完成"产生中断(位TC=1)
	//Enable the UART Transmit Complete Interrupt

  USART_ITConfig(USART2,UART_IT_TC,DISABLE);
//	__HAL_UART_DISABLE_IT(&UART_HandleStructureure,UART_IT_TC);
	//串口发送数据时,不使能"串口发送完成"产生中断(位TC=1)
/在串口中断服务函数中发送数据配置结束//

  HAL_NVIC_EnableIRQ(USART2_IRQn);
	//使能串口2中断
	//USART2_IRQn表示中断源为串口2
}

//函数功能:
//波特率为115200,数字为8位,停止位为1位,无奇偶校验
//自动波特率配置模式
//允许发送和接收数据,允许接收和发送中断,并使能串口
void My_USART2_Mode_Config(uint32_t baudrate)
{
	UART_InitTypeDef UART_InitStructureure;
	UART_AdvFeatureInitTypeDef AdvancedInit_Structureure;

  __HAL_RCC_USART2_CLK_ENABLE();//使能USART2外设时钟

  UART_InitStructureure.BaudRate     = baudrate;            //波特率为115200bps
  UART_InitStructureure.WordLength   = UART_WORDLENGTH_8B;  //串口字长度为8
  UART_InitStructureure.StopBits     = UART_STOPBITS_1;     //串口停止位为1位
  UART_InitStructureure.Parity       = UART_PARITY_NONE;    //串口无需奇偶校验
  UART_InitStructureure.HwFlowCtl    = UART_HWCONTROL_NONE; //串口无硬件流程控制
  UART_InitStructureure.Mode         = UART_MODE_TX_RX;     //串口工作模式为发送和接收模式

	AdvancedInit_Structureure.AdvFeatureInit=UART_ADVFEATURE_NO_INIT;//不使用自动波特率
//	AdvancedInit_Structureure.AdvFeatureInit=UART_ADVFEATURE_AUTOBAUDRATE_INIT;//使用自动波特率配置
//	AdvancedInit_Structureure.AutoBaudRateEnable=UART_ADVFEATURE_AUTOBAUDRATE_ENABLE;//自动波特率使能
//	AdvancedInit_Structureure.AutoBaudRateMode=UART_ADVFEATURE_AUTOBAUDRATE_ONSTARTBIT;//自动波特率模式

	USARTx_SetConfig(USART2,&UART_InitStructureure,&AdvancedInit_Structureure);
	//根据UART_HandleStructureure型结构初始化USART2

//USART_ITConfig(USART2,UART_IT_PE,ENABLE);
//	__HAL_UART_ENABLE_IT(&UART_HandleStructureure, UART_IT_PE);
//	//串口接收数据时,使能奇偶校验错误时产生中断,Enable the UART Parity Error Interrup

//	USART_ITConfig(USART2,UART_IT_ERR,ENABLE);
//	__HAL_UART_ENABLE_IT(&UART_HandleStructureure, UART_IT_ERR);
//	//串口接收数据时,使能帧错误、噪音错误和溢出错误时产生中断
//	//Enable the UART Error Interrupt: (Frame error, noise error, overrun error)

	USART_ITConfig(USART2,UART_IT_RXNE,ENABLE);
//	__HAL_UART_ENABLE_IT(&UART_HandleStructureure, UART_IT_RXNE);
	开启串口接收中断
	//串口接收数据时,使能"接收数据寄存器不为空"则产生中断(位RXNE=1)
	//Enable the UART Data Register not empty Interrupt

/在串口中断服务函数中发送数据配置开始//
//	USART_ITConfig(USART2,UART_IT_TXE,ENABLE);
//	__HAL_UART_ENABLE_IT(&UART_HandleStructureure, UART_IT_TXE);
	//串口发送数据时,使能"串口发送数据寄存器为空"产生中断(位TXE=1)
	//Enable the UART Transmit data register empty Interrupt

	USART_ITConfig(USART2,UART_IT_TXE,DISABLE);
//	__HAL_UART_DISABLE_IT(&UART_HandleStructureure, UART_IT_TXE);
	//串口发送数据时,不使能"串口发送数据寄存器为空"产生中断(位TXE=0)
	//Disable the UART Transmit Complete Interrupt

//  USART_ITConfig(USART2,UART_IT_TC,ENABLE);
//  __HAL_UART_ENABLE_IT(&UART_HandleStructureure, UART_IT_TC);
	//串口发送数据时,使能"串口发送完成"产生中断(位TC=1)
	//Enable the UART Transmit Complete Interrupt

  USART_ITConfig(USART2,UART_IT_TC,DISABLE);
//	__HAL_UART_DISABLE_IT(&UART_HandleStructureure,UART_IT_TC);
	//串口发送数据时,不使能"串口发送完成"产生中断(位TC=1)
/在串口中断服务函数中发送数据配置结束//

  HAL_NVIC_EnableIRQ(USART2_IRQn);
	//使能串口2中断
	//USART2_IRQn表示中断源为串口2
}

//函数功能:
//PA0是为USART2_TX,PA1是USART2_RX
//中断优先级为0x01
//波特率为115200,数字为8位,停止位为1位,无奇偶校验,允许发送和接收数据,允许接收和发送中断,并使能串口
void USART2_Init(uint32_t baudrate)
{
	RS485_Enable_Output_Init();
	USART2_GPIO_Config();//USART2的IO口配置,PA0是为USART2_TX,PA1是USART2_RX
	USART2_NVIC_Cpnfig();//设置串口2中断优先级为0x01
//	USART2_Mode_Config(baudrate);
	//波特率为115200,数字为8位,停止位为1位,无奇偶校验,允许发送和接收数据,允许接收和发送中断,并使能串口
	
	My_USART2_Mode_Config(baudrate);
//波特率为115200,数字为8位,停止位为1位,无奇偶校验
//自动波特率配置模式
//允许发送和接收数据,允许接收和发送中断,并使能串口

	USART2_RX_Buffer_Load_Index = 0;
	USART2_RX_Time_Count = 0;
	USART2_TX_Completed_Flag = 0; //允许再次发送数据
	memset(USART2_RX_Buffer,0,USART2_RX_Buffer_Size);
}

//重定义fputc函数
//函数功能:发送ch的值给USART2串口
int fputc(int ch, FILE *f)
{
  USART_SendData(USART2, (unsigned char) ch);
  while( USART_GetFlagStatus(USART2,USART_SR_TC)!= SET); //等待发送完成标志位被置1	
	return ch;
}

//函数功能:串口2发送一个字节
void USART2_SendByte(  unsigned char ch )
{
  USART_SendData(USART2, ch);
  while( USART_GetFlagStatus(USART2,USART_SR_TC)!= SET); //等待发送完成标志位被置1	
}

//函数功能:启动串口2发送
void USART2_Load_Send_Data(void)
{
	uint16_t k;

	RS485_ENABLE_PIN_Output_High();//RS485准备发送
	HAL_Delay(5);
	k=strlen((char*)USART2_TX_Buffer);
	USART2_TX_Buffer_Load_Index = k;

启动发送/
	USART2_TX_Completed_Flag=1;
	USART2_TX_Overtime_Conter=0;
	USART2_TX_Buffer_Send_Index = 0;  //设置USART2_TX_Buffer[]的发送索引值为0

	USART_ITConfig(USART2,UART_IT_TXE,ENABLE);
//	USART_TXEIE_Config(USART2,ENABLE);
	//将"串口控制寄存器1(USART_CR1)中的TXEIE位"设置为1
	//串口发送数据时,使能"串口发送数据寄存器为空"产生中断(位TXEIE=1)
	//Enable the UART Transmit Complete Interrupt
}

//函数功能:串口2中断服务程序
void USART2_IRQHandler(void)
{
	uint8_t RX_temp;

	if( _HAL_UART_GET_FLAG(USART2,USART_SR_RXNE) )
//	if(	SET==USART_GetITStatus(USART2,USART_SR_RXNE))
	{//在串口状态寄存器中,发现RXNE=1,且串口控制寄存器1允许接收数据
		RX_temp = (uint8_t)( USART_ReceiveData(USART2) );//读串口数据
		USART_ClearITPendingBit(USART2,USART_SR_RXNE);
		if(RX_temp=='1' && USART2_RX_Time_Count==0)	USART2_RX_Time_Count = 1;//如果接收到帧头为变频器地址为0x1,则启动USART2接收时间计数器
		if(USART2_RX_Time_Count > 0)
		{
			USART2_RX_Time_Count = 1;//设置USART2接收时间计数器为1;
			USART2_RX_Buffer[USART2_RX_Buffer_Load_Index] = RX_temp;//保存接收到的新数据
			USART2_RX_Buffer_Load_Index++;

			if(USART2_RX_Buffer_Load_Index>=USART2_RX_Buffer_Size) USART2_RX_Buffer_Load_Index=1;//防止USART2_RX_Buffer[]溢出
		}

		//软件先读"串口状态寄存器(USART_SR)",然后再读"串口数据寄存器USART_DR",就可以将ORE位(Overrun错误标志)清零;
		//软件先读"串口状态寄存器(USART_SR)",然后再读"串口数据寄存器USART_DR",就可以将NE位(噪声错误标志)清零;
		//软件先读"串口状态寄存器(USART_SR)",然后再读"串口数据寄存器USART_DR",就可以将FE位(帧错误标志)清零;
		//软件先读"串口状态寄存器(USART_SR)",然后再读"串口数据寄存器USART_DR",就可以将PE位(奇偶校验值错误)清零;
		//软件读"串口数据寄存器USART_DR",就可以将RXNE位清零
  }

	if(	SET==USART_GetITStatus(USART2,USART_SR_TXE))
	{
		USART_ClearITPendingBit(USART2,UART_IT_TXE);
		if(USART2_TX_Buffer_Send_Index < USART2_TX_Buffer_Load_Index)	//未发送完全部数据
		{
	    USART_SendData(USART2,USART2_TX_Buffer[USART2_TX_Buffer_Send_Index]);
	    //将USART2_TX_Buffer[USART2_TX_Buffer_Send_Index]的值写入串口发送"串口发送数据寄存器"
			USART2_TX_Buffer_Send_Index++;
		}
		else //RS485串口发送完成
		{
	    USART_ITConfig(USART2,UART_IT_TXE,DISABLE);
//			USART_TXEIE_Config(USART2,DISABLE);
	    //串口发送数据时,不使能"串口发送数据寄存器为空"产生中断(位TXE=0)
	    //Disabless Transmit Data Register empty interrupt

		  USART_ITConfig(USART2,UART_IT_TC,ENABLE);
			//将"串口控制寄存器1(USART_CR1)中的TCIE位"设置为1
			//串口发送数据时,使能"串口发送完成"产生中断(位TCIE=1)
			//Enables Transmission complete interrupt	
		}
	}
	if(	SET==USART_GetITStatus(USART2,USART_SR_TC))
	{
		USART_ClearITPendingBit(USART2,UART_IT_TC);

		USART_ITConfig(USART2,UART_IT_TC,DISABLE);
		//将"串口控制寄存器1(USART_CR1)中的TCIE位"设置为0
		//串口发送数据时,不使能"串口发送完成"产生中断(位TCIE=0)
		//Disable the UART Transmit Complete Interrupt

		USART2_TX_Completed_Flag=2;      //USART2发送完成
		USART2_TX_Overtime_Conter=0;
		USART2_TX_Buffer_Send_Index = 0;//清除USART2_TX_Buffer[]的发送索引值
		USART2_TX_Buffer_Load_Index = 0;//清除USART2_TX_Buffer[]的装载索引值
//		USART2_RX_Time_Count=0;
//		USART2_RX_Buffer_Load_Index =	0;//清接收计数索引
    RS485_ENABLE_PIN_Output_Low();//更改485为接收	
	}
}
#include "py32f0xx_hal.h"
#include "SystemClock.h"
#include "USART2.h"
#include "stdio.h"  //getchar(),putchar(),scanf(),printf(),puts(),gets(),sprintf()
#include "string.h" //使能strcpy(),strlen(),memset()
#include "delay.h"

const char CPU_Reset_REG[]="\r\nCPU reset!\r\n";
int main(void)
{
	uint8_t i;

  delay_init();
	HAL_Delay(1000);

	USART2_Init(115200);
	strcpy((char*)USART2_TX_Buffer,CPU_Reset_REG);
	USART2_Load_Send_Data();

  while (1)
  {
		delay_ms(10);
		for(i=0;i
#include "MyUSART.h"

void USART_ITConfig(USART_TypeDef * USARTx, uint32_t USART_IT, FunctionalState NewState);
//void USART_RXNEIE_Config(USART_TypeDef * USARTx, FunctionalState NewState);
//void USART_PEIE_Config(USART_TypeDef * USARTx, FunctionalState NewState);
//void USART_TXEIE_Config(USART_TypeDef * USARTx, FunctionalState NewState);
//void USART_EIE_Config(USART_TypeDef * USARTx, FunctionalState NewState);
FlagStatus USART_GetFlagStatus(USART_TypeDef* USARTx, uint16_t USART_FLAG);
ITStatus USART_GetITStatus(USART_TypeDef* USARTx, uint32_t USART_IT);
void USART_ClearITPendingBit(USART_TypeDef* USARTx, uint32_t USART_IT);
void USART_SendData(USART_TypeDef* USARTx, uint16_t Data);
uint16_t USART_ReceiveData(USART_TypeDef* USARTx);
void USARTx_SetConfig(USART_TypeDef* USARTx,UART_InitTypeDef *Init,UART_AdvFeatureInitTypeDef *AdvancedInit);

//函数功能:
//当NewState=ENABLE,USART_IT=UART_IT_RXNE,使能串口接收寄存器为非空时产生中断,即使能RXNEIE=1
//当NewState=ENABLE,USART_IT=UART_IT_PE,使能串口奇偶校验错误产生中断,即使能PEIE=1
//当NewState=ENABLE,USART_IT=UART_IT_ERR,使能帧错误、噪音错误和溢出错误时产生中断,即使能EIE=1
//当NewState=ENABLE,USART_IT=UART_IT_TXE时,使能串口发送寄存器为空产生中断,即使能TXEIE=1
//当NewState=ENABLE,USART_IT=UART_IT_TC时,使能发送完成产生中断,即使能TCIE=1
void USART_ITConfig(USART_TypeDef * USARTx, uint32_t USART_IT, FunctionalState NewState)
{
	if(NewState==DISABLE) _UART_DISABLE_IT(USARTx,USART_IT);
	else _HAL_UART_ENABLE_IT(USARTx,USART_IT);
}

/*
//函数功能:使能串口接收中断
//当NewState=ENABLE,使能串口接收中断
//当NewState=DISABLE,不使能串口接收中断
void USART_RXNEIE_Config(USART_TypeDef * USARTx, FunctionalState NewState)
{
	if(NewState==DISABLE)
		CLEAR_BIT(USARTx->CR1,USART_CR1_RXNEIE);
	//将"串口控制寄存器1(USART_CR1)中的RXNEIE位"置0,不使能RXNE接收产生中断
	else
		SET_BIT(USARTx->CR1,USART_CR1_RXNEIE);
	//将"串口控制寄存器1(USART_CR1)中的RXNEIE位"置1,使能RXNE接收产生中断
}

//函数功能:使能串口奇偶校验错误中断
//当NewState=ENABLE,使能PE奇偶校验错误产生中断
//当NewState=DISABLE,不使能PE奇偶校验错误产生中断
void USART_PEIE_Config(USART_TypeDef * USARTx, FunctionalState NewState)
{
	if(NewState==DISABLE)
		CLEAR_BIT(USARTx->CR1,USART_CR1_PEIE);
	//将"串口控制寄存器1(USART_CR1)中的PEIE位"置0,不使能PE奇偶校验错误产生中断
	else
		SET_BIT(USARTx->CR1,USART_CR1_PEIE);
	//将"串口控制寄存器1(USART_CR1)中的PEIE位"置1,使能PE奇偶校验错误产生中断
}

//函数功能:使能串口发送中断
//当NewState=ENABLE,使能TXE发送产生中断
//当NewState=DISABLE,不使能TXE发送产生中断
void USART_TXEIE_Config(USART_TypeDef * USARTx, FunctionalState NewState)
{
	if(NewState==DISABLE)
		CLEAR_BIT(USARTx->CR1,USART_CR1_TXEIE);
	//将"串口控制寄存器1(USART_CR1)中的TXEIE位"置0,不使能TXE发送产生中断
	else
		SET_BIT(USARTx->CR1,USART_CR1_TXEIE);
	//将"串口控制寄存器1(USART_CR1)中的TXEIE位"置1,使能TXE发送产生中断
}

//函数功能:使能串口"帧错误FE、overrun错误ORE和噪声NF“产生中断
//当NewState=ENABLE,使能串口"帧错误FE、overrun错误ORE和噪声NF“产生中断能TXE发送产生中断
//当NewState=DISABLE,不使能串口"帧错误FE、overrun错误ORE和噪声NF“产生中断能TXE发送产生中断
void USART_EIE_Config(USART_TypeDef * USARTx, FunctionalState NewState)
{
	if(NewState==DISABLE)
		CLEAR_BIT(USARTx->CR3, USART_CR3_EIE);
		//清除"帧错误FE、overrun错误ORE和噪声NF中断使能位"
	else
		SET_BIT(USARTx->CR3, USART_CR3_EIE);
	//将"串口控制寄存器1(USART_CR3)中的EIE位"置1,使能"帧错误FE、overrun错误ORE和噪声NF“产生中断
}
*/

//函数功能:读串口状态标志位
FlagStatus USART_GetFlagStatus(USART_TypeDef* USARTx, uint16_t USART_FLAG)
{
	if( USART_FLAG & READ_REG(USARTx->SR) ) return SET;
	else  return RESET;
}

//函数功能:读串口中断标志位
ITStatus USART_GetITStatus(USART_TypeDef* USARTx, uint32_t USART_IT)
{
	if( USART_IT & READ_REG(USARTx->SR) ) return SET;
	else  return RESET;
}

//函数功能:
//USART_IT=UART_IT_RXNE,清除"串口接收寄存器为非空时产生的中断标志位"
//USART_IT=UART_IT_PE,清除"串口奇偶校验错误产生的中断标志位"
//USART_IT=UART_IT_ERR,清除"帧错误、噪音错误和溢出错误时产生的中断标志位"
//USART_IT=UART_IT_TXE时,清除"串口发送寄存器为空产生的中断标志位"
//USART_IT=UART_IT_TC时,清除"发送完成产生的中断标志位"
void USART_ClearITPendingBit(USART_TypeDef* USARTx, uint32_t USART_IT)
{
	CLEAR_BIT(USARTx->SR,USART_IT);//将"状态寄存器USART_SR"的USART_IT
}

//函数功能:串口发送数据
void USART_SendData(USART_TypeDef* USARTx, uint16_t Data)
{
	USARTx->DR = (Data & (uint16_t)0x01FF);
}

//函数功能:串口接收数据
uint16_t USART_ReceiveData(USART_TypeDef* USARTx)
{
	return (uint16_t)(USARTx->DR & (uint16_t)0x01FF);
}

//函数功能:USARTx_CK引脚配置
void USART_CK_Pin_Config(USART_TypeDef* USARTx, FunctionalState NewState)
{
	if(NewState==DISABLE)
	{
    CLEAR_BIT(USARTx->CR2, USART_CR2_CLKEN);
	  //清除"串口控制寄存器2(USART_CR2)中的CLKEN位",不使能USARTx_CK引脚
	}
	else
	{
    SET_BIT(USARTx->CR2, USART_CR2_CLKEN);
	  //设置"串口控制寄存器2(USART_CR2)中的CLKEN位",使能USARTx_CK引脚
	}
}

//函数功能:USARTx半双工通讯配置
//NewState=DISABLE,配置串口为"非半双工模式"
//NewState=ENABLE,配置串口为"半双工模式"
void USART_Half_Duplex_Config(USART_TypeDef* USARTx, FunctionalState NewState)
{
	if(NewState==DISABLE)
	{
    CLEAR_BIT(USARTx->CR3, USART_CR3_HDSEL);
	  //清除"串口控制寄存器3(USART_CR3)中的HDSEL位",配置串口为"非半双工模式"
	}
	else
	{
    SET_BIT(USARTx->CR3, USART_CR3_HDSEL);
	  //设置"串口控制寄存器3(USART_CR3)中的HDSEL位",配置串口为"半双工模式"
	}
}

//函数工能:使用自动波特率配置
//AdvancedInit->AdvFeatureInit=UART_ADVFEATURE_AUTOBAUDRATE_INIT;//使用自动波特率配置
//AdvancedInit->AutoBaudRateEnable=UART_ADVFEATURE_AUTOBAUDRATE_ENABLE;//自动波特率使能
//AdvancedInit->AutoBaudRateMode=UART_ADVFEATURE_AUTOBAUDRATE_ONSTARTBIT;//自动波特率模式
void USART_Automatic_Baudrate_Detection_Config(USART_TypeDef* USARTx, UART_AdvFeatureInitTypeDef *AdvancedInit)
{
  /* Check whether the set of advanced features to configure is properly set */
  assert_param(IS_UART_ADVFEATURE_INIT(AdvancedInit->AdvFeatureInit));

  /* if required, configure auto Baud rate detection scheme */
  if (HAL_IS_BIT_SET(AdvancedInit->AdvFeatureInit, UART_ADVFEATURE_AUTOBAUDRATE_INIT))
  {
    assert_param(IS_USART_AUTOBAUDRATE_DETECTION_INSTANCE(USARTx));
    assert_param(IS_UART_ADVFEATURE_AUTOBAUDRATE(AdvancedInit->AutoBaudRateEnable));
    MODIFY_REG(USARTx->CR3, USART_CR3_ABREN, AdvancedInit->AutoBaudRateEnable);
    /* set auto Baudrate detection parameters if detection is enabled */
    if (AdvancedInit->AutoBaudRateEnable == UART_ADVFEATURE_AUTOBAUDRATE_ENABLE)
    {
      assert_param(IS_UART_ADVFEATURE_AUTOBAUDRATEMODE(AdvancedInit->AutoBaudRateMode));
      MODIFY_REG(USARTx->CR3, USART_CR3_ABRMODE, AdvancedInit->AutoBaudRateMode);
    }
  }
}

//函数功能:将UART_InitTypeDef型结构变量写入"串口控制寄存器"
void USARTx_SetConfig(USART_TypeDef* USARTx,UART_InitTypeDef *Init,UART_AdvFeatureInitTypeDef *AdvancedInit)
{
  uint32_t tmpreg;
  uint32_t pclk;

  /* Check the parameters */
  assert_param(IS_UART_BAUDRATE(Init->BaudRate));
  assert_param(IS_UART_STOPBITS(Init->StopBits));
  assert_param(IS_UART_PARITY(Init->Parity));
  assert_param(IS_UART_MODE(Init->Mode));

  _HAL_UART_DISABLE(USARTx);
	//将"串口控制寄存器1(USART_CR1)中的UE位"置0,不使能串口

  /*-------------------------- USART CR2 Configuration -----------------------*/
  /* Configure the UART Stop Bits: Set STOP[13:12] bits
     according to Init->StopBits value */
  MODIFY_REG(USARTx->CR2, USART_CR2_STOP, Init->StopBits);
	//使用Init->StopBits的值修改"串口控制寄存器2(USART_CR2)中的STOP位",用来设置停止位的位数

  /*-------------------------- USART CR1 Configuration -----------------------*/
  /* Configure the UART Word Length, Parity and mode:
     Set the M bits according to Init->WordLength value
     Set PCE and PS bits according to Init->Parity value
     Set TE and RE bits according to Init->Mode value
     Set OVER8 bit according to Init->OverSampling value */

#if defined(USART_CR3_OVER8)
  tmpreg = (uint32_t)Init->WordLength | Init->Parity | Init->Mode;
	//将"数据长度,奇偶校验,串口发送和接收模式合并为字,准备修改"串口控制寄存器1(USART_CR1)
  MODIFY_REG(USARTx->CR1,
             (uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE),
             tmpreg);

  tmpreg = (uint32_t) Init->OverSampling;//准备修改"串口控制寄存器3(USART_CR3)中的OVER8位"
  MODIFY_REG(USARTx->CR3,
             (uint32_t)(USART_CR3_OVER8),
             tmpreg);
#else
  tmpreg = (uint32_t)Init->WordLength | Init->Parity | Init->Mode;
  MODIFY_REG(USARTx->CR1,
             (uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE),
             tmpreg);
#endif /* USART_CR3_OVER8 */

  /*-------------------------- USART CR3 Configuration -----------------------*/
  /* Configure the UART HFC: Set CTSE and RTSE bits according to Init->HwFlowCtl value */
  MODIFY_REG(USARTx->CR3, (USART_CR3_RTSE | USART_CR3_CTSE), Init->HwFlowCtl);
	//修改"串口控制寄存器3中的RTS和CTS位"

#if defined(USART_CR3_OVER8)
  /* Check the Over Sampling */
  if(Init->OverSampling == UART_OVERSAMPLING_8)
  {
    /*-------------------------- USART BRR Configuration ---------------------*/
    pclk = HAL_RCC_GetPCLK1Freq();//读取PCLK1时钟频率
    USARTx->BRR = UART_BRR_SAMPLING8(pclk, Init->BaudRate);
		//设置串口波特率
  }
  else
  {
    /*-------------------------- USART BRR Configuration ---------------------*/
    pclk = HAL_RCC_GetPCLK1Freq();//读取PCLK1时钟频率
    USARTx->BRR = UART_BRR_SAMPLING16(pclk, Init->BaudRate);
		//设置串口波特率
  }
#else
  /*-------------------------- USART BRR Configuration ---------------------*/

  pclk = HAL_RCC_GetPCLK1Freq();
  USARTx->BRR = UART_BRR_SAMPLING16(pclk, Init->BaudRate);

#endif /* USART_CR3_OVER8 */

	if( AdvancedInit->AdvFeatureInit != UART_ADVFEATURE_NO_INIT )
	{//使用自动波特率配置
	  USART_Automatic_Baudrate_Detection_Config(USARTx,AdvancedInit);
	}

	USART_CK_Pin_Config(USARTx,DISABLE);//不使用USARTx_CK引脚配置
	USART_Half_Duplex_Config(USARTx,DISABLE);//配置串口为"非半双工模式"
	_HAL_UART_ENABLE(USARTx);//使能串口
}
#ifndef __MyUSART_H
#define __MyUSART_H

#include "py32f0xx_hal.h"

#define _HAL_UART_ENABLE(__INSTANCE__)               ((__INSTANCE__)->CR1 |=  USART_CR1_UE)
//将"串口控制寄存器1(USART_CR1)中的UE位"置1,使能串口

#define _HAL_UART_DISABLE(__INSTANCE__)              ((__INSTANCE__)->CR1 &=  ~USART_CR1_UE)
//将"串口控制寄存器1(USART_CR1)中的UE位"置0,不使能串口

#define _HAL_UART_ENABLE_IT(__INSTANCE__, __INTERRUPT__)   ((((__INTERRUPT__) >> 28U) == UART_CR1_REG_INDEX)? ((__INSTANCE__)->CR1 |= ((__INTERRUPT__) & UART_IT_MASK)): \
                                                           (((__INTERRUPT__) >> 28U) == UART_CR2_REG_INDEX)? ((__INSTANCE__)->CR2 |= ((__INTERRUPT__) & UART_IT_MASK)): \
                                                           ((__INSTANCE__)->CR3 |= ((__INTERRUPT__) & UART_IT_MASK)))
//使能串口中断
																													 
#define _UART_DISABLE_IT(__INSTANCE__, __INTERRUPT__)  ((((__INTERRUPT__) >> 28U) == UART_CR1_REG_INDEX)? ((__INSTANCE__)->CR1 &= ~((__INTERRUPT__) & UART_IT_MASK)): \
                                                           (((__INTERRUPT__) >> 28U) == UART_CR2_REG_INDEX)? ((__INSTANCE__)->CR2 &= ~((__INTERRUPT__) & UART_IT_MASK)): \
                                                           ((__INSTANCE__)->CR3 &= ~ ((__INTERRUPT__) & UART_IT_MASK)))
//不使能串口中断

#define _HAL_UART_GET_FLAG(__INSTANCE__, __FLAG__) (((__INSTANCE__)->SR & (__FLAG__)) == (__FLAG__))

extern void USART_ITConfig(USART_TypeDef * USARTx, uint32_t USART_IT, FunctionalState NewState);
//extern void USART_RXNEIE_Config(USART_TypeDef * USARTx, FunctionalState NewState);
//extern void USART_PEIE_Config(USART_TypeDef * USARTx, FunctionalState NewState);
//extern void USART_TXEIE_Config(USART_TypeDef * USARTx, FunctionalState NewState);
//void USART_EIE_Config(USART_TypeDef * USARTx, FunctionalState NewState);
extern FlagStatus USART_GetFlagStatus(USART_TypeDef* USARTx, uint16_t USART_FLAG);
extern ITStatus USART_GetITStatus(USART_TypeDef* USARTx, uint32_t USART_IT);
extern void USART_ClearITPendingBit(USART_TypeDef* USARTx, uint32_t USART_IT);
extern void USART_SendData(USART_TypeDef* USARTx, uint16_t Data);
extern uint16_t USART_ReceiveData(USART_TypeDef* USARTx);
extern void USARTx_SetConfig(USART_TypeDef* USARTx,UART_InitTypeDef *Init,UART_AdvFeatureInitTypeDef *AdvancedInit);
#endif /* __MyUSART_H */
#include "delay.h"

static uint8_t  fac_us=0; //us延时倍乘数

void delay_init(void);
void delay_us(uint32_t nus);
void delay_ms(uint32_t nms);

//函数功能:配置"SysTick定时器"每1ms中断一次,优先级为最低
void delay_init(void)
{
	fac_us=SystemCoreClock/1000000;//不论是否使用OS,fac_us都需要使用
	uwTickFreq=HAL_TICK_FREQ_1KHZ;
	//准备配置"SysTick定时器"每1ms中断一次
	//配置"SysTick定时器"时钟源为系统时钟,并使能中断
  //HAL_TICK_FREQ_10HZ= 100,"SysTick计数器"的中断周期为100ms
  //HAL_TICK_FREQ_100HZ= 10,"SysTick计数器"的中断周期为10ms
  //HAL_TICK_FREQ_1KHZ = 1,"SysTick计数器"的中断周期为1ms

	HAL_InitTick(PRIORITY_LOWEST);//配置"SysTick定时器"每1ms中断一次,优先级为最低
//	HAL_Init();//配置"SysTick定时器"每1ms中断一次,优先级为最低

	HAL_SetTickFreq(uwTickFreq);//设置"SysTick滴答定时器"的中断周期为uwTickFreq个毫秒
}

//函数功能:延时nus
//nus:要延时的us数.	
//nus:0~204522252(最大值即2^32/fac_us)	    								   
void delay_us(uint32_t nus)
{		
	uint32_t ticks;
	uint32_t told,tnow,tcnt=0;
	uint32_t reload=SysTick->LOAD;//读取"SysTick定时器"自动重装载值
	ticks=nus*fac_us; 						//需要的节拍数 
	told=SysTick->VAL;        	  //读取"系统滴答定时器的计数值"
	while(1)
	{
		tnow=SysTick->VAL;//读取"系统滴答定时器的计数值"	
		if(tnow!=told)
		{	    
			if(tnow=ticks)break;			//时间超过/等于要延迟的时间,则退出.
		}		
	}										    
}

//函数功能:延时nms
//nms:要延时的ms数
//nms:0~65535
void delay_ms(uint32_t nms)
{	
	delay_us((uint32_t)(nms*1000));//普通方式延时
}

//HAL库接口函数
//HAL_Delay(x)延时x毫秒,x<0xFFFFFFFF,至少需要延时一个周期
//HAL_SuspendTick();不使能"SysTick滴答定时器"中断
//HAL_ResumeTick();使能"SysTick滴答定时器"中断
//HAL_GetTickFreq();读取"SysTick滴答定时器"的中断频率
//HAL_SetTickFreq(Freq);设置"SysTick滴答定时器"的中断频率为Freq
//HAL_GetTickPrio();读取"SysTick滴答定时器"的中断优先级
//HAL_GetTick();读取"SysTick滴答定时器"的中断次数计数器uwTick
//HAL_IncTick();供SysTick_Handler()调用
//uwTickFreq=HAL_TICK_FREQ_1KHZ;//准备配置"SysTick定时器"每1ms中断一次
//HAL_InitTick(PRIORITY_LOWEST);//配置"SysTick定时器"每1ms中断一次,优先级为最低
//HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource)
//设置系统滴答定时器的时钟源
//CLKSource=SYSTICK_CLKSOURCE_HCLK_DIV8时,系统滴答定时器的时钟源为系统时钟的8分频
//CLKSource=SYSTICK_CLKSOURCE_HCLK,系统滴答定时器的时钟源为系统时钟

三、测试结果

PY32F003F18之RS485通讯_第2张图片

你可能感兴趣的:(产品研发,PY32F003F18P,USART,嵌入式硬件,单片机,RS485,经验分享)