Skip to content

Instantly share code, notes, and snippets.

@hkennyv
Last active October 30, 2019 20:41
Show Gist options
  • Save hkennyv/0e961e684222fecc43a955cb32d27147 to your computer and use it in GitHub Desktop.
Save hkennyv/0e961e684222fecc43a955cb32d27147 to your computer and use it in GitHub Desktop.
Virutal Serial Ports with socat

Virtual Serial Ports with socat

author(s): khuynh

Overview

I found this great resource online about using socat to create virtual serial ports. This is extremely useful for testing code that interfaces with a serial port. I'm documenting this here so I can have refer to later. I'll provide a script that opens two new virutal serial ports that you can read & write from as well.

The documentation for socat is located here. The run.sh script was taken from here.

Installation

Debian/Ubuntu

Install via apt

sudo apt install socat

MacOS

Install via brew

brew install socat

Windows

I haven't tested any of these methods out myself but here are some resources that I came across:

Code

# this one creates a symlink to two files: ./reader and ./writer that you can use
#     to connect to instead of the traditional /dev/ttysXXX method (idk if this works
#     on windows...)
# socat -d -d -v pty,rawer,echo=0,link=./reader pty,rawer,echo=0,link=./writer


# this one opens up two new serial ports
# see following link for windows resources:
# https://stackoverflow.com/questions/38444497/trouble-locating-my-serial-ports-using-bash-on-windows-10

socat -d -d -v pty,rawer,echo=0, pty,rawer,echo=0
import serial
import time
# make sure to modify your ports
PORT1 = '/dev/ttys008'
PORT2 = '/dev/ttys009'
ser1 = serial.Serial(PORT1, 115200)
ser2 = serial.Serial(PORT2, 115200)
while 1:
time.sleep(1)
# write to PORT1
message = b'hello world'
ser1.write(message)
print('writing: {}'.format(message))
time.sleep(1)
# read from PORT2
if ser2.inWaiting():
payload = ser2.read(ser2.inWaiting())
print('recv: {}'.format(payload))
# this one creates a symlink to two files: ./reader and ./writer that you can use
# to connect to instead of the traditional /dev/ttysXXX method (idk if this works
# on windows...)
# socat -d -d -v pty,rawer,echo=0,link=./reader pty,rawer,echo=0,link=./writer
# this one opens up two new serial ports
# see following link for windows resources:
# https://stackoverflow.com/questions/38444497/trouble-locating-my-serial-ports-using-bash-on-windows-10
socat -d -d -v pty,rawer,echo=0, pty,rawer,echo=0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment