0

我有一个温度和压力计,我想用它来跟踪温度随时间的变化。由于随着时间的推移我可能会使用多个传感器,因此我希望能够将我的 BMP085 传感器引用为tp. 换句话说,我想调用tp.temptp.pressure获取当前温度等。问题是每次调用时都不会更新tp.temp.pressure建议?

#!/usr/bin/env python
#temperature logger for the BMP085 Temperature and Pressure Sensor on the Raspberry Pi

from Adafruit_BMP085 import BMP085
from time import sleep
import pickle, sys, os

class tps():
    def __init__(self):
        #temperature/pressure sensor setup
        self.bmp = BMP085(0x77)
        self.temp = self.bmp.readTemperature()*1.8+32
        self.pressure = self.bmp.readPressure()*0.0002953

class data():
    def __init__(self):
        self.tp = tps()
        self.savedata()


    def savedata(self):
#        if os.path.exists("data.dat")==True:
#            if os.path.isfile("data.dat")==True:
#                fileHandle = open ( 'data.dat' )
#                olddata = pickle.load ( fileHandle )
#                fileHandle.close()

        print self.tp.temp, self.tp.pressure
        sleep(4)
        print self.tp.temp, self.tp.pressure

#        newdata = [self.tp.temp, self.tp.pressure]
#        self.datadump = [olddata]
#        self.datadump.append(newdata)
#        fileHandle = open ( 'data.dat', 'w' )
#        pickle.dump ( self.datadump, fileHandle )
#        fileHandle.close()             

data()
4

1 回答 1

2

那是因为您只调用了一次bmp.readTemperature()andbmp.readPressure()函数tps.__init__。在最后的打印语句中,您只是两次读取这些函数返回的值,而不是获取更新的值。

以下是如何获取更新值的示例:

class tps():
    def __init__(self):
        #temperature/pressure sensor setup
        self.bmp = BMP085(0x77)
        self.temp = None
        self.pressure = None
#       If you want to initialize your tps object with sensor data, you can call your updater method here.
        self.updateTempAndPressure()

#   Here's a function that you can call whenever you want updated data from the sensor
    def updateTempAndPressure(self):
        self.temp = self.bmp.readTemperature()*1.8+32
        self.pressure = self.bmp.readPressure()*0.0002953

class data():
    def __init__(self):
        self.tp = tps()
        self.savedata()

    def savedata(self):
#       Call the method that gets updated data from the sensor
        self.tp.updateTempAndPressure()
        print self.tp.temp, self.tp.pressure
        sleep(4)
#       Call the update method again
        self.tp.updateTempAndPressure()
        print self.tp.temp, self.tp.pressure

data()
于 2013-08-09T21:13:43.153 回答