File "/tmp/maixpy_run/main.py", line 76, in <module> uart1.write(packet) # 通过串口发送目标名称 ^^^^^^^^^^^^^^^^^^^ TypeError: write(): incompatible function arguments. The following argument types are supported: 1. (self: maix._maix.peripheral.uart.UART, data: maix.Bytes(bytes)) -> int
时间: 2025-07-19 16:13:40 浏览: 11
在 MaixPy 中调用 `UART.write()` 方法时,若传入的数据类型不正确,会引发 `TypeError: write() incompatible function arguments` 错误。该错误通常出现在传入的参数不是 `bytes` 或 `bytearray` 类型的情况下。Python 的串口通信模块要求数据必须以字节形式发送,若直接传入字符串或其他不可迭代的类型,将导致类型不匹配问题。
例如,以下代码会导致类型错误:
```python
uart.write("Hello, MaixCam!") # 传入字符串而未编码为 bytes
```
为解决该问题,应确保传入的是 `bytes` 类型的数据。可以通过以下方式转换数据:
- 使用字节字符串字面量:
```python
uart.write(b"Hello, MaixCam!") # 使用字节字符串
```
- 或使用 `.encode()` 方法将字符串编码为 `bytes`:
```python
uart.write("Hello, MaixCam!".encode('utf-8')) # 将字符串编码为 bytes
```
此外,若构造了 `bytearray` 类型的数据包,也应直接传入 `write()` 方法:
```python
packet = bytearray([0x40, 0x01] + [0x00] * 25 + [0x5D])
uart.write(packet)
```
在 C 语言环境中,若通过 MaixCam SDK 使用 UART 通信,应确保调用 `uart_write_bytes()` 时传入的是 `uint8_t` 类型的指针和长度,否则也会导致类似的类型不匹配问题。正确的调用方式如下:
```c
uint8_t packet[28] = {0x40, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x5D};
uart_write_bytes(UART_DEVICE_0, packet, sizeof(packet));
```
通过上述方式可确保数据格式与函数接口要求一致,从而避免参数类型不兼容的问题[^1]。
阅读全文