话不多说先演示代码
usart.c
#include "stm32f10x.h"
#include "usart.h"
#include "stdio.h"
#pragma import(__use_no_semihosting)
//
struct __FILE
{
int handle;
};
FILE __stdout;
//
int _sys_exit(int x)
{
x = x;
}
int fputc(int ch, FILE *f)
{
USART_SendData(USART1, (unsigned char) ch);
while (!(USART1->SR & USART_FLAG_TXE));
return ch;
}
/************************************
PA9 ---- USART1_TX
PA10 ---- USART1_RX
*************************************/
void Usart1_Init(int myBaudRate)
{
GPIO_InitTypeDef GPIO_InitStruct;
USART_InitTypeDef USART_InitStruct;
NVIC_InitTypeDef NVIC_InitStructure;
//时钟的使能
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_AFIO, ENABLE);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP; //推挽输出
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING; //浮空输入
GPIO_Init(GPIOA, &GPIO_InitStruct);
USART_InitStruct.USART_BaudRate = myBaudRate; //自己在调用函数时,填写波特率
USART_InitStruct.USART_Mode = USART_Mode_Tx|USART_Mode_Rx; //使用模式
USART_InitStruct.USART_Parity = USART_Parity_No; //无奇偶效验
USART_InitStruct.USART_StopBits = USART_StopBits_1; //1个停止位
USART_InitStruct.USART_WordLength= USART_WordLength_8b; //一个字节
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None; //无硬件控制流
//5串口初始化
USART_Init(USART1, &USART_InitStruct);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; //中断通道1
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x01; //抢占优先级
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x01; //响应优先级
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //使能
//启动定时器中断,配置NVIC
NVIC_Init(&NVIC_InitStructure);
//使能中断接收
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
//使能串口
USART_Cmd(USART1, ENABLE);
}
如果你想使用串口中断接受信息的话,千万别忘记写这一条命令!!! USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);