Python操作串口

发布时间:2019-09-16 07:27:25编辑:auto阅读(1852)

    首先需确保安装了serial模块,如果没安装的话就安装一下python-pyserial。

    一个Python实现的串口Echo

    import serial
    import sys
    
    try:
    	ser = serial.Serial('/dev/ttyUSB0', 9600)
    except Exception, e:
    	print 'open serial failed.'
    	exit(1)
    
    print 'A Serial Echo Is Running...'
    while True:
    	# echo
    	s = ser.read()
    	ser.write(s)
    
    	# write to stdout and flush it
    	sys.stdout.write(s)
    	sys.stdout.flush()



关键字