usart.c
#include "usart.h"
int fputc(int ch, FILE *f)
{
while(RESET == usart_flag_get(PCS_COM, USART_FLAG_TBE));
usart_data_transmit(PCS_COM, (uint8_t)ch);
return ch;
}
//PCS COM使能,1=发送,0=接收
void gd_485_com_en(uint8_t flag)
{
if(flag)
{
GPIO_BOP(PCS_COM_EN_PORT)=PCS_COM_EN_PIN;//置1
}
else
{
GPIO_BC(PCS_COM_EN_PORT)=PCS_COM_EN_PIN;//置0
}
}
//com:串口号
//bound:波特率 96=9600
void gd_485_com_init(uint32_t com,uint16_t bound)
{
rcu_periph_clock_enable( PCS_COM_TX_CLK);
rcu_periph_clock_enable( PCS_COM_RX_CLK);
rcu_periph_clock_enable( PCS_COM_EN_CLK);
/* enable USART clock */
rcu_periph_clock_enable(PCS_COM_CLK);
/* connect port to USARTx_Tx */
gpio_af_set(PCS_COM_TX_PORT, PCS_COM_AF, PCS_COM_TX_PIN);
/* connect port to USARTx_Rx */
gpio_af_set(PCS_COM_RX_PORT, PCS_COM_AF, PCS_COM_RX_PIN);
/* configure USART Tx as alternate function push-pull */
gpio_mode_set(PCS_COM_TX_PORT, GPIO_MODE_AF, GPIO_PUPD_PULLUP,PCS_COM_TX_PIN);
gpio_output_options_set(PCS_COM_TX_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ,PCS_COM_TX_PIN);
/* configure USART Rx as alternate function push-pull */
gpio_mode_set(PCS_COM_RX_PORT, GPIO_MODE_AF, GPIO_PUPD_PULLUP,PCS_COM_RX_PIN);
gpio_output_options_set(PCS_COM_RX_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ,PCS_COM_RX_PIN);
/* configure COM En as alternate function push-pull */
gpio_mode_set(PCS_COM_EN_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_PULLUP,PCS_COM_EN_PIN);
gpio_output_options_set(PCS_COM_EN_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ,PCS_COM_EN_PIN);
usart_deinit(com);
usart_baudrate_set(com,bound);
usart_receive_config(com, USART_RECEIVE_ENABLE);
usart_transmit_config(com, USART_TRANSMIT_ENABLE);
usart_enable(com);
nvic_irq_enable(PCS_COM_IRQN, 0, 0);
usart_interrupt_enable(PCS_COM, USART_INT_RBNE);//使能接收中断
usart_enable(PCS_COM);//使能串口
}
usart.h
#ifndef __USART_H
#define __USART_H
#include "head.h"
#define PCS_COM_IRQN USART5_IRQn
#define PCS_COM USART5
#define PCS_COM_CLK RCU_USART5
#define PCS_COM_AF GPIO_AF_8
#define PCS_COM_TX_PIN GPIO_PIN_6
#define PCS_COM_TX_PORT GPIOC
#define PCS_COM_TX_CLK RCU_GPIOC
#define PCS_COM_RX_PIN GPIO_PIN_7
#define PCS_COM_RX_PORT GPIOC
#define PCS_COM_RX_CLK RCU_GPIOC
#define PCS_COM_EN_PIN GPIO_PIN_14
#define PCS_COM_EN_PORT GPIOE
#define PCS_COM_EN_CLK RCU_GPIOE
#endif
串口中断处理函数
unsigned char arr_rxData[100]={0};//存储串口接收的数据
unsigned int arr_len=0;//串口已经接收数据的字节数个数
char rxFlg=0;//默认串口未接收到数据
void USART5_IRQHandler(void)
{
if(RESET != usart_interrupt_flag_get(PCS_COM, USART_INT_FLAG_RBNE))
{
LED_ON();
arr_rxData[arr_len++]=usart_data_receive(PCS_COM);
if(arr_len>10)
{
rxFlg=1;
arr_rxData[arr_len]='\0';
usart_interrupt_disable(PCS_COM, USART_INT_RBNE);
}
}
}
主函数代码
gd_485_com_init(PCS_COM,9600);
gd_485_com_en(0);//接收使能
while(1)
{
if(rxFlg==1)
{
gd_485_com_en(1);//发送使能
delay_1ms(10);//不延时会乱码,硬件问题
printf("%s\r\n",arr_rxData);
arr_len=0;
rxFlg=0;
memset(arr_rxData,0,sizeof(arr_rxData));
gd_485_com_en(0);//接收使能
usart_interrupt_enable(PCS_COM, USART_INT_RBNE);
}
}