You can download this code by clicking the button below.
This code is now available for download.
This function randomly selects a serial port from the provided list and connects to it using the specified baudrate and timeout. If the port list is empty, it raises a ValueError exception.
Technology Stack : PySerial
Code Type : Function
Code Difficulty : Intermediate
import serial
import random
def random_serial_port_connection(port_list, baudrate=9600, timeout=1):
"""
Connects to a random serial port from the provided list with specified baudrate and timeout.
"""
if not port_list:
raise ValueError("Port list is empty")
port = random.choice(port_list)
ser = serial.Serial(port, baudrate, timeout=timeout)
return ser