0

如果我想将数据发送到连接到 Arduino 的蓝牙模块,我需要特别注意哪些代码行。

我想向蓝牙模块发送数字“75”之类的东西,Arduino 会读取它

谢谢

4

1 回答 1

3

蓝牙 LE 很长很麻烦,中间有很多代表。写入数据的最小路径是:

  1. 确保您具有蓝牙权限:CBCentralManagerDelegate.centralManagerDidUpdateState,如果是,则使用 scanForPeripherals 开始扫描
  2. CBCentralManagerDelegate.didDiscover 如果这是您想要的外围设备,则将自己设置为其委托
  3. CBPeripheralDelegate.peripheral:didDiscoverServices: 如果这是您想要的服务,则停止扫描并发现Characteristics:for: service
  4. CBPeripheralDelegate.peripheral:didDiscoverCharacteristicsFor: service 如果特征数组中的一个特征是您想要的,那么:

    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        guard let characteristics = service.characteristics else {
            return
        }
        for characteristic in characteristics {
            if characteristic.uuid == CBUUID(string: characteristicIdentifier) {
                let value: UInt8 = 75
                let data = Data(bytes: [value])
                peripheral.writeValue(data, for: characteristic, type: .withResponse)
            }
        }
    }
    
于 2017-02-02T00:01:12.600 回答