1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SRF02超音波センサをi2cを使ってpytonで動かした

Posted at

##超音波センサー SRF02
SRF02.png

秋月で2400円くらい http://akizukidenshi.com/catalog/g/gM-06685/
・使用マイコン:16F687-I/ML
・測定範囲:16cm~6m.
・電源:5V(消費電流4mA Typ.)

超音波の距離センサ―の中で精度が結果良い?
これをラズパイにつないで12c通信で制御する

##i2c接続
SRF02_2.png
ピンヘッダーを半田付け
Modeピンはi2cの場合未接続
各々のピンをラズパイに接続
  ラズパイの場合はプルアップ抵抗不要
ターミナルで

sudo i2cdetect -y 1

アドレスを確認デフォルトなら0x70(112)のはず

##制御
pythonでプログラミング

from time import sleep
import smbus

i2c = smbus.SMBus(1)
address = 0x70
SLEEPTIME = 0.5
DELAY = 0.1

if __name__ == '__main__':
    try:
        print ("cancel:CTRL+C")
        cnt = 1
        while True:
            i2c.write_i2c_block_data(0x70,0x00,[0x51])
            time.sleep(DELAY)

            block = i2c.read_i2c_block_data(address,0x00,4)
            distance = (block[2]<<8 | block[3])
            print(int(cnt),distance)
            cnt = cnt + 1
            time.sleep(SLEEPTIME)
             
    except KeyboardInterrupt:
        print("finishing...")
    finally:
        print("finish!!")

###細かく書いていく

i2c.write_i2c_block_data(0x70,0x00,[0x51])

0x51が測定コマンド センチメートル単位
(0x50であればインチ)

time.sleep(DELAY)

測定コマンド後は遅延をかけなければいけない
データシートでは70ms

block = i2c.read_i2c_block_data(address,0x00,4)
distance = (block[2]<<8 | block[3])

Location2がHigh Byte, Location3がLow Byte
8bitずらして結合

##たまに値が飛ぶ
たまに上記プログラムだと値が飛ぶことがある
どうやら測定に用いているsoftwareが異なるよう
location0はReadの際、データシートによると"Software Revision"であり
普段はここが6だがたまに134を返す
値の意味は不明...

    i2c.write_i2c_block_data(0x70,0x00,[0x51])
    time.sleep(DELAYTIME)
    block = i2c.read_i2c_block_data(address,0x00,6)
    if(block[0]==6):
        distance = (block[2]<<8 | block[3])
    else:
        distance = (block[2]<<8 | block[3]) + block[4]

その場合はこちらに変更で問題なし

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?