swiftarduino

Insert Newline and Carriage-Return into Swift String


I'm writing a macOS app that interacts with an Arduino UNO via serial connection. It currently has no problem reading strings from the UNO but I can't manage to send it the proper Newline and Carriage-Return characters on outgoing strings.

The code responsible for sending the string is as follows:

@IBAction func SendCommand(sender: AnyObject) {
    let data = self.sendTextField.stringValue.dataUsingEncoding(NSUTF8StringEncoding)
    self.serialPort?.sendData(data)
}

For the moment I am attempting to manually insert '\r\n' at the end of messages when the program is running. Should this not be equivalent to what the Arduino IDE would do programatically in its own serial monitor? However, my app isn't interpreting these commands as Newline of Carriage-Return characters. Is it only possible programatically and if so how?


Solution

  • Well after all it looks like the escape characters weren't being recognized when I included them with the command so I've fixed it in the program itself.

       @IBAction func SendCommand(sender: AnyObject) {
        var test = (self.sendTextField.stringValue) + "\r\n"
        let data = test.dataUsingEncoding(NSUTF8StringEncoding)
        self.serialPort?.sendData(data)
    }