** 剛剛開始接觸如有錯誤請留言指正,多謝 **
設備
- Raspberry Pi第三代B+版本
- Arduino Pro Mini(5V,16MHz)w/ ATmega328 + 寫入設備(或使用其他Arduino版本)
- 藍牙HC-06
- 發光二極管1個
- 10千歐電阻1個
- 杜邦線若干
安裝過程中所需要的包和工具
在 Python 環境下,使用“import bluetooth”如果報出錯誤信息“ImportError: No module named bluetooth”則說明沒有安裝相應的包,執行一下命令安裝。
$ sudo apt-get update
$ sudo apt-get install bluetooth bluez python-bluez
連接藍牙設備(Arduino)
使用下面的命令查看藍牙的配置信息
$ hciconfig
使用下面的命令掃描可配對的設備
$ hcitool scan
進入$ bluetoothctl
[NEW] Controller B8:27:EB:D3:61:B0 raspberrypi [default]
[bluetooth]# agent on
Agent registered
[bluetooth]# default-agent
Default agent request successful
//掃描可配對的設備
[bluetooth]# scan on
Discovery started
[CHG] Controller B8:27:EB:D3:61:B0 Discovering: yes
[NEW] Device 00:14:01:10:10:32 HC-06
//連接設備
[bluetooth]# pair 00:14:01:10:10:32
Attempting to pair with 00:14:01:10:10:32
[CHG] Device 00:14:01:10:10:32 Connected: yes
Request PIN code
[agent] Enter PIN code: 1234
[CHG] Device 00:14:01:10:10:32 UUIDs:
00001101-0000-1000-8000-00805f9b34fb
[CHG] Device 00:14:01:10:10:32 Paired: yes
Pairing successful
//查看已連接的設備
[bluetooth]# paired-devices
Device 00:14:01:10:10:32 HC-06
//刪除已經配對的設備
[bluetooth]# remove 00:14:01:10:10:32
[DEL] Device 00:14:01:10:10:32 HC-06
Device has been removed
測試是否能夠ping通
$ sudo l2ping 00:14:01:10:10:32
連接Arduino的藍牙設備
$ sudo rfcomm connect 0 00:14:01:10:10:32
Press CTRL-C for hangup
連接藍牙設備后,會在樹莓派的【/dev】目錄中創建一個藍牙設備的虛擬文件 /dev/rfcomm0 ,同時Arduino的藍牙指示燈為常亮狀態,表示“已連接”。
綁定Arduino的藍牙設備
$ sudo rfcomm bind 0 00:14:01:10:10:32
綁定藍牙設備后,也會在樹莓派的【/dev】目錄中創建 /dev/rfcomm0 文件,而此時Arduino的藍牙指示燈為閃爍狀態,表示“未連接”;當樹莓派向藍牙設備發送消息時才去做連接操作。
對已經綁定Arduino的藍牙設備解除綁定
$ sudo rfcomm bind 0 00:14:01:10:10:32
解除綁定藍牙設備后,文件 /dev/rfcomm0 消失了。
編程程序
- Arduino:
void setup()
{
pinMode(11, OUTPUT);
digitalWrite(11, HIGH);
delay(500);
digitalWrite(11, LOW);
Serial.begin(9600);
}
void loop() {
while (Serial.available())
{
char c = Serial.read();
digitalWrite(11, HIGH);
delay(500);
digitalWrite(11, LOW); //收到消息指示燈(LED)閃一下
if (c == 'A')
{
Serial.println("B"); //收到A就返回B
} else {
Serial.println("Please input [A]"); //都是其他字符返回
}
}
}
- python代碼:
#coding=utf-8
#send to arduino
import serial
import sys
port = "/dev/rfcomm0"
serial = serial.Serial(port,9600)
if len(sys.argv) > 1:
sendStr = sys.argv[1]
else:
sendStr = "A"
serial.write(sendStr)
serial.flushInput()
if serial.isOpen() == False:
serial.open()
line = serial.readline()
print line
運行測試
如何測試就不發了