我正在使用iOS开发BLE。
我正在使用BLE服务来打开/关闭LED。我能够读取数据,但是无法将数据发送到BLE设备。
当我向BLE发送00时,LED应该熄灭,而当我向01发送BLE时,LED应该打开。
这是我的代码段。
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")
}
}
我该怎么做?
最佳答案
迅捷3
var arrayReadWriteChar = [CBCharacteristic]()
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
for newChar: CBCharacteristic in service.characteristics!{
if newChar.uuid.uuidString == "FEE1"{
self.arrayReadWriteChar.append(newChar)
periphreal.readValue(for: newChar)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
print("didUpdateValueForChar", characteristic)
if let error1 = error{
print(error1)
}
else{
let value = [UInt8](characteristic.value!)
print(value) //whole array
print(value[0]) //array object of index 0
}
}
func writeValue(){
if isMyPeripheralConected {
let dataToSend: Data = "01".data(using: String.Encoding.utf8)!
print(dataToSend)
let command:[UInt8] = [0x01]
let sendData:Data = Data(command)
myBluetoothPeripheral.writeValue(sendData, for: self.arrayReadWriteChar[0], type: .withResponse)
}
else {
print("Not connected")
}
}
关于ios - 在BLE中读取和写入数据以快速打开/关闭LED,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47139946/