2016年11月21日 星期一

[RPi] Raspberry Pi藍牙程式(Python)

使用RFCOMM Socket連線
#!/usr/bin/python

import bluetooth
import thread
import time

server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
print "bluetooth.RFCOMM: " + str(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()

使用RFCOMM Serial連線
#!/usr/bin/python

import serial
import time
import thread

port = serial.Serial("/dev/rfcomm0", baudrate=38400, timeout=0.1)

def receive_thread():
    while True:
        try:
            recvS = port.readlines()
            for recv in recvS:
                print("\nAndroid] " + recv.replace("\n", ""))

        except serial.SerialException:
            print "SerialException: "
            port.close()

        time.sleep(0.1)

thread.start_new_thread(receive_thread, ())

while True:
    s = raw_input("RPi] ")
    port.write(s)

沒有留言: