SRF02 ultrasonic sensor run on pyton using i2c

Ultrasonic sensor SRF02

SRF02.png

About 2400 yen in Akizuki http://akizukidenshi.com/catalog/g/gM-06685/ ・ Microcomputer used: 16F687-I / ML ・ Measurement range: 16cm ~ 6m. ・ Power supply: 5V (current consumption 4mA Typ.)

Is the accuracy good in the ultrasonic distance sensor? Connect this to Raspberry Pi and control it with 12c communication

i2c connection

SRF02_2.png Solder the pin header Mode pin is not connected for i2c Connect each pin to Raspberry Pi No pull-up resistor required for Raspberry Pi At the terminal

sudo i2cdetect -y 1

Check address Should be 0x70 (112) by default

control

Programming with 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!!")

Write in detail

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

0x51 is the measurement command in centimeters (Inches for 0x50)

time.sleep(DELAY)

You have to delay after the measurement command 70ms in the data sheet

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

Location2 is High Byte, Location3 is Low Byte Combine by shifting 8 bits

Sometimes the value flies

Occasionally, the above program may cause the value to jump. Apparently the software used for the measurement is different location0 is "Software Revision" according to the data sheet when reading Usually 6 here, but occasionally returns 134 The meaning of the value is unknown ...

    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]

In that case, there is no problem with changing here

Recommended Posts

SRF02 ultrasonic sensor run on pyton using i2c
Run Yocto on Ubuntu using QEMU.
Run servomotor on Raspberry Pi 3 using python
Try using the temperature sensor (LM75B) on the Raspberry Pi.
[EV3 MicroPython] Distance measurement using DIST-ToF sensor (& I2C communication)