可以使用Arduino Portenta H7板内置的蓝牙模块通过蓝牙连接到Windows系统。以下是一个简单的示例代码,演示了如何在Arduino Portenta H7板和Windows系统之间建立蓝牙连接并进行数据交换:
Arduino代码:
#include
BLEService dataService("19b10010-e8f2-537e-4f6c-d104768a1214");
BLEUnsignedCharCharacteristic dataChar("19b10011-e8f2-537e-4f6c-d104768a1214", BLERead | BLEWrite);
void setup() {
Serial.begin(9600);
if (!BLE.begin()) {
Serial.println("Failed to start Bluetooth");
while (1);
}
BLE.setLocalName("Arduino Portenta H7");
BLE.setAdvertisedService(dataService);
dataService.addCharacteristic(dataChar);
BLE.addService(dataService);
dataChar.writeValue(0);
BLE.advertise();
}
void loop() {
BLEDevice central = BLE.central();
if (central) {
Serial.print("Connected to central: ");
Serial.println(central.address());
while (1) {
if (dataChar.written()) {
Serial.println("Data received");
Serial.println(dataChar.value());
// Handle the received data here
dataChar.writeValue(0);
}
}
}
}
Windows代码:
import bluetooth
server_address = '00:00:00:00:00:00' # Replace with the MAC address of the Arduino Portenta H7 board
port = 1
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((server_address, port))
print('Connected to Arduino Portenta H7 board')
while True:
data = input('Enter data to send: ')
sock.send(data)
data = sock.recv(1024)
print('Received data: ', data)
sock.close()
在Windows系统上运行上述Python代码后,将提示输入要发送到Arduino Portenta H7板的数据。将任何数据输入到控制台中,然后按Enter键,数据将通过蓝牙发送到Arduino Portenta H7板。Arduino Portenta H7板将收到该数据并将其打印到串口监视器中。接下来,Arduino Portenta H7板将向Windows系统发送值0,并将其打印到Python控制台中。您可以在循环中添加代码来处理从Windows系统接