📜  关于HC-05蓝牙模块的所有信息|与Android连接

📅  最后修改于: 2021-08-27 05:26:13             🧑  作者: Mango

曾经想用Android手机控制机械机器人或设计带有自定义遥控器的机器人,因此在本教程中,我们将学习用于上述和许多其他情况的蓝牙模块HC-05。在这里,我们将了解HC-05模块的连接和工作方式,以及与自定义android应用程序的接口。
基本
在电子和通信方面,无线通信正在迅速取代有线连接。设计用于替换电缆连接HC-05使用串行通信与电子设备进行通信。通常,它用于通过短程无线连接来连接小型设备(如手机)以交换文件。它使用2.45GHz频带。数据的传输速率最高可达到1Mbps,范围为10米。
HC-05模块可以在电源的4-6V范围内运行。它支持9600、19200、38400、57600等的波特率。最重要的是,它可以在主从模式下运行,这意味着它既不会发送也不会接收来自外部源的数据。

HC-05模块

引脚说明


  • 使能-此引脚用于设置数据模式或AT命令模式(设置为高电平)。
  • VCC-连接到+ 5V电源。
  • 接地-已连接至电源系统的接地。
  • Tx(发送器)-该引脚串行发送接收到的数据。
  • Rx(接收器)-用于通过蓝牙串行广播数据。
  • 状态-用于检查蓝牙是否正常工作。

操作方式

HC-05蓝牙模块可用于两种操作模式:命令模式和数据模式。

命令模式

在命令模式下,您可以通过AT命令与蓝牙模块进行通信,以配置模块的各种设置和参数,例如获取固件信息,更改波特率,更改模块名称,可将其设置为主设备或从设备。

关于HC-05模块的一点是,它可以在通信对中配置为主设备或从设备。为了选择任何一种模式,您需要激活命令模式并发送适当的AT命令。

数据模式

进入数据模式,在此模式下,模块用于与其他蓝牙设备进行通信,即在此模式下进行数据传输。

用微控制器编程HC-05

代码的技术规格:

  • Arduino-Uno被用作微控制器。
  • 名称:HC-05
  • 密码:1234(或0000)
  • 类型:从属
  • 模式:数据
  • 波特率:9600,具有8个数据位,无奇偶校验和1个停止位
//Define the variable that contains the led
#define ledPin 7
int state = 0;
void setup() {
  //Setting the pin mode and initial LOW 
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  Serial.begin(9600); // Default communication rate
}
void loop() {
  // Checks if the data is coming from the serial port
  if(Serial.available() > 0){ 
    state = Serial.read(); // Read the data from the serial port
 }
 Deciding functions for LED on and off 
 if (state == '0') {
  digitalWrite(ledPin, LOW); // Turn LED OFF
  // Send back, to the phone, the String "LED: ON"
  Serial.println("LED: OFF"); 
  state = 0;
 }
 else if (state == '1') {
  digitalWrite(ledPin, HIGH);
  Serial.println("LED: ON");;
  state = 0;
 } 
}

与HC-05接口的Android应用

现在,我们将开发一个小型android应用程序,以演示蓝牙模块和android应用程序的连接。我们将为此目的使用Android Studio,并在微控制器上使用上述C代码。

Algorithm:
Create an empty project on Android Studio
Create a ListView containing all the available bluetooth devices. 
Get the name and MAC-address of HC-05 module.
Open connection with HC-05 module.
Instruct the module with data as bytes.

了解代码

1.在ListView中获取所有蓝牙设备

此代码用于MainActivity或第一个活动,将在该活动中显示列表,然后在选择设备后,Control活动将发出命令。

// Initializing the Adapter for bluetooth
private BluetoothAdapter BluetoothAdap = null;
private Set Devices;
// comes in Oncreate method of the activity
BluetoothAdap = BluetoothAdapter.getDefaultAdapter();
  
// Method to fill the listwith devices
private void pairedDevices()
{
    Devices = BluetoothAdap.getBondedDevices();
    ArrayList list = new ArrayList();
  
    if (Devices.size() > 0) {
        for (BluetoothDevice bt : Devices) {
            // Add all the available devices to the list
            list.add(bt.getName() + "\n" + bt.getAddress());
        }
    }
    else {
        // In case no device is found
        Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
    }
  
    // Adding the devices to the list with ArrayAdapter class
    final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
    devicelist.setAdapter(adapter);
  
    // Method called when the device from the list is clicked
    devicelist.setOnItemClickListener(myListListener);
}

2.获取设备的名称和MAC地址

现在,我们将为列表创建一个OnClick侦听器,以便可以从设备中提取名称和MAC地址。

// On click listener for the Listview
private AdapterView.OnItemClickListener myListListener = new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView av, View v, int arg2, long arg3)
    {
        // Get the device MAC address
        String name = ((TextView)v).getText().toString();
        String address = info.substring(info.length() - 17);
  
        // Make an intent to start next activity.
        Intent i = new Intent(MainActivity.this, Control.class);
        // Put the data got from device to the intent
        i.putExtra("add", address); // this will be received at control Activity
        startActivity(i);
    }
};

3,建立两者之间的联系

控件中的connect()函数。 Java将有助于在两者之间建立连接。

BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
// This UUID is unique and fix id for this device
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  
// receive the address of the bluetooth device
Intent intent = getIntent();
address = intent.getStringExtra("add");
  
try {
    if (btSocket == null || !isBtConnected) {
        myBluetooth = BluetoothAdapter.getDefaultAdapter();
  
        // This will connect the device with address as passed
        BluetoothDevice hc = myBluetooth.getRemoteDevice(address);
        btSocket = hc.createInsecureRfcommSocketToServiceRecord(myUUID);
        BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
  
        Now you will start the connection
            btSocket.connect();
    }
}
catch (IOException e) {
    e.printStackTrace();
}

4.最终命令HC-05模块

在这里,首先我们将检查套接字是否已连接,然后只有我们可以避免Null Pointer异常。

// Function for commanding the module
private void turnOffLed()
{
    if (btSocket != null) {
        try { // Converting the string to bytes for transferring
            btSocket.getOutputStream().write("0".toString().getBytes());
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

现在终于有了HC-05模块和Android编程,完成了我们的第一个基础项目,我们可以继续使用复杂的电子机器人,并使用此惊人的模块HC-05与无线进行有线连接,而且我们现在知道自定义应用。

您可以在此处提交的Android Studio Project形式中找到以上代码。