Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

Python to automatically select serial ports (for Arduino)

Currently the python program must know which port a device (Arduino) is on before Python can communicate the device.

Problem: Whenever the device is plugged out and back in, its COM port changes, so the correct serial port must be given to Python again for it to find the device.

How can Python (using pySerial) automatically search for the correct serial port to use? Is it possible for python to correctly identify the device on a serial port as an Arduino?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the following code to see all the available serial ports:

import serial.tools.list_ports
ports = list(serial.tools.list_ports.comports())
for p in ports:
    print p

This gives me the following:

('COM4', 'Arduino Due Programming Port (COM4)', 'USB VID:PID=2341:003D SNR=75330303035351300230')
('COM11', 'RS-232 Port (COM11)', 'FTDIBUS\VID_0856+PID_AC27+BBOPYNPPA\0000')

To work out if it's an Arduino you could do something like:

    if "Arduino" in p.description:
        print "This is an Arduino!"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...