2016年11月6日 星期日

[RPi] 藍牙通訊

硬體:Pi 3
軟體:2016-05

Android 手機安裝 BlueTerm, 原始碼

修改 /etc/systemd/system/dbus-org.bluez.service, 將
ExecStart=/usr/lib/bluetooth/bluetoothd
改為
ExecStart=/usr/lib/bluetooth/bluetoothd --compat
重新載入設定檔
$ sudo systemctl daemon-reload


Pi 3 藍牙設定
$ sudo bluetoothctl
[bluetoothctl] power on
[bluetoothctl] scan on
[bluetoothctl] agent on
[bluetoothctl] pair MAC_ADDRESS
[bluetoothctl] trust MAC_ADDRESS
[bluetoothctl] exit
sudo rfcomm bind 0 MAC_ADDRESS


Pi 3 程式碼:
#!/usr/bin/python

import bluetooth
import thread
import time

server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )

port = 1 
server_sock.bind(("",port))
server_sock.listen(1)

client_sock,address = server_sock.accept()
print "Accepted connection from ", address

def receive_thread():
    while True:
        try:
            data = client_sock.recv(1024)
            print "received [%s]" % data

        except:
            print "SerialException: "

        time.sleep(0.1)

thread.start_new_thread(receive_thread, ()) 

while True:
    s = raw_input("RPi] ")
    client_sock.send(s)

client_sock.close()
server_sock.close()

reference:
* An Introduction to Bluetooth Programming
* Using smart phone (Android) to control LED on Raspberry Pi 3 through Bluetooth connection


如果透過 App Inventor 寫 Android 端程式, 可以參考這篇文章
http://howtomechatronics.com/tutorials/arduino/how-to-build-custom-android-app-for-your-arduino-project-using-mit-app-inventor/

目前還沒搞定, 之後會再打通這邊...
列出有用到的 PORT
import serial.tools.list_ports

ports = list(serial.tools.list_ports.comports())
for p in ports:
    print p

沒有留言: