0

I getting a text input and writing it to a ble device. I don't have an issue for 1 Byte of data but I could not covert the text input value to 2 bytes and send it.

How can I convert a value like 3400 to 2 bytes of UInt8 array and what should I for values below 255?

For 1 byte I use:

let myInt = Int(textField.text)
let value: [UInt8] = [UInt8(myInt)]
self.bluetoothManager.writeValue(data: Data(bytes: value), forCharacteristic: myChar!, type: .withResponse)

I tried to convert like this but I can't send String with .writeValue:

https://stackoverflow.com/a/36967037/4704055

   let d1 = 21
   let b1 = String(d1, radix: 2) 
   print(b1) // "10101"
serdar aylanc
  • 1,197
  • 1
  • 16
  • 35

1 Answers1

0

You probably want to convert the string to a 16-bit integer, then convert the integer to data (compare round trip Swift number types to/from Data), and finally write the data to the device:

guard var value = Int16(textField.text) else {
    // ... invalid number ...
}
// value = value.bigEndian (if big-endian is expected by the device)
let data = Data(buffer: UnsafeBufferPointer(start: &value, count: 1))
self.bluetoothManager.writeValue(data: data, ...)
Martin R
  • 488,667
  • 78
  • 1,132
  • 1,248