M
M
MaxEpt2020-05-25 18:41:42
Python
MaxEpt, 2020-05-25 18:41:42

Python serial: how to add CR, LF(\r\n) to message?

Hello ! For example, there is a number: I need to pass it to the serial port as an ascii string. Not a symbol corresponding to a digit, but to form a string of digits, that is, a string consisting of just hex digits should go to the port, this is how it should look: If we listen to the serial port, for example, via putty, we will see plain text there 03E8 :
input = 0x3E8

5ecbe3c5b2c59916207254.png


input = 0x3E8
str_res = binascii.b2a_hex(input.to_bytes(2, "big"))

#to upper case
for e in str_res:
   arr_for_send.append( ord(chr(e).upper()) )

#send to serial 
ser.write(serial.to_bytes(arr_for_send))

Everything seems to be working. But, each message must end.
\r\n

I do it like this:
input = 0x3E8
str_res = binascii.b2a_hex(input.to_bytes(2, "big"))

#add CR LF
arr_for_send.append(ord('\r'))
arr_for_send.append(ord('\n'))

#to upper case
for e in str_res:
   arr_for_send.append( ord(chr(e).upper()) )

#send to serial 
ser.write(serial.to_bytes(arr_for_send))


The log analyzer sees the following result:
5ecbe612eb5c8246119692.png

At the same time, if you try to send in an endless loop with a short pause:
while 1:
   ser.write(serial.to_bytes(arr_for_send))
   time.sleep(.3)


5ecbe720b3e1b459692418.png

PS I'm testing sending via cp2102

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question