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 ??)
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 ??)
Share
Improve this question
edited 2 days ago
mkrieger1
23.2k7 gold badges63 silver badges79 bronze badges
asked Feb 17 at 21:59
BEsmartBEsmart
516 bronze badges
4
|
1 Answer
Reset to default 2To 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)
b'AT\r'
andb'AT+HTTPINIT\xAE\r'
. – tdelaney Commented Feb 18 at 6:42