Random Serial Connection Function

  • Share this:

Code introduction


This function creates a randomly configured serial connection and either reads data or writes a random string based on a random choice.


Technology Stack : PySerial

Code Type : Custom function

Code Difficulty : Intermediate


                
                    
import serial
import random

def random_serial_connection(port, baudrate, timeout):
    """
    Establish a random serial connection with given parameters.
    """
    # Create a serial connection object
    ser = serial.Serial(port, baudrate, timeout=timeout)
    
    # Randomly choose to read data or write a random string
    if random.choice([True, False]):
        # Read data from the serial port
        data = ser.read(random.randint(1, 10))
    else:
        # Write a random string to the serial port
        random_string = ''.join(random.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=random.randint(10, 20)))
        ser.write(random_string.encode('utf-8'))
    
    # Close the serial connection
    ser.close()                
              
Tags: