从模块 class 存储和读取数据

Storing and reading data from module class

我正在尝试使用一个模块从传感器板上读取数据,将该数据放入 class,然后在另一个模块中打印该数据。我不确定我是否遵循了这里的最佳实践,或者是否有更好的方法来做到这一点。目前我收到以下错误,我不确定如何更正。

Traceback (most recent call last):
  File "app/conductor.py", line 15, in <module>
    accel_x, accel_y, accel_z = nineDOF.Acceleration()
TypeError: cannot unpack non-iterable NoneType object

conductor.py:

import time
import datetime
import dht11
import max31865
import lsm9ds1

while True:
    externalReading = max31865.temp()
    print("External Temp: {0:0.3f}C".format(externalReading))

    internalTemp, internalHumidity = dht11.readings()
    print("Internal Temp 1: {:.3f}C  Humidity: {}% ".format(internalTemp, internalHumidity))

    nineDOF = lsm9ds1.get()
    accel_x, accel_y, accel_z = nineDOF.Acceleration()
    mag_x, mag_y, mag_z = nineDOF.Magnetometer()
    gyro_x, gyro_y, gyro_z = nineDOF.Gyroscope()
    internalTemp2 = nineDOF.temperature()
    print(
        "Acceleration (m/s^2): ({0:0.3f},{1:0.3f},{2:0.3f})".format(
            accel_x, accel_y, accel_z
        )
    )
    print(
        "Magnetometer (gauss): ({0:0.3f},{1:0.3f},{2:0.3f})".format(mag_x, mag_y, mag_z)
    )
    print(
        "Gyroscope (degrees/sec): ({0:0.3f},{1:0.3f},{2:0.3f})".format(
            gyro_x, gyro_y, gyro_z
        )
    )
    print("Internal Temp 2: {0:0.3f}C".format(internalTemp2))

lsm9ds1.py:

import board
import busio
import adafruit_lsm9ds1

# SPI connection:
from digitalio import DigitalInOut, Direction

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
csag = DigitalInOut(board.D5)
csag.direction = Direction.OUTPUT
csag.value = True
csm = DigitalInOut(board.D6)
csm.direction = Direction.OUTPUT
csm.value = True
sensor = adafruit_lsm9ds1.LSM9DS1_SPI(spi, csag, csm)


class Readings:
    def __init__(self):
        pass

    def Acceleration(self):
        x, y, z = sensor.acceleration

    def Magnetometer(self):
        x, y, z = sensor.magnetic

    def Gyroscope(self):
        x, y, z = sensor.gyro

    def temperature(self):
        x = sensor.temperature


def get():
    return Readings()

您的直接问题是 Readings class 中的方法没有 return 值,而 Python 的默认 return 值没有显式 return 语句是None。有一些语言的函数中的最后一个值也是 return 值 - 想到 R、Perl 和 Bourne Shell - 这可能是这里混淆的根源。 return, return None, and no return at all?

中对此进行了讨论

来自 Acceleration 方法的隐式 None return 值无法解压缩为三元素元组。如果您在该方法的末尾添加一个 return x, y, z,它应该可以工作。

就class和程序结构而言,这取决于您的目标。