STM32-Keil5固件库——串口通讯(以蓝牙透传为例)
(注意:源文件下载请查看文末链接。)
一、串口通讯基本知识
串口通讯基本知识网上资料非常多,小编不再过多赘述,详细请查看STM32 通信基本知识 串口通信(USART)。
二、器件
****本例中依旧使用单片机STM32F405,蓝牙传输使用**逐飞蓝牙透传模块。**当然使用HC-05也可以。
由于在很多STM32项目中使用蓝牙串口一般用于调试,所以使用透传最为常见,当然,使用蓝牙向手机传输数据也很常见,但蓝牙传输受到距离限制,远距离传输数据更适合使用WIFI。
三、主要代码
这里设置了两个串口,我们只使用到一个,即Usart1。连接时,RX-PA9,TX-PA10.
usart.c文件:
/**
************************************************************
************************************************************
************************************************************
* 文件名: usart.c
*
* 作者: 北辰远_code
*
* 日期: 2024.5.4
*
* 版本: V1.0
*
* 说明: 单片机串口外设初始化,格式化打印
*
* 修改记录:
************************************************************
************************************************************
************************************************************
**/
//硬件驱动
#include "usart.h"
#include "delay.h"
//C库
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
/*
************************************************************
* 函数名称: Usart1_Init
*
* 函数功能: 串口1初始化
*
* 入口参数: baud:设定的波特率
*
* 返回参数: 无
*
* 说明: TX-PA9 RX-PA10
************************************************************
*/
void Usart1_Init(unsigned int baud)
{
GPIO_InitTypeDef gpio_initstruct;
USART_InitTypeDef usart_initstruct;
NVIC_InitTypeDef nvic_initstruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
//PA9 TXD
gpio_initstruct.GPIO_Mode = GPIO_Mode_AF_PP;
gpio_initstruct.GPIO_Pin = GPIO_Pin_9;
gpio_initstruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &gpio_initstruct);
//PA10 RXD
gpio_initstruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;
gpio_initstruct.GPIO_Pin = GPIO_Pin_10;
gpio_initstruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &gpio_initstruct);
usart_initstruct.USART_BaudRate = baud;
usart_initstruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None; //无硬件流控
usart_initstruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //接收和发送
usart_initstruct.USART_Parity = USART_Parity_No