一、蓝牙模块配置
蓝牙模块的配置要根据商家提供的资料来配置,首先打开串口工具,这里我用XCOM,市面上卖的蓝牙模块一般都是这样的,其实蓝牙通信的本质还是串口通信,所以我们如果和单片机使用,就要RX----TX、TX----RX这样交替连接
首先是蓝牙方面的配置,用串口发送指令,一般的蓝牙模块都有下面这几个指令:
发送指令要带一个新行
输入 | 输出 | 说明 |
AT | +OK | 正常连接 |
AT+NAME | +NAME=JDY-31-SPP | 蓝牙模块的名字 |
AT+RESET | 软复位 | |
AT+DISC | 断开连接 |
还有一些配置波特率、密码、取地址的指令,用法跟上面这些一样,但是不同的商家给的指令可能不一样,这里就不列举了,可以去找商家要资料
然后上电测试一下,可以找到Climb,并且可以连接,这样蓝牙模块就没有问题
二、软件配置
蓝牙模块本质上还是串口通信,所以我们要配置一个串口,这里用TX:PA9、RX:PA10
跟蓝牙模块连接好后,开始写代码
先是uart.c文件
void Usart_Init(u32 bound){
//GPIO端口设置
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE); //使能USART1,GPIOA时钟
//USART1_TX GPIOA.9
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //PA.9
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化GPIOA.9
//USART1_RX GPIOA.10初始化
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;//PA10
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//浮空输入
GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化GPIOA.10
//Usart1 NVIC 配置
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3;//抢占优先级3
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //子优先级3
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能
NVIC_Init(&NVIC_InitStructure); //根据指定的参数初始化VIC寄存器
//USART 初始化设置
USART_InitStructure.USART_BaudRate = bound;
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);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
USART_Cmd(USART1, ENABLE); //使能串口1
}
void USART1_IRQHandler(void) //串口1中断服务程序
{
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) //接收中断
{
//中断程序
}
}
usart.h
#ifndef __USART_H
#define __USART_H
#include "stdio.h"
#include "sys.h"
void Usart_Init(u32 bound);
#endif
main.c
#include "stm32f10x.h" // Device header
#include "usart.h"
int main(void)
{
SystemInit();
Usart_Init(9600); //一般蓝牙模块默认9600波特率
USART_SendData(USART1,'5'); //发送一个字节
while(USART_GetFlagStatus(USART1,USART_FLAG_TC) == RESET);
while(1) {
}
}
测试成功