You can download this code by clicking the button below.
This code is now available for download.
This function randomly selects a serial port name and connects to that port with a specified baudrate. The function first checks the type of the port name and baudrate, then randomly selects a port from a predefined list of common ports, creates a serial connection, and returns the connection object.
Technology Stack : PySerial
Code Type : Function
Code Difficulty : Intermediate
import serial
import random
def random_serial_port_connection(port_name, baudrate):
# This function connects to a random serial port with a specified baudrate
if not isinstance(port_name, str) or not isinstance(baudrate, int):
raise ValueError("Invalid port name or baudrate")
# List of common serial ports
common_ports = ['COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9', 'ttyUSB0', 'ttyUSB1', 'ttyUSB2']
# Randomly select a port from the list
selected_port = random.choice(common_ports)
# Create a serial connection
ser = serial.Serial(selected_port, baudrate)
# Return the serial connection object
return ser