XL%20Ultrasonic%20Sensor%20Iso_200px.jpgThis is a post about how to receive data from a I2CXL-MaxSonar ultrasonic sensor with RPi's GPIO. Maybe this information can be useful to you or it can save you some time. I am happy for some feedback or optimization proposals etc.

 

 

 

The I2CXL-MaxSonar sensor should be connected to the following RPi GPIO Pins (*):

  • [P1-01]  3.3V -> V+ (Pin 6)
  • [P1-03]  I2C0_SDA -> SDA (Pin 4)
  • [P1-05]  I2C0_SCL -> SCL (Pin 5)
  • [P1-09]  GROUND -> GND (Pin 7)

 

Before you are able to receive data from the the ultrasonic sensor you have to make sure that I2C-support is enabled within the RPi Linux system settings. You can check one of my previous posts for instructions how to enable it.

You can use the shell commands i2cset and i2cget to test the functionality of your sensor. The default I2C-Address of the sensor is 0x70. To perform a range measurement you must send the "Take Range Reading” command byte 0x51.

# i2cset -y 1 0x70 0x51
# i2cget -y 1 0x70 0xE1 w
0xfd02

 

A python script can easily be implemented by using the smbus module functions write_byte() and read_word_data(). Finally the two bytes of the returned value need to be swapped because they are received in the wrong byte order.

from smbus import SMBus
from time import sleep

try:
  i2cbus = SMBus(1)
  i2cbus.write_byte(0x70, 0x51)
  sleep(0.12)
  val = i2cbus.read_word_data(0x70, 0xe1)
  print (val >> 8) & 0xff | (val & 0xff), 'cm'
except IOError, err:
  print err

 

The default I2C-Address of the sensor 0x70 can be changed by overwriting the sensors EEPROM. The sensor requires two separate values 0xAA and 0xA5 to be sent in sequence before the final byte sent is used for changing the stored 8-bit I2C-Address. The I2C-Address should not be modified to often because a EEPROM can only be reprogrammed a limited number of times. Changing the I2C-Address may be required if the default address is already in use or if you plan to use multiple I2CXL-MaxSonar sensors connected to one I2C-Bus. Use the shell command i2cdetect -y 1 to display and verify the current (or changed) I2C-Address of the sensor.

from smbus import SMBus

try:
  i2cbus = SMBus(1)
  i2cbus.write_block_data(0x70, 0xe0, [0xAA, 0xA5, 0x71 \<\< 1])
except IOError, err:
  print err

 

Have fun and stay tuned.

 

References:

 

Notes:

  • After you send the "Take Range Reading” command (0x51) the sensor may need 65 - 110 μs to initialize and perform the ultrasonic range measurement
  • The I2CXL-MaxSonar-EZ series (only) supports I2C clock frequencies up to 100kHz

 

(* of course you can use any other 3.3V or GROUND Pin)

E-mail me when people leave their comments –

You need to be a member of diydrones to add comments!

Join diydrones

Comments

  • Very nice introductory article on Raspberry Pi, Python and Sonar.

    We need to get more people able to program both the APM and the PX4 for their own custom uses and right now it is not an easy entry.

This reply was deleted.