iosswiftxcodebluetoothhm-10

sending data to bluetooth module to be read by arduino rom iOS swift 3


If i want to send data to a bluetooth module, which is connected to the Arduino, what code lines are specifically the ones I need to take notice of.

I want to send something like, the number '75' to the bluetooth module and the Arduino will read it

thanks


Solution

  • Bluetooth LE is very long and cumbersome with many delegates in between. The minimum path to write your data is:

    1. Make sure you have bluetooth permission: CBCentralManagerDelegate.centralManagerDidUpdateStateand if so start scanning with scanForPeripherals
    2. CBCentralManagerDelegate.didDiscover If this is the peripheral you want then set yourself as its delegate
    3. CBPeripheralDelegate.peripheral:didDiscoverServices: If this is the service you want then stop scanning and discoverCharacteristics:for: service
    4. CBPeripheralDelegate.peripheral:didDiscoverCharacteristicsFor: service If a characteristic in the array of characteristics is the one you want then:

      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)
              }
          }
      }