温湿度センサー HTU21D / ユーザーレジスタを読み出してみる / micro:bit / MicroPython

デフォルトのままなら 0x02 (ビット[1] だけが 1) になるはずである。

from microbit import *

class HTU21D:
    def __init__(self):
        self.HTDU21D_ADDRESS           = 0x40
        self.TRIGGER_TEMP_MEASURE_HOLD = 0xE3
        self.TRIGGER_HUMD_MEASURE_HOLD = 0xE5
        self.SHIFTED_DIVISOR           = (2**8 + 2**5 + 2**4 + 1)<<15 # 0x988000
        self.READ_USER_REG             = 0xE7
        
    def readTemp(self):
        buf = bytes([self.TRIGGER_TEMP_MEASURE_HOLD])
        i2c.write(self.HTDU21D_ADDRESS, buf) 
                  
        msb, lsb, crc = i2c.read(self.HTDU21D_ADDRESS, 3)
        crcResult = self.__check_crc(msb, lsb, crc)
        
        if crcResult == 0:
            raw = (msb<<8 | lsb) & 0xfffc
            return -46.85 + 175.72 * raw / 65536.0
        else:
            return crcResult
        
    def readHumid(self):
        buf = bytes([self.TRIGGER_HUMD_MEASURE_HOLD])
        i2c.write(self.HTDU21D_ADDRESS, buf) 
                  
        msb, lsb, crc = i2c.read(self.HTDU21D_ADDRESS, 3)
        crcResult = self.__check_crc(msb, lsb, crc)
        
        if crcResult == 0:
            raw = (msb<<8 | lsb) & 0xfffc
            return -6.0 + 125.0 * raw / 65536.0
        else:
            return crcResult
        
    def __check_crc(self, msb, lsb, crc):
        divisor   = self.SHIFTED_DIVISOR
        remainder = msb<<16 | lsb<<8 | crc
        
        for i in range(23, 7, -1):
            if remainder & 1<<i:
                remainder ^= divisor
             
            divisor >>= 1

        if remainder == 0:
            return 0
        else:
            return 999
    
    def readUserRegister(self):
        buf = bytes([self.READ_USER_REG])
        i2c.write(self.HTDU21D_ADDRESS, buf)
        return i2c.read(self.HTDU21D_ADDRESS, 1)
        
if __name__ == "__main__":
    HTU = HTU21D()
    while True:
        print(HTU.readUserRegister()) # ユーザーレジスタの内容を読み出してみる。
        
        temp  = HTU.readTemp()
        humid = HTU.readHumid()
        print("%.1f C, %.1f %%" % (temp, humid))
        sleep(1000)

実行結果:
f:id:ti-nspire:20180613161304p:plain