From c56abb5962dac6f60097ca6f2121c882f6f01970 Mon Sep 17 00:00:00 2001 From: li123456ke <46290363@qq.com> Date: Wed, 12 Nov 2025 06:43:16 +0000 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BA=86=E4=B8=B2=E5=8F=A3?= =?UTF-8?q?=E6=8E=A5=E6=94=B6=E4=BB=A3=E7=A0=81=E4=BB=A5=E5=8F=8A=E6=96=87?= =?UTF-8?q?=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- example/periphery/usart/python/README.md | 18 +++++++++++++++--- .../periphery/usart/python/test_usart_read.py | 18 +++++++++++++++--- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/example/periphery/usart/python/README.md b/example/periphery/usart/python/README.md index dd87600..84f5b50 100644 --- a/example/periphery/usart/python/README.md +++ b/example/periphery/usart/python/README.md @@ -112,16 +112,28 @@ class USARTBase: from lockzhiner_vision_module.periphery import USART1 +def read_exactly(usart, total_bytes): + """累积读取 exactly total_bytes 个字节""" + buffer = bytearray() + while len(buffer) < total_bytes: + chunk = usart.read(total_bytes - len(buffer)) + if not chunk: + continue + buffer.extend(chunk.encode('latin1')) + return bytes(buffer) + + if __name__ == "__main__": usart = USART1() - if usart.open(115200) is False: + if not usart.open(115200): print("Failed to open usart.") exit(1) - print("Start receiving serial port data.") + print("Start receiving serial port data (waiting for 1024 bytes per output)...") while True: - print(usart.read(1024)) + data = read_exactly(usart, 12) + print(f"Received {len(data)} bytes: {data}...") ``` 串口发送例程的核心代码如下: diff --git a/example/periphery/usart/python/test_usart_read.py b/example/periphery/usart/python/test_usart_read.py index d80c972..b2966ef 100644 --- a/example/periphery/usart/python/test_usart_read.py +++ b/example/periphery/usart/python/test_usart_read.py @@ -1,13 +1,25 @@ from lockzhiner_vision_module.periphery import USART1 +def read_exactly(usart, total_bytes): + """累积读取 exactly total_bytes 个字节""" + buffer = bytearray() + while len(buffer) < total_bytes: + chunk = usart.read(total_bytes - len(buffer)) + if not chunk: + continue + buffer.extend(chunk.encode('latin1')) + return bytes(buffer) + + if __name__ == "__main__": usart = USART1() - if usart.open(115200) is False: + if not usart.open(115200): print("Failed to open usart.") exit(1) - print("Start receiving serial port data.") + print("Start receiving serial port data (waiting for 1024 bytes per output)...") while True: - print(usart.read(1024)) + data = read_exactly(usart, 12) + print(f"Received {len(data)} bytes: {data}...") -- Gitee