You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PyFirmata读取Arduino摇杆输入时乘1023返回None的问题

解决PyFirmata读取摇杆输入时乘法操作导致值为None的问题

问题出在程序启动初期或数据上报延迟时,board.analog[x].read()可能返回None——此时直接执行乘法运算,None与数字相乘的结果依然是None,就会出现你看到的异常。另外你代码里存在冗余的引脚配置操作,且遗漏了对analog[1]的模式设置。

以下是修复后的代码:

import pyfirmata
import time

board = pyfirmata.Arduino('COM3')
it = pyfirmata.util.Iterator(board)  
it.start()

# 配置模拟输入引脚并启用数据上报
board.analog[0].mode = pyfirmata.INPUT
board.analog[0].enable_reporting()
board.analog[1].mode = pyfirmata.INPUT
board.analog[1].enable_reporting()

while True:
    x = board.analog[0].read()
    y = board.analog[1].read()
    
    # 仅在获取到有效数值时执行缩放和打印
    if x is not None and y is not None:
        x_scaled = x * 1023
        y_scaled = y * 1023
        print(x_scaled, y_scaled)
    else:
        print("等待获取有效输入...")
    
    time.sleep(0.5)

修复说明:

  • 新增None值判断逻辑,确保只有拿到有效数据时才进行乘法运算
  • 清理了重复的引脚模式配置代码,补全了analog[1]的模式设置
  • 使用独立变量存储缩放后的值,避免覆盖原始读取结果,提升代码可读性

内容的提问来源于stack exchange,提问作者pert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 20:32:32