【问题标题】:microPython attributeError in __init____init__ 中的 microPython 属性错误
【发布时间】:2018-11-23 16:38:41
【问题描述】:

编辑:多亏了拔掉插头再插上所有东西的古老传统,我让它工作了;我刷新了 WiPy 模块并重新安装了 Pymakr 插件。

我目前正在为 micropython 编写一个 PID 控制器(我们必须创建一个 linefollower)。我已经将 microPython 中的 PID 算法作为一个类实现了。

我将使用 Pycom 的 WiPy 模块来控制我的 linefollower。

目前实际程序并没有做太多,我只是想测试程序是否相当快,因此我有一些随机数作为输入和 K 值,而输出函数只是留空。

但是,每当我尝试运行一个小测试脚本来创建对象并计算 PID 100 次时,我会在 PID 类的 init 中得到一个属性错误。这是给我带来麻烦的方法:

def __init__(self, input_func, output_func, P_factor=1.0, I_factor=0.0,
             D_factor=0.0):

    ... previous variable declarations ...

    # Initializer for the time. This will form the basis for the timebased
    # calculations. This time will mark the start of a time-block.
    self.last_calculate_time = utime.ticks_ms()

最后一行给我带来了麻烦。主程序里面有这个:

def motorOutput(PID_output):
    """
    Function for driving the two motors depending on the PID output.
    """
    pass

def generateInput():
    """
    Return a random float
    """
    return 2.5


if __name__ == "__main__":

    print("creating PID controller")
    PID_controller = PID.PID(generateInput, motorOutput, 1.0, 0.5, 1.5)
    counter = 0
    print("starting loop")
    while counter < 1000:
        counter += 1
        PID_controller.calculate()

    print("finished loop")

这是我运行文件时得到的输出:

>>> Running main.py

>>>
>>> creating PID controller
╝Traceback (most recent call last):
File "<stdin>", line 60, in <module>
File "/flash/lib/PID.py", line 95, in __init__
AttributeError: 'PID' object has no attribute 'last_calculate_time'
╝>
MicroPython v1.8.6-621-g17ee404e on 2017-05-25; WiPy with ESP32

【问题讨论】:

    标签: python pid attributeerror micropython


    【解决方案1】:

    您收到此错误是因为您尝试分配尚未声明的属性,并且我假设您使用的是 python 2 经典的课堂风格。在您的 PID 类中添加 last_calculate_time 的定义,例如 last_calculate_time = None,然后它应该可以按预期工作。

    更合适的方法是将object 作为参数传递给您的类定义,如下所示,使其被视为新样式类:

    class PID(object):
        def __init__(self):
            self.last_calculate_time = utime.ticks_ms()
    

    更多信息可见:https://wiki.python.org/moin/NewClassVsClassicClass

    【讨论】:

    • 感谢您的快速回复!我已经将对象作为类参数。我尝试先将变量初始化为 None 然后分配值。但是现在我得到了同样的错误,但是在实际的计算方法中而不是 init
    • @Pieter-JanCassiman 抱歉假设这是问题所在!嗯,您对 utime.ticks_ms() 的输出进行了一些测试吗?也许暂时硬编码该值以查看是否有帮助?
    • 啊哈!我们正在做某事! ticks_ms() 确实是问题所在。它说该模块没有属性 ticks_ms()。这很奇怪,因为这是文档告诉我要使用的......
    • 刚刚使用在线 micropython CLI 对其进行了测试并为我工作。您为 utime 使用的 import 语句是什么?
    • 我使用的是“import utime”,但我刚刚删除了所有插件并重新安装了它。我还把固件重新刷到了主板上,这似乎解决了问题。
    猜你喜欢
    • 2011-12-16
    • 1970-01-01
    • 2023-02-06
    • 2019-03-02
    • 2017-11-28
    • 2022-06-23
    • 1970-01-01
    • 2016-11-10
    • 2011-10-27
    相关资源
    最近更新 更多