一、HC05引脚插线
STATE:状态指示引脚,未连接时输出低电平,连接时输出高电平(不接)
RXD:UART接收引脚,接在软件串口的TX引脚上(这里插Arduino的7号引脚)
TXD:UART发送引脚,接在软件串口的RX引脚上(这里插Arduino的8号引脚)
GND:接地
VCC:电源
EN:使能引脚(不接)
二、HC05命令设置
1、AT命令设置程序
将HC05模块按提示插线到Arduino主控板上,上传下面的程序便可以开始进行HC-05蓝牙模块的命令设置了
#include <SoftwareSerial.h>
int led = A0;
SoftwareSerial mainBl(8,7);
char val;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);//Arduino串口通讯频率
//系统启动提示
Serial.println("Enter HC05-AT commands:");
mainBl.begin(38400);//hc05指令模式默认通讯频率
}
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available()) {
//HC05接收串口发送的数据
val = Serial.read();
mainBl.print(val);
}
if(mainBl.available()) {
//串口打印模块接受的数据
val = mainBl.read();
Serial.print(val);
}
}
2、设置命令
(1)进入AT命令模式
上传程序结束后断电,此时按下HC-05模块上的按键同时进行通电,待模块显示灯进入两秒一闪的状态便可以进行命令设置了。
(2)从机命令
//恢复出场设置
AT+ORGL
//设置连接密码,主从机密码一致才可进行连接
AT+PSWD="0000"
//设置从机模式
AT+ROLE=0
//查询从机地址,将地址数据中的冒号换成逗号便可以对主机绑定指定从机地址进行连接了
AT+ADDR?
//设置主机通信波特率115200
AT+UART=115200,0,0
(3)主机命令
//恢复出场设置
AT+ORGL
//设置连接密码,主从机密码一致才可进行连接
AT+PSWD="0000"
//设置主机模式
AT+ROLE=1
//绑定从机地址
AT+BIND=从机地址
//设置连接模式为指定地址连接模式,模式编码为0
AT+CMODE=0
//设置主机通信波特率115200
AT+UART=115200,0,0
三、通信程序
主从机蓝牙模块通信及串口通信统一采用115200的波特率。
1、主机通信程序
#include <SoftwareSerial.h>
SoftwareSerial mainBl(8,7);
char val;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Enter HC05-AT commands:");
mainBl.begin(115200);//hc05默认通讯频率
}
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available()) {
//接收串口发送的数据
val = Serial.read();
//讲数据发送给从机
mainBl.print(val);
}
}
2、从机通信程序
#include <SoftwareSerial.h>
SoftwareSerial congBT(8,7);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("CongHC-05 is opened:");
congBT.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
if(congBT.available()){
//接收主机发送的数据
char val = congBT.read();
//讲主机发送的数据打印出来
Serial.print(val);
}
}
四、假设——等待尝试
既然主机绑定从机后可以向从机发送数据,假设使从机绑定主机应该也可以向主机发送数据。这样两个元件应该互为主机,从机模式应该变为AT+ROLE=1或者其他模式。