通过蓝牙连接HC-05蓝牙模块与python时出错

时间:2016-03-20 04:46:39

标签: python sockets bluetooth communication rfcomm

我一直在尝试将我的hc 05 bt模块与笔记本电脑连接,并与Idle进行通信。

首先,我从笔记本电脑的蓝牙设置手动连接我的bt设备,然后我可以使用以下代码获取模块的bt address

import bluetooth

target_name = "HC-05"
target_address = None

nearby_devices = bluetooth.discover_devices()

for bdaddr in nearby_devices:
 if target_name == bluetooth.lookup_name( bdaddr ):
    target_address = bdaddr
    break

if target_address is not None:
  print "found target bluetooth device with address ", target_address
else:
  print "could not find target bluetooth device nearby"

我收到的蓝牙地址为"98:D3:31:70:7D:2D"

现在我编写了以下代码,通过python ..

连接HC-05
bd_addr = "98:D3:31:70:7D:2D"

port = 20
sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((bd_addr, port))
sock.send("1")

sock.close()

现在我浏览笔记本电脑的蓝牙通讯端口设置,发现了两件事 第一......

COM19 
Direction--- Incoming... 
Name--- HC-05

...第二

COM20
Direction--- Outgoing

...
Name--- HC-05 'Dev B'

因此我选择COM20因为我想从Python传输数据。

当我运行此代码时,我收到错误:

Traceback (most recent call last):
  File "C:\Python27\TestBluetooth.py", line 26, in <module>
    sock.connect((bd_addr, port))
  File "C:\Python27\lib\site-packages\bluetooth\msbt.py", line 72, in connect
    bt.connect (self._sockfd, addr, port)
IOError: A socket operation failed because the destination host was down.

我尝试了COM19COM20但得到了同样的错误。 我的蓝牙通过TX引脚连接到arduino's RX pin,而arduino已连接到我的电脑,因此有时不会发生COM port共享错误。

当我将蓝牙模块与笔记本电脑蓝牙连接并打开Bluetooth Serial terminal并从那里传输数据时,它工作正常。 所以我对Python代码的理解和编写存在一些问题。 请帮忙......

0 个答案:

没有答案
相关问题