简体   繁体   中英

Python serial commands to send CTRL+ L

I have a customer display, that's connected to serial port. I am using a windows machine for this.

图片

I want to send Ctrl + L to clear the display of customer display, but I cannot find a solution that helps me. Basically I wish to send Ctrl +'any commands' in future.

In command Prompt I can use " Ctrl + L " to clear the existing display and display the text. The following is the command that gets displayed in prompt

echo ^LDisplay me > COMX // ^L is actually CTRL + L 

The above will output as ,

  1. Clears the display.

  2. Displays "Display me"

Now I am trying to achieve the same thing using Python serial connector.

import serial
ser = Serial ('COM5',timeout=2)
ser.write("\x0C") # equivalent to ctrl+L

This does not work at all. I get error as `

Exception in serial connection: unicode strings are not supported, please encode to bytes:'\\x03'

However if I try the following for normal texts, it works perfectly,

ser.write("Display me".encode()

This displays "Display me" in the customer display.

I tried to use ser.write("\\x0C".encode()) but I get no output.

I get error as

Exception in serial connection: unicode strings are not supported, please encode to bytes:'\\x1fc\\x00'

I would appreciate any suggestions, improvements and help to solve this. Thanks.

To encode a Ctrl + L as bytes in Python3, you should use:

b'\x0c'

Why?

Ascii control characters are encoded as their position in the alphabet, so Ctrl + C , since it is the third letter of the alphabet, encoded as a hex string, would be \\x03 . Similarly, Ctrl + L would \\x0c (hex C is decimal 12).

In python 3 to get bytes, you can pre-pend the string with a b .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM