Raspberry Pi經過藍牙與Arduino鏈接

** 剛剛開始接觸若有錯誤請留言指正,多謝 **python

設備

  • Raspberry Pi第三代B+版本
  • Arduino Pro Mini(5V,16MHz)w/ ATmega328 + 寫入設備(或使用其餘Arduino版本)
  • 藍牙HC-06
  • 發光二極管1個
  • 10千歐電阻1個
  • 杜邦線若干

安裝過程當中所須要的包和工具

在 Python 環境下,使用「import bluetooth」若是報出錯誤信息「ImportError: No module named bluetooth」則說明沒有安裝相應的包,執行一下命令安裝。git

$ sudo apt-get update
$ sudo apt-get install bluetooth  bluez  python-bluez

鏈接藍牙設備(Arduino)

使用下面的命令查看藍牙的配置信息編程

$ hciconfig

使用下面的命令掃描可配對的設備工具

$ hcitool scan

進入$ bluetoothctloop

[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的藍牙設備ui

$ sudo rfcomm connect 0 00:14:01:10:10:32
Press CTRL-C for hangup

鏈接藍牙設備後,會在樹莓派的【/dev】目錄中建立一個藍牙設備的虛擬文件 /dev/rfcomm0 ,同時Arduino的藍牙指示燈爲常亮狀態,表示「已鏈接」。code

綁定Arduino的藍牙設備utf-8

$ sudo rfcomm bind 0 00:14:01:10:10:32

綁定藍牙設備後,也會在樹莓派的【/dev】目錄中建立 /dev/rfcomm0 文件,而此時Arduino的藍牙指示燈爲閃爍狀態,表示「未鏈接」;當樹莓派向藍牙設備發送消息時纔去作鏈接操做。ci

對已經綁定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

運行測試

如何測試就不發了

相關文章
相關標籤/搜索