温湿度センサー HTU21D / 温度、湿度の測定と CRC とを組み合わせる / micro:bit / MicroPython

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           = 0x988000
        
    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
        print(remainder) #### 確認のため CRC の結果を表示する。###
        if remainder == 0:
            return 0
        else:
            return 999
        
if __name__ == "__main__":
    HTU = HTU21D()
    while True:
        temp  = HTU.readTemp()
        humid = HTU.readHumid()
        print("%.1f C, %.1f %%" % (temp, humid))
        sleep(1000)

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