实验名:串口实验
实验说明:在串口助手上选择波特率为9600.选择HE发送和HEX显示,发送数据在串口的加1上进行显示,参考文末图片选择
main.c
*******************************************************************************/
#include "public.h"
#include "usart.h"
#include "systick.h"
/****************************************************************************
* Function Name : main
* Description : Main program.
* Input : None
* Output : None
* Return : None
****************************************************************************/
int main()
{
usart_init();//串口1初始化
while(1);
}
usart.c
#include "usart.h"
/*******************************************************************************
* 函 数 名 : usart_init
* 函数功能 : 串口初始化函数
* 输 入 : 无
* 输 出 : 无
*******************************************************************************/
void usart_init()
{
GPIO_InitTypeDef GPIO_InitStructure; //声明一个结构体变量,用来初始化GPIO
USART_InitTypeDef USART_InitStructure; //串口结构体定义
NVIC_InitTypeDef NVIC_InitStructure;//中断结构体定义
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE); //打开时钟
/* 配置GPIO的模式和IO口 */
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;//TX //串口输出PA9
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP; //复用推挽输出
GPIO_Init(GPIOA,&GPIO_InitStructure); /* 初始化串口输入IO */
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10;//RX //串口输入PA10
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING; //模拟输入
GPIO_Init(GPIOA,&GPIO_InitStructure); /* 初始化GPIO */
USART_InitStructure.USART_BaudRate=9600; //波特率设置为9600 //波特率
USART_InitStructure.USART_WordLength=USART_WordLength_8b; //数据长8位
USART_InitStructure.USART_StopBits=USART_StopBits_1; //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_Cmd(USART1, ENABLE); /* 使能USART1 */
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//使能或者失能指定的USART中断 接收中断
USART_ClearFlag(USART1,USART_FLAG_TC);//清除USARTx的待处理标志位
/* 设置NVIC参数 */
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; //打开USART1的全局中断
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //抢占优先级为0
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //响应优先级为0
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //使能
NVIC_Init(&NVIC_InitStructure);
}
stm32f10x_it.c
void USART1_IRQHandler(void) //串口1中断函数
{
static u8 k;
USART_ClearFlag(USART1,USART_FLAG_TC);
if(USART_GetITStatus(USART1,USART_IT_RXNE)!=Bit_RESET)//检查指定的USART中断发生与否
{
k=USART_ReceiveData(USART1);
k++;
USART_SendData(USART1,k);//通过外设USARTx发送单个数据
while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==Bit_RESET);
}
}
具体操作详情见PDF