Python串口命令发送CTRL L

Python serial commands to send CTRL+ L

我有一个连接到串行端口的客户显示器。为此,我正在使用 windows 机器。

我想发送Ctrl+L清除客户显示的显示,但是找不到对我有帮助的解决方案。基本上我希望将来发送Ctrl+'any commands'。

在命令提示符中我可以使用“Ctrl+L”来清除现有显示并显示文本。以下是提示

中显示的命令
echo ^LDisplay me > COMX // ^L is actually CTRL + L 

以上将输出为,

  1. 清除显示。

  2. 显示 "Display me"

现在我正尝试使用 Python 串行连接器实现相同的目的。

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

这根本不起作用。我得到的错误是`

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

但是,如果我对普通文本尝试以下操作,它会完美运行,

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

这会在客户显示屏上显示 "Display me"。

我尝试使用 ser.write("\x0C".encode()) 但没有输出。

我收到错误

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

对于解决此问题的任何建议、改进和帮助,我将不胜感激。谢谢。

要将 Ctrl+L 编码为 Python3 中的字节,您应该使用:

b'\x0c'

为什么?

Ascii 控制字符被编码为它们在字母表中的位置,因此 Ctrl+C,因为它是字母表,编码为十六进制字符串,将是 \x03。同样,Ctrl+L\x0c(十六进制 C 为十进制 12)。

在 python 3 中获取字节,您可以在字符串前加上 b.