蓝牙与Arduino的问题

0 投票
2 回答
1285 浏览
提问于 2025-04-18 02:32

我正在尝试通过蓝牙将信息从电脑发送到Arduino。我使用Python来处理蓝牙,使用的是pybluez库,操作系统是Windows。

import bluetooth

target_name = "HC-05"
target_address = None

nearby_devices = bluetooth.discover_devices()
print nearby_devices

for bdaddr in nearby_devices:
    print bluetooth.lookup_name( bdaddr )
        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
    sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )

    print "Trying connection"
    port = 3
    sock.connect((target_address, port))
    print "Trying sending"
    sock.send("1 2 3")
    print "Finished sending"
    sock.close()
else:
    print "could not find target bluetooth device nearby"

在Arduino那边,我运行着以下代码。

#include <stdlib.h>

//format [motor #][pwmA = 0, pwmB = 0]
const int MOTOR_PINS[5][2] = {{3,4}, {5,6}, {9, 10}, {23, 22}, {21, 20}};
const int SIGN = 1;
String msg = "";

void setup() {  
  Serial.begin(9600); //usb for testing
  Serial1.begin(9600);
}

void loop() {
  //check for inputs to bluetooth adapter
  while (Serial1.available()) {
   char reading = Serial1.read();
    if ((int)reading == 13 ) {
      Serial.println(msg);
      parseString(msg);
      msg = "";
    }
    else {
      msg += reading;
    }
  }
}

(我知道Python的端口是写死的,打算稍后再整理一下。)

总之,当我运行Python代码时,我能成功找到蓝牙设备。但是,当我尝试连接时,却出现了一个错误,提示 IOError: A socket operation failed because the destination host was down. 当我用PuTTY打开COM3时,可以成功向Arduino发送数据(parseString被调用了)。我不明白这两者之间有什么区别。

2 个回答

0

好的,感谢你提供的代码。通过稍微修改一下,我终于得到了我想要的结果。

我也遇到了同样的错误信息:IOError: A socket operation failed because the destination host was down. 所以我首先把我的HC-05蓝牙模块和电脑(Windows系统)配对,因为我的HC-05是有密码锁的。接着,我开始写一个循环,检查给定范围内的每一个端口。

虽然影响不大,但我建议把串口的波特率提高到115200,这样可能会更好用。

对我来说,Python代码看起来是这样的。

import bluetooth

#--Pair HC-05 with PC first

target_name = "BLUESAND"
target_address = None

nearby_devices = bluetooth.discover_devices()
print nearby_devices

for bdaddr in nearby_devices:
    print bluetooth.lookup_name( bdaddr )
    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
    sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )

    print "Trying connection"
    #######################################
    i=0 # ---- your port range starts here
    maxPort = 3 # ---- your port range ends here
    err = True
    while err == True and i <= maxPort:
        print "Checking Port ",i
        port = i
        try:
            sock.connect((target_address, port))
            err = False
        except Exception,e:
            ## print the exception if you like
            i += 1
    if i > maxPort:
        print "Port detection Failed."
        exit(0)
    #######################################
    print "Trying sending"
    sock.send("Challange")
    print "Finished sending"
    print sock.recv()
    print "Finished receiving"
    sock.close()
else:
    print "could not find target bluetooth device nearby"

而我的Arduino代码是这样的。

String str;

void setup() {
  Serial.begin(115200);     // opens serial port, sets data rate
}

void loop() {
  // send data only when you receive data:
  if (Serial.available() > 0) {
      str = Serial.readStringUntil('\n');

      // say what you got:
      Serial.print("I received: ");
      Serial.println("\""+str+"\"");
      //trim the string to skip the trailing CRLF
      str.trim(); 
  }
}
0

可能是COM3连接了蓝牙,所以你的Python程序无法连接?

另外,你可以使用pyserial来连接COM3。http://pyserial.sourceforge.net/shortintro.html

撰写回答