3.STM32_USART的配置
一:FX_USART1.c
1.配置USATR1:
void Serial1_begin(u32 bps)
{
#define TX GPIO_Pin_9
#define RX GPIO_Pin_10
//定义结构体
GPIO_InitTypeDef GPIO_InitStructure;
//使能时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
//配置接收管脚GPIO_Pin_10 RX
GPIO_InitStructure.GPIO_Pin = RX;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//浮空输入
GPIO_Init(GPIOA, &GPIO_InitStructure);
//配置发送管脚GPIO_Pin_9 TX
GPIO_InitStructure.GPIO_Pin = TX;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;//复用推挽输出
GPIO_Init(GPIOA, &GPIO_InitStructure);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
USART_InitTypeDef USART_InitStructure;
//波特率、字长、停止位、奇偶校验位、硬件流控制、异步串口为默认(被屏蔽字设置)
USART_InitStructure.USART_BaudRate = bps; //波特率
USART_InitStructure.USART_WordLength = USART_WordLength_8b; //数据位
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(USART1, &USART_InitStructure); //初始化到串口USART1
USART_ClearFlag(USART1,USART_FLAG_TC); //清除发送完成标志位
USART_Cmd(USART1, ENABLE); //USART1终端优先级的配置
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); //使能接收终端
USART1_NVIC_Configuration();
}
2.开启接收中断
void USART1_NVIC_Configuration(void) //组0空
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;//指定IRQ通道
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;//指定先占优先级
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;//从优先级
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //定义的IRQ是被使能还是失能
NVIC_Init(&NVIC_InitStructure);
}
3.中断程序
接收什么,就发出来什么,根据需要可更改
void USART1_IRQHandler(void)
{
u8 receive_data;
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{
receive_data = USART_ReceiveData(USART1); //接收单个字节的串口数据
USART_SendData(USART1,receive_data);
}
USART_ClearITPendingBit(USART1, USART_IT_RXNE);
}
4.printf()函数发送数据
int fputc(int c,FILE *stream)
{
USART1->DR = c;//将c赋给串口1的DR寄存器,即重定向到串口,也可以是其他的接口
while(!(USART1->SR & (1 << 7))) {}; //等待数据发送完成
return c;
}
5.scanf()函数接收
int fgetc(FILE *stream)
{
while(!(USART1->SR & (1 << 5))) {}; //等待数据接收完成
return USART1->DR;
}
二:FX_USART1.h
#ifndef FX_USART1_H
#define FX_USART1_H
#include "stm32f10x.h" // Device header
#include "stm32f10x_usart.h" // Keil::Device:StdPeriph Drivers:USART
#include "stdio.h"
void Serial1_begin(u32 bps);
void USART1_NVIC_Configuration(void); //组0空
#endif
四:main 函数
注:选微库
主函数
#include "stm32f10x.h" // Device header
#include "FX_USART1.h"
int main()
{
Serial1_begin(115200);
printf("asdf");
while(1)
{
}
}