HC-05 Bluetooth module -------- mobile phone and STM32 communication (code writing) (host computer configuration) nanny level tutorial


⏩ Hello everyone! I'm Xiaoguang, an embedded enthusiast, a junior who wants to become a system architect.
⏩Because in the past, whether it was an electric race or a project, the Bluetooth module was used, such as: the communication between the mobile phone and the stm32, the two-vehicle communication in the electric race, or the wireless communication between the stm32 and the stm32 of the remote sensing car, etc. ⏩This article is
about The communication between HC-05 Bluetooth module and mobile phone is a detailed tutorial.
⏩Thank you for reading, please correct me if I am wrong.
HC-05 Bluetooth module routine
Link: https://pan.baidu.com/s/1-dNXPluImjaH1PcfHfpMyA?pwd=6666
Extraction code: 6666



1. Bluetooth module principle

1. The working principle of the Bluetooth module

Bluetooth devices use radio waves to connect phones and computers. A Bluetooth product consists of a small Bluetooth module along with a Bluetooth radio and software to support the connection. When two Bluetooth devices want to communicate with each other, they need to be paired. Communication between Bluetooth devices takes place over short-range, ad-hoc networks known as piconets, which are networks of devices connected using Bluetooth technology. This type of network can accommodate two to eight devices connected. When the network environment is created successfully, one device acts as the master device and all other devices act as slave devices. Intang Zhongchuang dynamically and automatically establishes when the Bluetooth device joins and leaves the radio short-range sensor.

2. The transmission method of the Bluetooth module

With the continuous development of Bluetooth technology in recent years, the transmission rate of Bluetooth has been continuously improved while the power consumption is continuously reduced, which makes the application range of Bluetooth more extensive. But if you want to design a complete bluetooth system, you must fully master the relevant technical knowledge of bluetooth, such as: radio frequency design, protocol stack, system integration and bluetooth module selection and other aspects of expertise.
The Bluetooth module can transmit data through the serial port (SPI, IIC) and the MCU control device. The Bluetooth module can be used as a host and a slave. The master is able to search for other Bluetooth modules and actively establish a connection, but the slave cannot actively establish a connection and can only wait for others to connect itself.

3. Types of Bluetooth modules

1. Introduction to HC-05 Bluetooth module
The HC-05 Bluetooth serial communication module (hereinafter referred to as the module) has two working modes: command response working mode and automatic connection working mode. In the automatic connecting working mode, the module can be divided into master (Master ), slave (Slave) and loopback (Loopback) three job roles.
When the module is in the automatic connection working mode, it will automatically transmit data according to the pre-set method; when the module is in the command response working mode, it can execute all the following AT commands, and the user can send various AT commands to the module to set up the module. Set control parameters or issue control commands. By controlling the input level of the external pin (PIO11) of the module, the switch between the two working modes of the module can be realized.
2. The HC-06 slave Bluetooth module
can only be used as a slave.
Others include low-power BLE Bluetooth 4.0 modules (cc2540 or cc2541), JDY-10 Bluetooth 4.0 BLE modules, etc. Here we use HC-05 Bluetooth module as an example.

2. Communication between mobile phone and STM32

1. Bluetooth module configuration

Configuration steps:
(1) Press and hold the en button on the Bluetooth module to connect to the computer through the USB to TTL module:
if the module flashes at two-second intervals, it means the connection is successful and enter the AT command mode
Note: If there is no button, connect the en pin to high, and then connect to the computer through USB to TTL
(2) Open XCOM (serial port debugging assistant), select the connected serial port, configure the baud rate to 38400, and open the serial port:
insert image description here
Note: If the serial port cannot be found, please check whether the CH340 driver is installed.
(3) Command configuration:
Input: AT+ORGL\\Restore the default state
Return: OK
Input: AT
Return: OK
Input: AT+NAME=xiaoguang\\Set the Bluetooth device name
Return: OK
Input: AT+PSWD=1234\\Set the Bluetooth device password
Return: OK
Input: AT+UART=9600,0,0\\Set the serial wave Baud rate 115200, no stop bit, no parity bit
Return: OK
Input: AT+CMODE=1\\Any bluetooth address connection
Return: OK
Note: If AT+NAME?OK is not returned except for the command, please check whether the Bluetooth module enters the command response mode
(4) The Bluetooth module is powered on again, and the indicator light flashes quickly. Turn on the Bluetooth debugger on our mobile phone to connect to our Bluetooth module. After connection, the Bluetooth module flashes twice at intervals of two seconds:
Please add a picture description
If you can't find the name, you can AT+ADDR?check the address and connect according to the instructions
Going here shows that our bluetooth module can already be connected with the mobile phone.

