我正在通过Hm10将数据从滑块和按钮发送到Arduino,但问题是我的字符串被分成两部分读取,从倒数第二个特征分为新的行字符串。
func writeValue(data: String){
let valueString = (data as NSString).data(using: String.Encoding.utf8.rawValue)
print("data string is" , data)
//change the "data" to valueString
if let blePeripheral = blePeripheral{
if let txCharacteristic = txCharacteristic {
blePeripheral.writeValue(valueString!, for: txCharacteristic, type: CBCharacteristicWriteType.withResponse)
print(valueString!)
}
}
}
@IBAction func switchAction(_ sender: Any) {
if switchUI.isOn {
print("On ")
// writeCharacteristic(val: 1)
writeValue(data:"tp1z ")
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
print("characterstic value is" , characteristic.value!)
if characteristic == rxCharacteristic {
if let ASCIIstring = NSString(data: characteristic.value!, encoding: String.Encoding.utf8.rawValue) {
characteristicASCIIValue = ASCIIstring
print("Value Recieved: \((characteristicASCIIValue as String))")
NotificationCenter.default.post(name:NSNotification.Name(rawValue: "Notify"), object: nil)
}
}
}
func updateIncomingData () {
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "Notify"), object: nil , queue: nil){
notification in
let appendString = "\n"
let myFont = UIFont(name: "Helvetica Neue", size: 15.0)
let myAttributes2 = [NSAttributedStringKey.font: myFont!, NSAttributedStringKey.foregroundColor: UIColor.red]
let attribString = NSAttributedString(string: "[Incoming]: " + (characteristicASCIIValue as String) + appendString, attributes: myAttributes2)
let newAsciiText = NSMutableAttributedString(attributedString: self.consoleAsciiText!)
self.baseTextView.attributedText = NSAttributedString(string: characteristicASCIIValue as String , attributes: myAttributes2)
newAsciiText.append(attribString)
self.consoleAsciiText = newAsciiText
self.baseTextView.attributedText = self.consoleAsciiText
print("incoming")
}
}
我不明白为什么它会使我的字符串从倒数第二个字符开始中断。
答案 0 :(得分:0)
所以最后,我习惯于清空字符,因为它使我的字符串从倒数第二个字符中断开,如下所示:-
writeValue(data:"tp1z ")
对我有用。