Python:将传感器数据更新为变量

时间:2013-08-09 21:05:26

标签: python python-2.7

我有一个温度和压力表,我想用它来跟踪温度。由于随着时间的推移我可能最终会有多个传感器,我希望能够将我的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()

1 个答案:

答案 0 :(得分:2)

那是因为您只在bmp.readTemperature()中调用bmp.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()