Search code examples
pythonpyserial

Sending dictionary value with hex numbers over serial in python


I have a dictionary with commands (ASCII with extended characters and hex numbers), that should be sent over serial to a microcontroller.

But I'm not able to get the right format for the value to be sent. How can I do this correctly?

I'm using Python 3.13.2.

command= {
    "cmd_a": 'AT\r',
    "cmd_b": 'AT+HTTPINIT\xAE\r',
    "cmd_c": 'AT+CGMM\xC7\xB4\r',
}

cmd_to_send = at_cmd.get("cmd_c") 

comport.write(cmd_to_send ??)  

Solution

  • To use Serial.write() you need to pass a byte string as an argument. Here are some ways to do this:

    Method 1 — use str.encode() method:

    command = {
        "cmd_a": 'AT\r',
        "cmd_b": 'AT+HTTPINIT\xAE\r',
        "cmd_c": 'AT+CGMM\xC7\xB4\r',
    }
    
    cmd_to_send = command.get("cmd_c")
    
    comport.write(cmd_to_send.encode('utf-8'))
    

    Method 2 — start every string with b:

    command = {
        "cmd_a": b'AT\r',
        "cmd_b": b'AT+HTTPINIT\xAE\r',
        "cmd_c": b'AT+CGMM\xC7\xB4\r',
    }
    
    cmd_to_send = command.get("cmd_c")
    
    comport.write(cmd_to_send)
    

    Method 3 — use bytes():

    command = {
        "cmd_a": 'AT\r',
        "cmd_b": 'AT+HTTPINIT\xAE\r',
        "cmd_c": 'AT+CGMM\xC7\xB4\r',
    }
    
    cmd_to_send = command.get("cmd_c")
    
    comport.write(bytes(cmd_to_send, 'utf-8'))
    

    To be sure, you can use type checking.

    For methods 1 and 3:

    if type(cmd_to_send) is str:
        comport.write(...)
    

    For method 2:

    if type(cmd_to_send) is bytes:
        comport.write(cmd_to_send)