Check and receive Serial port in Python (Port check)

When receiving data from Serial in Python, it is necessary to specify SerialPort, but if there is only one Serial and the baud rate is also known

from serial.tools import list_ports
import serial
ports = list_ports.comports()
ser = serial.Serial(ports[0].device,9600,timeout=0.1)

You can open the port as follows.

If this is too violent, you can check the format of the incoming data for all available ports and open the port if you know the serial baud rate and the format of the incoming data. ..

For example, from Arduino connected to a PC regularly at 9600bps

test:data=***

If you receive data like

from datetime import datetime as dt
from serial.tools import list_ports
import serial
import re

#---------------------------
def ReceiveSerial(_ser):
    _dataStr = ""
    if(_ser!=None):
        _data = _ser.readline()
        if(len(_data)>0):
            try:
                tmpDataStr = _data.decode('utf-8') # 'temp,24.5,hum,50.0'
            except:
                pass
            else:
                _dataStr = re.sub(r'\r|\n|','',tmpDataStr)
    return _dataStr
#---------------------------

def ScanUsingSerialPortName(_reg="^", _baudrate = 115200):
    devName = ""
    ckSer = serial.Serial()
    ckSer.baudrate = _baudrate
    ckSer.timeout = 0.1
    ports = list_ports.comports()
    print("find " + str(len(ports))+"ports")
    if len(ports) > 0:
        deviceNames = []
        for info in ports:
            deviceNames.append(info.device)	#Get the name of the port
            isReady = SerialPortCheck(ckSer,info.device,_reg)
            if (isReady):
                devName = info.device
                break;
    return devName

def SerialPortCheck(_serial, _portName, _reg):
    ret = False
    _serial.port = _portName	#Specify port

    try:
        _serial.open()
    except:
        pass
    else:
        print("SerialPortCheck " + _serial.port )
        startDt = dt.now()
        while True:
            #Read one line
            s = ReceiveSerial(_serial)
            if(len(s)>0):
                print(">" + s)
                matchOB = re.match(_reg,s)
                if matchOB:
                    print("match")
                    ret = True
                    break

            tickTime = (dt.now() - startDt).seconds
            if ((_serial.is_open==False) or (tickTime > 3)):
                print("TimeOut" + s)
                break
        _serial.close()
    return ret

#---------------------------

def SetSerial(_serial, _reg="^", _baudrate=115200):
    if((_serial!=None)and(_serial.is_open)):
        _serial.close()
    tmpSer = None
    usingPortName = ScanUsingSerialPortName(_reg,_baudrate)
    if(usingPortName!=""):
        tmpSer = serial.Serial()
        tmpSer.baudrate = _baudrate
        tmpSer.timeout = 0.1
        tmpSer.port = usingPortName	#Specify port

        try:
            tmpSer.open()
        except:
            tmpSer = None
        else:
            print("SetSerialOK")
    return tmpSer
#---------------------------
ser =SetSerial(ser,"^"+"test:data=",9600)

You can identify the port by doing like.

Recommended Posts

Check and receive Serial port in Python (Port check)
Check and move directories in Python
Find and check inverse matrix in Python
Receive and display HTML form data in Python
POST JSON in Python and receive it in PHP
Receive the form in Python and do various things
Receive runtime arguments in Python 2.7
Write tests in Python to profile and check coverage
Stack and Queue in Python
Unittest and CI in Python
Just try to receive a webhook in ngrok and python
Check for memory leaks in Python
MIDI packages in Python midi and pretty_midi
Difference between list () and [] in Python
Difference between == and is in python
View photos in Python and html
Sorting algorithm and implementation in Python
Manipulate files and folders in Python
About dtypes in Python and Cython
Assignments and changes in Python objects
Ciphertext in Python: IND-CCA2 and RSA-OAEP
Hashing data in R and Python
Function synthesis and application in Python
Export and output files in Python
Reverse Hiragana and Katakana in Python2.7
Reading and writing text in Python
[GUI in Python] PyQt5-Menu and Toolbar-
Create and read messagepacks in Python
Check if you can connect to a TCP port in Python
Notes using cChardet and python3-chardet in Python 3.3.1.
Modules and packages in Python are "namespaces"
Avoid nested loops in PHP and Python
Check the behavior of destructor in Python
Differences between Ruby and Python in scope
AM modulation and demodulation in Python Part 2
difference between statements (statements) and expressions (expressions) in Python
Eigenvalues and eigenvectors: Linear algebra in Python <7>
Implementation module "deque" in queue and Python
Line graphs and scale lines in python
Implement FIR filters in Python and C
Differences in syntax between Python and Java
POST variously with Python and receive with Flask
Search and play YouTube videos in Python
Difference between @classmethod and @staticmethod in Python
[Python] [Windows] Serial communication in Python using DLL
Check if the URL exists in Python
Difference between append and + = in Python list
Difference between nonlocal and global in Python
Write O_SYNC file in C and Python
How to check opencv version in python
Dealing with "years and months" in Python
Read and write JSON files in Python
Easily graph data in shell and Python
Private methods and fields in python [encryption]
Linear Independence and Basis: Linear Algebra in Python <6>
Call sudo in Python and autofill password
Put Tkinter in Macbook and check operation
Differences in multithreading between Python and Jython
Module import and exception handling in python
How to use is and == in Python
SublimeText2 and SublimeLinter --Syntax check for Python3--