Ubuntu 下使用虚拟串口进行开发测试

1.  python 工具

#coding = utf-8
 
import pty
import os
import select
 
def mkpty():
    master1, slave = pty.openpty()
    slaveName1 = os.ttyname(slave)
    master2, slave = pty.openpty()
    slaveName2 = os.ttyname(slave)
    print '\nslave device names: ', slaveName1, slaveName2
    return master1, master2
 
if __name__ == "__main__":
    master1, master2 = mkpty()
    while True:
        rl, wl, el = select.select([master1, master2], [], [], 1)
        for master in rl:
            data = os.read(master, 128)
            print "read %d data." %len(data)
            if master == master1:
                os.write(master2, data)
            else:
                os.write(master1, data)

使用方法:

  启动:在终端里运行“python mkptych.py&”,这样就可以生成一个基于pty(伪终端)的虚拟端口对,两个设备名会显示在终端里。然后就可以利用这两个设备名在本机上进行虚拟串口之类的调试。

  关闭:使用完后用ps查看这个python进程的pid号,然后kill掉即可。

2.  Ubuntu下 cutecom 图像界面串口调试工具(参考:https://blog.csdn.net/zhaoqi2617/article/details/72238546)

  (1)终端下载命令:sudo apt-get install cutecom 

  (2)通过终端打开软件:sudo cutecom (需要root权限,否则无法打开串口)

  (3)在 Device 中填写上边生成的虚拟串口号  /dev/pts/24   和   /dev/pts/25,  Input  中输入文字 ,点击回车发送测试 

Ubuntu 下使用虚拟串口进行开发测试_第1张图片

3.  python 编写测试程序

       (参考 https://blog.csdn.net/itas109/article/details/78874165  ,                                                     https://blog.csdn.net/jiangchao3392/article/details/75107330)

  (1)1.安装pyserial(安装 serial module)

     这里区分python2和 python3:

1 sudo apt install python-pip     //python2
2 sudo apt install python3-pip    //python3

  (2)然后通过:

 

1 pip install pyserial    //python2
2 pip3 install pyserial   //python3

        (3)测试程序

import serial
from time import sleep

def recv(serial):
    while True:
        data = serial.read_all()
        if data == '':
            continue
        else:
            break
        sleep(0.02)
    return data

if __name__ == '__main__':
    serial = serial.Serial('COM5', 9600, timeout=0.5)  #/dev/ttyUSB0
    if serial.isOpen() :
        print("open success")
    else :
        print("open failed")

    while True:
        data =recv(serial)
        if data != b'' :
            print("receive : ",data)
            serial.write(data) #数据写回

参考文章:  https://blog.csdn.net/a844651990/article/details/80624019

       https://blog.csdn.net/haifengid/article/details/51996613

       https://blog.csdn.net/itas109/article/details/78874165

 

注:解决 ImportError: No module named 'serial' 问题

  https://blog.csdn.net/jiangchao3392/article/details/75107330

你可能感兴趣的:(Linux,python,虚拟串口,Ubuntu,Linux)