2. Code writing

The communication protocol we configure is:
packet header (0xA5) + data + parity + end of packet (0x5A).
In our example, the data to be received is an int integer and a char type, a total of 5 bytes, so a whole The packet is 8 bytes

Serial port initialization and interrupt service function configuration

/*bsp_usart.h*/
#ifndef __BSP_USART_H
#define __BSP_USART_H
#include "stm32f10x.h"
#include <stdio.h>

#define REC_BUF_SIZE 8    //接收数据包的大小

#define DEBUG_USARTx                     USART2   //蓝牙所用串口2
#define DEBUG_USART_CLK                  RCC_APB1Periph_USART2  //串口时钟
#define DEBUG_USART_APBxClkCmd           RCC_APB1PeriphClockCmd //串口时钟使能
#define DEBUG_USART_BAUDRATE             9600 //波特率设置·

#define DEBUG_USART_GPIO_CLK             RCC_APB2Periph_GPIOA   

#define DEBUG_USART_GPIO_APBxClkCmd       RCC_APB2PeriphClockCmd  //端口时钟

#define DEBUG_USART_TX_GPIO_PORT         GPIOA              //端口宏定义
#define DEBUG_USART_TX_GPIO_PIN          GPIO_Pin_2
#define DEBUG_USART_RX_GPIO_PORT         GPIOA
#define DEBUG_USART_RX_GPIO_PIN          GPIO_Pin_3

#define DEBUG_USART_IRQ                  USART2_IRQn
#define DEBUG_USART_IRQHandler           USART2_IRQHandler   //中断服务函数

static void NVIC_Config(void);
void USART_Config(void);
void Usart_SendByte(USART_TypeDef*pUSARTx,uint8_t data);

#endif 
/*bsp_usart.c*/
__IO uint8_t usart_value=0;//接收一个字节数据的变量
uint8_t len=0;             //接收数据的数组当前下标   
uint8_t num[20];           //存放接收一次数据包的数组
uint8_t Flag=0;  		   //接收到数据之后Flag=1
static uint8_t f = 0;      //从0xA5开始接收0x5A结束
// 中断服务函数
void DEBUG_USART_IRQHandler(void){
    
    
	if(USART_GetITStatus(DEBUG_USARTx,USART_IT_RXNE)){
    
      //接收中断标志位变化
		usart_value=USART_ReceiveData(DEBUG_USARTx);    //接收一个字节的数据
		if(usart_value == 0xA5)                         //从0xA5开始
		{
    
    
			f = 1;
		}
		if(f == 1)                                      //0xA5之后的数据存放到num[]数组
		{
    
    
			num[len]=usart_value;
			len++;
		}
		
	}
	if(len==REC_BUF_SIZE && usart_value == 0x5A){
    
           //接收到包尾,结束本次接收
		Flag=1;
		len=0;
		f = 0;
	}
	else if(len > REC_BUF_SIZE){
    
                            //如果长度大于数据包的长度,也结束本次接收
		f = 0;
		len = 0;
	}
 	USART_ClearFlag(DEBUG_USARTx,USART_IT_RXNE);        //清除中断标志位
}

If you don't understand, you can read the comments

receive packet code

 /*function.h*/
#ifndef __FUNCTION_H
#define __FUNCTION_H
	
#include "stm32f10x.h"
#include "bsp_usart.h"
#include "function.h"

typedef struct {
    
    
	int  num;
	char c;
}INPUT;

INPUT DATARecv();//接收上位机数据
void BL_Send(USART_TypeDef*pUSARTx,u8 send_ok);//发送数据给上位机

#endif 
#include "function.h"
#include "bsp_usart.h"
#include "math.h"
#include "stm32f10x_it.h" 

extern uint8_t Flag;//数据包是否发送
extern uint8_t num[20];//存储上位机发出的数据包


