usart.c
代码语言:javascript复制//串口3配置
static void Usart3GpioInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
//使能GPIOB时钟
RCC_APB2PeriphClockCmd(USART3_GPIO_CLK,ENABLE);
//TX 复用推挽输出
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin = USART3_TX_GPIO_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(USART3_GPIO_PORT,&GPIO_InitStructure);
//RX 浮空输入
GPIO_InitStructure.GPIO_Pin = USART3_RX_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(USART3_GPIO_PORT,&GPIO_InitStructure);
}
static void Usart3Config(void)
{
USART_InitTypeDef USART_InitStructure;
RCC_APB1PeriphClockCmd(USART3_CLK,ENABLE);
//USART1 初始化设置
USART_InitStructure.USART_BaudRate = USART3_BAUDRATE; //波特率
USART_InitStructure.USART_WordLength = USART_WordLength_8b; //8位数据位
USART_InitStructure.USART_StopBits = USART_StopBits_1; //一个停止位
USART_InitStructure.USART_Parity = USART_Parity_No; //无奇偶校验
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; //无硬件流控制
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //收发模式
USART_Init(USART3,&USART_InitStructure); //初始化串口
USART_ITConfig(USART3,USART_IT_RXNE,ENABLE); //开启串口中断
USART_Cmd(USART3,ENABLE); //使能串口
}
static void Usart3NvicInit(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
//usart1 NVIC 配置
NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; //抢占优先级1
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; //子优先级3
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能
NVIC_Init(&NVIC_InitStructure);
}
void Usart3Init(void)
{
Usart3GpioInit();
Usart3NvicInit();
Usart3Config();
}
//重定向输出,使printf能输出在PC端
int fputc(int ch, FILE *f)
{
while((USART3->SR&0x40)==0);//循环发送,直到发送完成
USART3->DR = (u8)ch;
return ch;
}
//中断读取到什么数据就返回什么数据
void USART3_IRQHandler(void)
{
uint16_t temp;
if(USART_GetITStatus(USART3,USART_IT_RXNE)!=RESET)
{
temp = USART_ReceiveData(USART3);
USART_SendData(USART3,temp);
}
}
usart.h
代码语言:javascript复制#ifndef _USART_H_
#define _USART_H_
#include "stm32f10x.h"
#include <stdio.h>
//串口3配置
#define USART3_CLK RCC_APB1Periph_USART3
#define USART3_GPIO_CLK RCC_APB2Periph_GPIOB
#define USART3_BAUDRATE 115200
#define USART3_TX_GPIO_PIN GPIO_Pin_10
#define USART3_RX_GPIO_PIN GPIO_Pin_11
#define USART3_GPIO_PORT GPIOB
#define USART3_IRQn USART3_IRQn
#define USART3_IRQHandler USART3_IRQHandler
void Usart3Init(void);
#endif