'Swift to Arduino using serial
For my school project, i want to create a MacOS application that communicates with my Arduino using a serial connection. I tried 2 different library (SwiftSerial and ORSSerialPort). Both without succes. Probably because I'm a beginner with Swift.
I decided to continue with ORSSerialPort
because I can find more information about this library. Not a loth but more then SwiftSerial.
So the problem: If I create the ORSSerialPort
object, it think that my parameters don't come through the constructor (init()). Because when i try to read the variables in the object I get a nil. Even when I do this:
port?.baudRate = 9600
baudRate stays nil.
Here my code:
ViewController.swift
import Cocoa
var port: SerialParser?
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
port = SerialParser(path: "/dev/cu.usbmodem14101")
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
@IBAction func ledOn(_ sender: Any) {
port?.open()
port?.sendString(data: "1")
port?.close()
}
@IBAction func ledOff(_ sender: Any) {
port?.open()
port?.sendString(data: "0")
port?.close()
}
}
SerialParser.swift
import Cocoa
import ORSSerial
class SerialParser : NSObject, ORSSerialPortDelegate {
var port : ORSSerialPort?
init(path: String){
port = ORSSerialPort(path: path)
print("path: \(port?.path)")
}
func open(){
port?.baudRate = 9600
port?.delegate = self
if let portUnwraped = port {
portUnwraped.open()
print("path: \(portUnwraped.path) baudRate: \(portUnwraped.baudRate)")
}else{
print("port object empty");
}
}
func close(){
port?.delegate=nil
port?.close()
print("poort closed")
}
func sendString(data: String){
let dataa = Data(data.utf8)
port?.send(dataa)
print("Data sended: \(data)")
}
func serialPortWasRemovedFromSystem(_ serialPort: ORSSerialPort) {
print("PORT REMOVED")
}
}
My output
path: nil
port object empty
Data sended: 1
poort closed
``
Solution 1:[1]
I just checked, the example OSRSerialPortDemo
example from the ORSSerial library works straight out of the box on my M1 running Monterey. It however detects the USB port as usbmodem1101 or usbmodem1201, unlike the Arduino IDE which is detecting it as usbmodem14101 or the like when the Arduino is attached to the mac via a USB hub rather than directly to a USB port of the mac.
I would suggest you to check you are hooked up directly to the mac, and to use the demo app to check the actual names of the serial port.
As an alternative you may prefer to use the demo app and customize it to your needs.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | J Kasparian |