在发送字符串时,在字符串末尾加上一个分隔符,例如 “\n” 或 “\r”,以便 Swift 可以识别多个字符串。以下是如何在 Arduino 中使用 “\n” 进行字符串分隔的示例代码:
String message = "Hello World\n"; // 添加 \n 分隔符
BLECharacteristic txCharacteristic;
void setup() {
Serial.begin(9600);
BLE.begin();
BLE.setLocalName("Arduino");
BLE.setAdvertisedService(txService);
txCharacteristic = BLECharacteristic(UUID_TX, BLECharacteristic::PROPERTY_NOTIFY);
BLE.addService(txService);
BLE.advertise();
}
void loop() {
if (BLE.connected()) {
txCharacteristic.setValue(message.c_str());
txCharacteristic.notify();
delay(1000);
}
}
在 Swift 中,您需要实现 BLE 的委托方法 “peripheral(_:didUpdateValueFor: error:)”。在此方法中,您可以从收到的数据中分离出多个字符串,并对每个字符串进行处理。在以下示例代码中,我们将每个字符串输出到控制台:
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if let data = characteristic.value {
let message = String(data: data, encoding: .utf8)
let stringList = message?.components(separatedBy: "\n") // 以 \n 分隔符分离字符串
for string in stringList ?? [] {
print(string)
}
}
}
下一篇:bl和数据仓库的关系