Advertisement
Guest User

MaixPyでADT7410を使う

a guest
Feb 1st, 2020
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.44 KB | None | 0 0
  1. from machine import I2C
  2. import utime
  3.  
  4.  
  5. class adt7410_class:
  6.  
  7.     def __init__(self, i2c, i2c_address):
  8.         self.i2c = i2c
  9.         self.i2c_address = i2c_address
  10.         self.reset()
  11.  
  12.     def reset(self):
  13.         # リセット
  14.         self.i2c.writeto(self.i2c_address, bytearray([0x2f]))
  15.         # リセット後、動作するまでに200ms必要
  16.         wait01 = utime.ticks_us()
  17.         while True:
  18.             utime.sleep(200/1000000)
  19.             if (utime.ticks_us() - wait01) >= 200:
  20.                 break;
  21.  
  22.     def readdata(self):
  23.         # 16bit 1-shot
  24.         data = [0xa0]
  25.  
  26.         # 13bit 1-shot
  27.         #data = [0x20]
  28.  
  29.         self.i2c.writeto_mem(self.i2c_address, 0x03, bytearray(data))
  30.         read_wait_time = utime.ticks_ms()
  31.         read_wait = 22
  32.         utime.sleep(0.01*read_wait)
  33.  
  34.         # 気温データを読み取りできる状態になるまで待機
  35.         # (ステータスレジスタのbit7が0になると準備OK)
  36.         count001 = 0
  37.         while True:
  38.             wait01 = utime.ticks_ms()
  39.             while True:
  40.                 utime.sleep(0.01)
  41.                 if (utime.ticks_ms() - wait01) >= 10:
  42.                     break;
  43.             # ステータスレジスタの読み込み
  44.             status_reg = bytearray(self.i2c.readfrom_mem(self.i2c_address, 0x02, 1))
  45.             if count001 >= 500:
  46.                 break
  47.             if ((int(status_reg[0]) >> 7) & 1) == 0:
  48.                 break
  49.             count001 += 1
  50.         status_str = "status=0x{0:02x}, count001={1:d}, {2:d} ms".format(status_reg[0], count001, (utime.ticks_ms()-read_wait_time))
  51.         #print(status_str)
  52.  
  53.         # 気温データの読み取り
  54.         temp_raw = bytearray(self.i2c.readfrom_mem(self.i2c_address, 0, 2))
  55.         #print("temp_raw = 0x{0:02x}, 0x{1:02x}".format(temp_raw[0], temp_raw[1]))
  56.  
  57.         # 16bitの計算
  58.         temp = ((temp_raw[0]) << 8) | (temp_raw[1])
  59.         if temp >= 32768:
  60.             temp = temp - 65536
  61.         temp = temp / 128.0
  62.  
  63.         # 13bitの計算
  64.         #temp = (((temp_raw[0]) << 8) | (temp_raw[1])) >> 3
  65.         #if temp >= 4096:
  66.         #    temp - 8192
  67.         #temp = temp / 16
  68.  
  69.         return temp
  70.  
  71.  
  72.  
  73. if __name__ == '__main__':
  74.     i2c = I2C(I2C.I2C0, freq=400000, scl=30, sda=31)
  75.     adt7410_01 = adt7410_class(i2c, 0x48)
  76.     while True:
  77.         temp = adt7410_01.readdata()
  78.         print ("{0:.4f} ℃".format(temp))
  79.         time.sleep(5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement