Emulate serial port

joaocandre picture joaocandre · Mar 21, 2014 · Viewed 8.7k times · Source

Is it possible to create a "virtual" serial device that sends data through a "virtual" serial port? I need to develop some code to interact with an Arduino but don't have it with me. Can it be done with socat, or some code that writes to a dev/ttyXXX file?

EDIT: I'm running Arch Linux

Answer

esorton picture esorton · Mar 22, 2014

Yes, you can use socat to simulate a serial port.

You need to use socat's PTY address type:

PTY: Generates a pseudo terminal (pty) and uses its master side. Another
process may open the pty's slave side using it like a serial line or
terminal.

The simplest option is:

socat PTY,link=./virtual-tty,raw,echo=0 -

Have the application you are testing opens virtual-tty. Output from your application will print to the console. Text you type will be sent to your application.

As noted above, the PTY address type creates a peudo-terminal. The link option creates a soft-link between the pseudo-terminal and the given file. You can choose any filename you wish. Without the soft-link you would need to open the device and it is difficult to determine the correct one. raw puts the pseudo-terminal in raw mode. You usually want this as you don't want any of the special terminal handling options. echo=0 disables echo mode.

If you have (or create) an application that simulates the code executing on the Arduino, you can connect it via socat as well. If your simulator comunicates via stdin/stdout, then use the following command:

socat PTY,link=./virtual-tty,raw,echo=0 EXEC:simulator-command

The above connects the stdin/stdout of simulator-command to the pseudo-terminal.

If your simulator communicates via a serial port as well, then use the PTY command twice:

socat PTY,link=./arduino-sim,raw,echo=0 PTY,link=./virtual-tty,raw,echo=0

Have your simulator open arduino-sim.