使用BMP280模块检测压强和温度
#http://docs.dfrobot.com.cn/bxy/4.2.16bmp280.html#https://www.dfrobot.com.cn/goods-1860.html
#根据BMP280模块获取:温度、压强、海拔
from microbit import *
I2C_ADDR = 0x77
class BMP280():
def __init__(self,i2c):
self.i2c = i2c
self.T1 = self.get2Reg(0x88)
self.T2 = self.short(self.get2Reg(0x8A))
self.T3 = self.short(self.get2Reg(0x8C))
self.P1 = self.get2Reg(0x8E)
self.P2 = self.short(self.get2Reg(0x90))
self.P3 = self.short(self.get2Reg(0x92))
self.P4 = self.short(self.get2Reg(0x94))
self.P5 = self.short(self.get2Reg(0x96))
self.P6 = self.short(self.get2Reg(0x98))
self.P7 = self.short(self.get2Reg(0x9A))
self.P8 = self.short(self.get2Reg(0x9C))
self.P9 = self.short(self.get2Reg(0x9E))
self.setReg(0xF4, 0x2F)
self.setReg(0xF5, 0x0C)
self.T = 0
self.P = 0
def short(self, dat):
if dat > 32767: return dat-65536
else: return dat
def setReg(self,reg,dat):
self.i2c.write(I2C_ADDR, bytearray())
def getReg(self,reg):
self.i2c.write(I2C_ADDR,bytearray())
t = self.i2c.read(I2C_ADDR,1)
return t
def get2Reg(self,reg):
self.i2c.write(I2C_ADDR,bytearray())
t = self.i2c.read(I2C_ADDR,2)
return t+t*256
def get(self):
adc_T = (self.getReg(0xFA)<<12) + (self.getReg(0xFB)<<4) + (self.getReg(0xFC)>>4)
var1 = (((adc_T>>3)-(self.T1<<1))*self.T2)>>11
var2 = (((((adc_T>>4)-self.T1)*((adc_T>>4) - self.T1))>>12)*self.T3)>>14
t = var1+var2
self.T = ((t * 5 + 128) >> 8)/100
var1 = (t>>1) - 64000
var2 = (((var1>>2) * (var1>>2)) >> 11 ) * self.P6
var2 = var2 + ((var1*self.P5)<<1)
var2 = (var2>>2)+(self.P4<<16)
var1 = (((self.P3*((var1>>2)*(var1>>2))>>13)>>3) + (((self.P2) * var1)>>1))>>18
var1 = ((32768+var1)*self.P1)>>15
if var1 == 0:
return
adc_P = (self.getReg(0xF7)<<12) + (self.getReg(0xF8)<<4) + (self.getReg(0xF9)>>4)
p=((1048576-adc_P)-(var2>>12))*3125
if p < 0x80000000:
p = (p << 1) // var1
else:
p = (p // var1) * 2
var1 = (self.P9 * (((p>>3)*(p>>3))>>13))>>12
var2 = (((p>>2)) * self.P8)>>13
self.P = p + ((var1 + var2 + self.P7) >> 4)
return
def getTemp(self):
self.get()
return self.T
def getPress(self):
self.get()
return self.P
def getAltitude(self):
return 44330*(1-(self.getPress()/101325)**(1/5.255))
i2c.init(freq=100000,scl=pin19,sda=pin20)
bmp=BMP280(i2c)
print(str(bmp.getTemp())+' *C')
print(str(bmp.getPress())+' Pa')
print(str(bmp.getAltitude())+' m')
页:
[1]