Skip to content

Instantly share code, notes, and snippets.

@yojiro
Created August 6, 2013 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yojiro/6166512 to your computer and use it in GitHub Desktop.
Save yojiro/6166512 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python2.7
from smbus import SMBus
import logging
from datetime import datetime
from time import sleep
import struct
class MPL115A2(object):
# device registers
_MPL115A2_ADDR = 0x60
_MPL115A2_REG_PRESSURE = 0x00
_MPL115A2_REG_TEMP = 0x02
_MPL115A2_REG_COEFF_OFFSET = 0x04
_MPL115A2_REG_STARTCONVERSION = 0x12
_MPL115A2_CMD_STARTCONVERSION = 0x12
def __init__(self, bus):
self.bus = SMBus(bus)
self.a0 = None
self.b1 = None
self.b2 = None
self.c12= None
self.pres = None
self.temp = None
self.__read_coeffient()
def __read_coeffient(self):
# read registers
reg = []
for i in range(8):
v = self.bus.read_byte_data(self._MPL115A2_ADDR,
self._MPL115A2_REG_COEFF_OFFSET + i)
reg.append(v)
# convert to 4 set of signed 16bit values
(a0, b1, b2, c12) = struct.unpack(">hhhh",
''.join([chr(x) for x in reg]))
self.a0 = float(a0) / (1 << 3)
self.b1 = float(b1) / (1 << 13)
self.b2 = float(b2) / (1 << 14)
self.c12 = float((c12 >> 2)) / (1 << 22)
logging.debug("Coefficient: a0: %f, b1: %f, b2: %f, c12: %f",
self.a0, self.b1, self.b2, self.c12)
def read_sensor(self):
# start conversion
self.bus.write_i2c_block_data(self._MPL115A2_ADDR,
self._MPL115A2_REG_STARTCONVERSION,
[self._MPL115A2_CMD_STARTCONVERSION])
# wait until the conversion is finished
sleep(0.005) # wait 5ms
# read registers
msb = self.bus.read_byte_data(self._MPL115A2_ADDR,
self._MPL115A2_REG_PRESSURE+0)
lsb = self.bus.read_byte_data(self._MPL115A2_ADDR,
self._MPL115A2_REG_PRESSURE+1)
self.pres = ((msb << 8 | lsb) & 0xffc0) >> 6
msb = self.bus.read_byte_data(self._MPL115A2_ADDR,
self._MPL115A2_REG_TEMP+0)
lsb = self.bus.read_byte_data(self._MPL115A2_ADDR,
self._MPL115A2_REG_TEMP+1)
self.temp = ((msb << 8 | lsb) & 0xffc0) >> 6
def pressure(self):
'''
c12x2 = self.c12 * self.temp
a1 = self.b1 + c12x2
a1x1 = a1 * self.pres
y1 = self.a0 + a1x1
a2x2 = self.b2 * self.temp
pcomp = y1 + a2x2
'''
pcomp = self.a0
pcomp += (self.b1 + self.c12 * self.temp ) * self.pres
pcomp += self.b2 * self.temp
return (((650.0 / 1023.0) * pcomp) + 500.0)
def temperature(self):
return ((self.temp - 498.0) / -5.35) + 25.0
def value(self):
p = self.pressure()
t = self.temperature()
return [p, t]
if __name__ == "__main__":
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)-8s %(message)s",
datefmt="%Y-%m-%d(%a) %H:%M:%S",
filename='/tmp/plesure.log')
sensor = MPL115A2(1)
while (1):
sensor.read_sensor()
(p, t) = sensor.value()
logging.info("Pres: %04.2fhPa, Temp: %02.2fdeg-C" , p, t)
sleep (10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment