[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!"); 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(); BT.write(val); Serial.print(val); } }
|
- 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
| BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
|
連接arduino端的藍芽
1 2 3
| 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(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Log.d(device.getName() + "\n" + device.getAddress()); } } }; public void find(View view) { if (myBluetoothAdapter.isDiscovering()) { myBluetoothAdapter.cancelDiscovery(); } else { myBluetoothAdapter.startDiscovery(); registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); } }
|