Advertisement
Guest User

Raspberry Pi picoでI2C接続の温度センサーADT7410をMicroPythonで使う

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