red = master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 9)[0] # 这里可以修改需要读取的功能码 print(red) new = (red / 2) print(new) master.execute(1, function_code=cst.WRITE_MULTIPLE_REGISTERS, starting_address=0, output_value=new)object of type 'float' has no len()
时间: 2023-11-26 22:02:39 浏览: 32
这个错误是因为 `red` 变量的类型是 `float`,而不能像 `list` 一样使用 `len()` 方法。你需要将 `red` 转换成一个整型值,然后再使用 `len()` 方法。例如:
```
red = int(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 9)[0]) # 将 float 值转换成整型
print(red)
new = red / 2
print(new)
master.execute(1, function_code=cst.WRITE_MULTIPLE_REGISTERS, starting_address=0, output_value=new)
```
注意,如果你使用 Python 2.x 版本,则使用 `/` 运算符对两个整数进行除法运算,结果将会是一个整数。如果你希望得到一个浮点数结果,需要将其中一个整数强制转换成浮点数,例如:
```
red = int(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 9)[0]) # 将 float 值转换成整型
print(red)
new = float(red) / 2 # 将其中一个整数强制转换成浮点数
print(new)
master.execute(1, function_code=cst.WRITE_MULTIPLE_REGISTERS, starting_address=0, output_value=new)
```
这样就能够避免出现 `TypeError: object of type 'float' has no len()` 的错误了。