If you want to use an ultrasonic in python with the I2C command (SRF2 or SRF08 for example) , you must create 2 files.
I create a filename directory : Grove_i2c_ultrasonic
i create a new file: grove_i2c_ultrasonic.py
the code is:
import time,sys
import RPi.GPIO as GPIO
import smbus
use the bus that matches your raspi version
rev = GPIO.RPI_REVISION
if rev == 2 or rev == 3:
bus = smbus.SMBus(1)
else:
bus = smbus.SMBus(0)
class ULTRA:
address = None
REG_ADDR_CONFIG = 0x00
REG_ADDR_RESULT = 0x02
CMD_ULTRA_INCHES = 0x50
CMD_ULTRA_CM = 0x51
CMD_ULTRA_TIMER = 0x52
def __init__(self, address=0x70):
self.address=address
self.command=command
bus.write_byte_data(self.address, self.REG_ADDR_CONFIG,0x20)
def ultra_read(self, address=0x70,command=0x51):
self.address=address
self.command=command
bus.write_byte_data(self.address, self.REG_ADDR_CONFIG, self.command)
time.sleep(.07)
data=bus.read_i2c_block_data(self.address, self.REG_ADDR_RESULT, 2)
raw_val=(data[0]<<8) | data[1]
return raw_val
if name == “main”:
ultra= ULTRA()
while True:
print(ultra.ultra_read(0x70,0x51))
time.sleep(.5)
After i create a new file: i2c_ultrasonic_example.py
the code is:
import grove_i2c_ultrasonic
import time
You can initialize with a different address too: grove_i2c_ultrasonic.ULTRA(address=0x70)
ultrasonic= grove_i2c_ultrasonic.ULTRA()
while True:
#Print the 12 bit value from the I2C ADC
print(ultrasonic.ultra_read(0x70,0x51))
time.sleep(.5)
And now you can use a SRF02 or SRF08