[Python] Reading a serial port and storing the data in a Dictionary [closed]

Discussão em 'Python' iniciado por Stack, Fevereiro 19, 2025.

  1. Stack

    Stack Membro Participativo

    I'm fairly new to Python and so I'd like some feedback on the code I've written. The code is written to send and receive data from a ham radio. The code opens a serial port to the radio, then writes commands and reads the answer. The answer is saved in a dictionary for later use. This will be a part of a larger program that will allow the user to import the radio's configuration data to the app, then make modifications and send it back to the radio. It will also be able to save the data to a file so that different radio configurations can be saved and downloaded to the radio for use in different situations. I've copied the code below.

    import serial

    def Read_Radio():
    # Configure the serial port
    ser = serial.Serial(
    port='COM4',
    baudrate=38400,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=1
    )

    # Function to send a command to the device
    def send_command(ser, command):
    ser.write(command.encode())
    response = ser.readline().decode()
    return response

    menu_data = {}

    try:
    # Read all Menu items and store in dictionary
    for m in range(1, 15): # Limited to 15 for testing.
    ID = f"{m:03}" # formats the ID to 3 characters
    command = "EX" + str(ID) + ";" # creates the command to be sent
    response = send_command(ser, command) # sends the command
    raw = response.lstrip("EX") # strips the leading characters
    raw = raw.rstrip(";") # strips the trailing character
    P1 = raw[0:3] # pulls first three characters
    P2 = raw[3:] # pulls after first 3 letters
    menu_data.update({P1:p2}) # Saves the data pairs in a dict
    except Exception as e:
    print(f"An error occurred: {e}")
    finally:
    print(menu_data)
    # Close the serial port
    ser.close()

    Read_Radio()


    SAMPLE DATA OUPUT: {'001': '0300', '002': '0700', '003': '3000', '004': '0', '005': '1', '006': '0', '007': '1', '008': '08', '009': '2', '010': '050', '011': '050', '012': '3', '013': '0', '014': '30'}

    The results are as I expected. I'm trying to make sure that I have the data in a useful format and that my code is efficient or can it be simpler. Is there anything in my code that may be slowing it down.

    Continue reading...

Compartilhe esta Página