1
0

main.swift 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import Foundation
  2. import SwiftSerial
  3. print("You should do a loopback i.e short the TX and RX pins of the target serial port before testing.")
  4. let testString: String = "The quick brown fox jumps over the lazy dog 01234567890."
  5. let arguments = CommandLine.arguments
  6. guard arguments.count >= 2 else {
  7. print("Need serial port name, e.g. /dev/ttyUSB0 as the first argument.")
  8. exit(1)
  9. }
  10. let portName = arguments[1]
  11. let serialPort: SerialPort = SerialPort(name: portName)
  12. do {
  13. try serialPort.openPort()
  14. print("Serial port \(portName) opened successfully.")
  15. defer {
  16. serialPort.closePort()
  17. }
  18. serialPort.setSettings(receiveRate: .baud9600,
  19. transmitRate: .baud9600,
  20. minimumBytesToRead: 1)
  21. print("Writing test string <\(testString)> of \(testString.characters.count) characters to serial port")
  22. var bytesWritten = try serialPort.writeString(testString)
  23. print("Successfully wrote \(bytesWritten) bytes")
  24. print("Waiting to receive what was written...")
  25. let stringReceived = try serialPort.readString(ofLength: bytesWritten)
  26. if testString == stringReceived {
  27. print("Received string is the same as transmitted string. Test successful!")
  28. } else {
  29. print("Uh oh! Received string is not the same as what was transmitted. This was what we received,")
  30. print("<\(stringReceived)>")
  31. }
  32. } catch PortError.failedToOpen {
  33. print("Serial port \(portName) failed to open. You might need root permissions.")
  34. } catch {
  35. print("Error: \(error)")
  36. }