LoginSignup
15
14

More than 5 years have passed since last update.

Raspberry Pi 2で照度センサーTSL2561をシンプルに使うメモ

Last updated at Posted at 2016-02-17

照度センサーTSL2561のI2C対応モジュールを使おうと思って調べると、いろいろ面倒くさかったりします。いくつものPythonモジュールに依存していたり、サンプルプログラムがなぜか何百行にもなってたりして。

http://qiita.com/masato/items/1dd5bed82b19477b45d8
http://shimobayashi.hatenablog.com/entry/2015/07/27/001708

I2C対応のセンサーなら、smbusモジュールだけでシンプルに書けるはず、と思って書いてみました。

SimpleTSL2561.py
#!/usr/bin/python
#
# SimpleTSL2561.py by aike
# licenced under MIT License. 
#

import smbus
import time

class SimpleTSL2561:

    def __init__(self, address=0x39):
    self.bus = smbus.SMBus(1)
    self.address = address
        self.write8(0x80, 0x03)     # 0x03=PowerON 0x00=PowerOFF

    def write8(self, reg, value):
        try:
            self.bus.write_byte_data(self.address, reg, value)
        except IOError, err:
            print "IO Error"

    def readU16(self, reg):
        try:
            result = self.bus.read_word_data(self.address,reg)
            return result
        except IOError, err:
            print "IO Error"
            return 0

    def setParam(self, param):
    #  param   gain   integral
    #    0      x 1   13.7 ms
    #    1      x 1    101 ms
    #    2      x 1    402 ms  (default)
    #    3     x 16   13.7 ms
    #    4     x 16    101 ms
    #    5     x 16    402 ms
    if param >= 3:
        param = param - 3 + 16
    self.write8(0x81, param)

    def readData(self):
        return self.readU16(0xAC)

if __name__ == "__main__":
    tsl = SimpleTSL2561()
    while True:
        print tsl.readData()
        time.sleep(1)

複雑になる原因

なぜサンプルプログラムが複雑になるのか、データシートを読んだりして調べてみました。

TSL2561が多機能

・可視光と赤外線の両方を検知することができる
・感度を1倍と16倍の2種類選ぶことができる
・積分時間を13.7ms/101ms/402msから選ぶことができる

TSL2561のデータ仕様が特殊

・取得データの値がルクスの値と比例しておらず、場合分けした変換係数が必要
・TSL2561には大別してT、FN、CLの系列とCSの系列の2種類あって両者の係数が異なる

そんなわけで、すべてのTSL2561に対して正確なルクス値を取得できるプログラムは、それなりの行数になります。手持ちのハードウェアに対応するだけなら2種類の変換処理は不要で1種類だけで大丈夫です。
そもそも、よくある「暗くなったら電気をつける」といった用途であれば、可視光のみとして、ルクス値の変換処理も省略可能なので、上記のプログラムのように短く書けます。

あと、Adafruit_I2C.pyはsmbusの薄いラッパーなので、なくてもなんとかなります。

15
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
14