Connect Arduino Uno via Android Bluetooth

[Arduino端]

需要東西:

  • Arduino Uno
  • hc06 (藍芽模組,可自己挑一種自己需要)

Arduino只需要與藍芽模組對接即可:

  • VCC -> 5v
  • GND -> GND
  • TXD -> 8 (依照code setting)
  • RXC -> 9 (依照code setting)
載入需要函式庫
1
#include <SoftwareSerial.h>
定義連接藍牙模組的序列埠
1
SoftwareSerial BT(8, 9); // 接收腳, 傳送腳
配置監控視窗和藍芽模組鮑率
1
2
3
4
5
6
7
8
9
10
11
char val;  // 儲存接收資料的變數

void setup() {
Serial.begin(9600); // 與電腦序列埠連線
Serial.println("BT is ready!");

// 設定藍牙模組的連線速率
// 如果是HC-05,請改成38400
// HC-06 預設是9600
BT.begin(9600);
}
將監控視窗輸入的資料藍芽模組,並且列印至監控視窗
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void loop() {
// 若收到「序列埠監控視窗」的資料,則送到藍牙模組
if (Serial.available()) {
val = Serial.read();
BT.print(val);
}

// 若收到藍牙模組的資料,則送到「序列埠監控視窗」
if (BT.available()) {
val = BT.read();
// 此行為了測試android發送資料,回傳相同資訊回去
BT.write(val);
Serial.print(val);
}
}

HC-06的命令設定

監控視窗向藍芽模組下指令

  • AT : 測試,回應「OK」
  • AT+VERSION: 回應韌體版本。
  • AT+NAME: 設定名稱,中間不得有空白。(ex:AT+NAME123, 名稱設為123)
  • AT+PIN: 設定連線密碼。(ex:AT+PIN1234, 密把設為1234)
  • AT+BAUD: 設定鮑率。(ex:AT+BAUD4, 設為9600bps)
鮑率數值如下:
1
2
3
4
5
6
7
8
1 set to 1200bps
2 set to 2400bps
3 set to 4800bps
4 set to 9600bps (Default)
5 set to 19200bps
6 set to 38400bps
7 set to 57600bps
8 set to 115200bps

[Android端]

android部分只需要先開藍芽匹配好arduino端的藍芽,接著就可開啟自己寫的code,去發送資訊。

取得藍芽裝置, 如果無法找到藍芽裝置,將會回傳空值
1
BluetoothAdapter myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
取得arduino的device
1
2
// arduino的mac address
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
連接arduino端的藍芽
1
2
3
// MY_UUID 可自訂一組
BluetoothSocketBluetoothSocket btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
寫入訊息到arduino端
1
2
3
4
String message = "Hello world";
byte[] msgBuffer = message.getBytes();
outStream = btSocket.getOutputStream();
outStream.write(msgBuffer);
接收來至於arduino端的訊息
1
2
3
4
5
6
7
inStream = btSocket.getInputStream();
int bytesAvailable = inStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
inStream.read(packetBytes);
}
在Activity class中找尋device
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// 探索到的device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 取得一個藍芽device
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 顯示device的名稱和mac address
Log.d(device.getName() + "\n" + device.getAddress());
}
}
};

public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// 取消藍芽探索
myBluetoothAdapter.cancelDiscovery();
}
else {
// 開始探索藍芽裝置
myBluetoothAdapter.startDiscovery();
// 向activity註冊一個接收者
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}