diff --git a/example/periphery/usart/python/README.md b/example/periphery/usart/python/README.md index dd87600a777992a944d2aad6c4ca0c1751573b64..84f5b50f5705469fafd0a4752b8a8ed28942d90e 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 d80c972d6b89a426436dd1fc9ff8d25a36f614fa..b2966efa61dc1d27aa2935667e12e778bb846bc6 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}...")