Last active
September 24, 2015 00:21
-
-
Save whymarrh/23bf13b6a6ac2e68a5aa to your computer and use it in GitHub Desktop.
Create serial ports with Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 -OO | |
import itertools | |
import serial | |
import shlex | |
import subprocess | |
MESSAGE = """ | |
Hi there! You have a serial port: | |
RX = {0} | |
TX = {1} | |
You can create symbolic links to those files in /dev, naming them ttySX, where | |
X is a number of your choosing. Making symbolic links will have them show up | |
as available serial ports in applications that can only use those files. Once | |
you have that, you can write and read to TX and RX, respectively. | |
Example links: | |
ln -s {0} /dev/ttyS98 # RX | |
ln -s {1} /dev/ttyS99 # TX | |
On my side, you can use the prompt below to write to my serial port. You can | |
also use an application like screen to view the data I would be recieving. | |
My port details: | |
RX = {2} | |
TX = {3} | |
Example screen command: | |
screen {2} 115200 | |
Important: press ^D to quit | |
""" | |
def create_serial_pins(): | |
command = 'socat -d -d pty,raw,echo=1 pty,raw,echo=1' | |
process = subprocess.Popen(shlex.split(command), | |
universal_newlines=True, | |
stderr=subprocess.PIPE) | |
yield tuple([process.stderr.readline().split().pop() for i in range(2)]) | |
process.terminate() | |
def create_serial_line(pins=1): | |
pin_pairs = [create_serial_pins() for i in range(pins)] | |
return itertools.zip_longest(*pin_pairs) | |
for pins in create_serial_line(2): | |
a = (pins[0][0], pins[1][0]) | |
b = (pins[1][1], pins[0][1]) | |
print(MESSAGE.strip().format(*itertools.chain(a, b))) | |
try: | |
s = serial.Serial(b[1]) | |
while True: | |
s.write(bytes(input('>>> '), 'UTF-8')) | |
except (EOFError, KeyboardInterrupt, TypeError) as err: | |
print('') | |
print(err) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment