基于基于STM32F103ZET6串口实验串口实验
文章最后是串口中断的总结及算法文章最后是串口中断的总结及算法
串口的重要性大家都知道!mcu外部的重要接口,也是软件调试的重要调试方式,不管是调试串口,还是通信串口,原理都是
一样,这次我们将使用串口1来接收pc发出的数据,再将数据发回给pc,我们使用的是正点原子板载usb串口。
接下来我们要进行哪些大概步骤:
1)使用gpio,gpio初始化(时钟使能)
2)使用串口,串口初始化(时钟使能,复位)
3)使用中断,中断初始化(开启使能)
4)中断函数编写(包括数据接收)
5)主函数实现数据发送给pc
先从简单的开始
定义串口的头文件定义串口的头文件usart.c
#ifndef USART_H
#define USART_H
#define len 64//接收数据的最大个数buff
#include “sys.h”//io口的操作头文件包含
extern u8 bufff[len];
extern u16 USART_RX_STA;//接收数据标志变量
extern void usart_init(u32 bound);//串口初始化
#endif
这个都没什么说的,重点是在源文件!
定义源文件定义源文件usart.c
#include “sys.h”
#include “usart.h”
u8 bufff[len];
u16 USART_RX_STA=0;
void usart_init(u32 bound)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_2;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
USART_InitStructure.USART_BaudRate=bound;
USART_InitStructure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode=USART_Mode_Rx|USART_Mode_Tx;
USART_InitStructure.USART_Parity=USART_Parity_No;
USART_InitStructure.USART_StopBits=USART_StopBits_1;
USART_InitStructure.USART_WordLength=USART_WordLength_8b;
USART_Init(USART1,&USART_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel=USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3;
NVIC_InitStructure.NVIC_IRQChannelSubPriority=3;
NVIC_Init(&NVIC_InitStructure);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
评论0