/**************************************************************************
函数名:DATARecv

作用:  将中断接收的数据包导出到我们的INPUT结构体,结构体和DATARccv可根据实际情况进行更改

返回值:INPUT类型的结构体

使用:BL_Send(DEBUG_USARTx,mode,quan)
***************************************************************************/
INPUT DATARecv(){
    
    
	int a=0;
	uint8_t i;
	INPUT structure;
  
	//接收一个char类型的数据
	structure.c=num[1];
	//接收一个int整形数据
	for(i=2;i<=6;i++){
    
     
		a+=num[i]<<((i-2)*8);
	}
	structure.num=a;
	a = 0;
	Flag=0;    //接收完成
	return structure;
}
/**************************************************************************
函数名:BL_Send

作用:  上位机数据显示,板子发送上位机,根据要发送的数据字节,在调试器上设置接收数据包
				参数1代表串口,后面代表发送的数据,可根据实际情况进行更改

参数:(串口类型,要发送的参数1,参数2,参数3)可修改个数,同时也要修改发送的字节就是下面注释掉的部分

使用:BL_Send(DEBUG_USARTx,mode,quan)
***************************************************************************/
void BL_Send(USART_TypeDef*pUSARTx,u8 send_ok){
    
    
	
	u8 t;
	u8 sum=0;//校验位--数据字节之和的低八位
	u8 i;
	Usart_SendByte(pUSARTx,0xA5);//头
	///发送模式
    Usart_SendByte(pUSARTx,send_ok);
	sum+=send_ok;//校验位就是把数据的每一个字节相加,很重要,不然手机无法接收数据
	Usart_SendByte(pUSARTx,sum);//校验位
	Usart_SendByte(pUSARTx,0x5A);//尾
}

Send integer code:

	t=(mode>>0)&0x00FF;
	sum+=t;
	Usart_SendByte(pUSARTx,t);
	t=(mode>>8)&0x00FF;
	sum+=t;
	Usart_SendByte(pUSARTx,t);
	t=(mode>>16)&0x00FF;
	sum+=t;
	Usart_SendByte(pUSARTx,t);
	t=(mode>>24)&0x00FF;
	sum+=t;
	Usart_SendByte(pUSARTx,t);

Host computer data package configuration

(1) Host computer sends data packet settings
Packet header (1) + c (1) + num (4) + check digit (1) + packet tail (1) = 8 bytes

Please add a picture description
(2) Host computer receiving data packet setting:
packet header (1) + ok (1) + parity digit (1) + packet tail (1) = 4 bytes
Please add a picture description
(3) Data packet structure setting
Please add a picture description
(4) Editing host computer graphics interface:
send:
num: editable text
c: switch
receive:
ok: text
Please add a picture description

3. Debugging results

1. Sample code of the main function:

#include "sys.h"
#include "delay.h"
#include "usart.h"
#include "led.h"

#include "function.h"

extern uint8_t Flag;  //数据包是否发送
INPUT Rec;			      //从车回馈信息 


 int main(void)
 {
    
    	
	delay_init();	    //延时函数初始化	  
	LED_Init();		  	//初始化与LED连接的硬件接口
	USART_Config();   //串口二初始化,若想更改 请在 bsp_usart.h 头文件更改配置

	while(1)
	{
    
    
		if(Flag == 1)   //接收到数据
		{
    
    
			Rec = DATARecv(); //将数据包的数据赋值到结构体中
			if(Rec.c == 0)    //如果接收到0,灭灯
				LED0 = 1;
			else 			  //其他情况开灯	
				LED0 = 0;
			BL_Send(USART2,Rec.num);//将接收的num发送回去
		}
	}
 }

 

2. Results:
You can see that the light was off at the beginning, we sent data 100, and returned data 100
Please add a picture description

Please add a picture description
We turn on the switch c, and change the num data, the small light is on, and the data change is returned:
Please add a picture description

Please add a picture description

Four. Summary

Problem Summary

1. The Bluetooth module cannot enter the AT command mode?
The bluetooth module is broken, just replace it with another one.
2. You can enter the AT command mode, but sending commands will not return OK?
The bluetooth module is broken, please replace it directly
3. The mobile phone cannot connect with the bluetooth module, or can’t find the bluetooth module with the set name?
Solution: Power on again.
Check the address of the Bluetooth module through AT+ADDR?, and find the corresponding address to connect.
4. Can’t receive the data sent by the upper computer of the mobile phone?
Check the receiving code to see if it is configured by the method I taught.
5. The mobile phone host computer cannot receive data?
Check whether the format of the data packet is correct and whether the check digit is calculated correctly
6. The received data is disordered?
It must be like the interrupt receiving function above, start receiving from the beginning of the packet and end at the end of the packet, so that the data will not be misplaced.
Note: If you still have unresolved problems, you can put them in the comment area or private message me.

Summarize

In fact, the communication between STM32 and STM32 is the same method, which is to write another copy of the above code and change the data packet reception.
The upper computer uses a bluetooth debugger, and the code is changed by myself, if necessary, you can private message me.
HC-05 Bluetooth module routine
Link: https://pan.baidu.com/s/1-dNXPluImjaH1PcfHfpMyA?pwd=6666
Extraction code: 6666

Guess you like

Origin blog.csdn.net/qq_52608074/article/details/127970509