0
iOS와 함께 BLE을 개발 중입니다. LED 켜기/끄기에 BLE 서비스를 사용하고 있습니다. 데이터를 읽을 수는 있지만 데이터를 BLE 장치로 보낼 수 없습니다. BLE에 00을 보내면 LED가 꺼지고 01을 보내면 BLE 장치에 LED가 켜져 야합니다.신속한 LED 켜기/끄기를위한 BLE의 데이터 읽기 및 쓰기
다음은 제 코드입니다.
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if let characterArray = service.characteristics as [CBCharacteristic]! {
for cc in characterArray {
if(cc.uuid.uuidString == "FEE1") { //properties: read, write
//if you have another BLE module, you should print or look for the characteristic you need.
myCharacteristic = cc //saved it to send data in another function.
//writeValue()
peripheral.readValue(for: cc) //to read the value of the characteristic
}
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if (characteristic.uuid.uuidString == "FEE1") {
let readValue = characteristic.value
print(readValue as Any)
let value = (readValue! as NSData).bytes.bindMemory(to: Int.self, capacity: readValue!.count).pointee //used to read an Int value
print (value)
}
}
//if you want to send an string you can use this function.
func writeValue() {
if isMyPeripheralConected { //check if myPeripheral is connected to send data
let dataToSend: Data = "01".data(using: String.Encoding.utf8)!
print(dataToSend)
myBluetoothPeripheral.writeValue(dataToSend as Data, for: myCharacteristic, type: CBCharacteristicWriteType.withoutResponse) //Writing the data to the peripheral
} else {
print("Not connected")
}
}
어떻게하면됩니까?
당신은'Data' 사용 할 수있는 NSData로하지'<01>'(빠른 검사,'인쇄에 (dataToSend)'. 당신은'String'으로 변환 쓰기''<3031>을 보내는 UTF8이지만, 읽었을 때, 당신은'Int'로 변환 중입니다. 변환은'let offInt = 00 // or 01; let dataToSend = Data (bytes : & myInt, count : 1)' – Larme
정말 고마워요. 그것은 매력처럼 작동했습니다. 나는 var newValue 전에 이것을 시도했다 : Int = 00 let data = NSData (bytes : & newValue, length : MemoryLayout .size) 그러나 작동하지 않았다. –
user12346
저는 스위프트 전문가가 아니며 Objective-C를 더 많이 사용하지만'MemoryLayout .size'가 너무 큽니다. 데이터가 작아지기를 바란다. 그래서 실패했다. –
Larme