Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux and Python: auto-detect Arduino serial port [duplicate]

I have a problem automagically detecting my Arduino's serial port in Python, using Mac/Linux.

I know a working shell command to find the port; because Arduino serial ports almost always begin with tty.usbmodem, you can find the serial port with ls /dev | grep tty.usbmodem which should return something like tty.usbmodem262141.

However, I'm confused on how to call this shell command from my Python code. I've tried this:

p = "/dev/" + str(subprocess.Popen('ls /dev | grep tty.usbmodem', shell=True).stdout)

Which should make p become /dev/tty.usbmodem262141.

However, at the moment I get /dev/None.


How can I modify my shell script call to return the right string? I've tried to use several commands to call shell scripts, but none have worked.

like image 578
hao_maike Avatar asked Dec 26 '22 21:12

hao_maike


1 Answers

First of all, if you're using a shell, you can use a glob (*), so your command would become ls /dev/tty.usbmodem*.

Next, you don't even have to call a shell command to use a glob in Python!

Consider the following code:

import glob

print(glob.glob("/dev/tty.usbmodem*"))
like image 139
cha0site Avatar answered Feb 19 '23 06:02

cha0site