[英]Bluetooth Connection between Python and Arduino, PyBlueZ
我正在制作一个个人项目,可以通过蓝牙在 Python 和 Arduino 之间建立连接。 我需要 Python 代码来连接到 HC-05 蓝牙模块并向其发送字符。 我为 Arduino 编写的代码:
#include <SoftwareSerial.h>
SoftwareSerial bluetooth(10, 11);
void setup()
{
Serial.begin(9600);
bluetooth.begin(9600);
}
void loop()
{
if (bluetooth.available())
{
Serial.println(bluetooth.read());
}
}
到目前为止我为 Python 编写的代码:
import bluetooth
nearby_devices = bluetooth.discover_devices(lookup_names=True)
print("Found {} devices.".format(len(nearby_devices)))
for addr, name in nearby_devices:
print(" {} - {}".format(addr, name))
每次运行此代码时,都会出现此错误:
Traceback (most recent call last): File "C:\Users\peiji\OneDrive\Documentos\Arduino\Carro\main.py", line 1, in import bluetooth ModuleNotFoundError: No module named 'bluetooth'
我已经尝试过: pip install pybluez
但是,我收到此错误:
从 Python 版本 3.9 开始,通过使用套接字库的标准 Python 安装,可以使用串行端口配置文件 (SPP) 进行蓝牙连接。
HC-05 模块是服务器,所以你需要创建一个客户端。 这里有一个比较 pyBluez 和 Python sockets 的博客: http://blog.kevindoran.co/bluetooth-programming-with-python-33/
如果您更新地址和端口信息,Kevin 博客中的客户端示例应该会执行您想要的操作:
import socket
serverMACAddress = '00:1f:e1:dd:08:3d' # Put your HC-05 address here
port = 1 # Match the setting on the HC-05 module
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
s.connect((serverMACAddress,port))
print("Connected. Type something...")
while 1:
text = input()
if text == "quit":
break
s.send(bytes(text, 'UTF-8'))
s.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.