Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 257
Nyxynyx Avatar asked Jun 13 '14 22:06

Nyxynyx


People also ask

How do I select a serial port for Arduino?

Select your board type and port You'll need to select the entry in the Tools > Board menu that corresponds to your Arduino board. Select the serial device of the board from the Tools | Serial Port menu. This is likely to be COM3 or higher (COM1 and COM2 are usually reserved for hardware serial ports).

Can you control Arduino with Python?

On the PC, you could write a program to control the Arduino through a serial connection, based on the protocol you've designed. For this, you can use whatever language and libraries you prefer, such as Python and the PySerial library. Fortunately, there are standard protocols to do all this!


1 Answers

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!" 
like image 54
Matt Williams Avatar answered Nov 03 '22 00:11

Matt Williams