Skip to content

Instantly share code, notes, and snippets.

@grodtron
Created February 10, 2013 20:52

Revisions

  1. grodtron created this gist Feb 10, 2013.
    45 changes: 45 additions & 0 deletions i2c_accelerometer.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    #!/usr/bin/python

    import smbus
    import time

    # Plot a graph of the z-axis acceleration using a Raspberry Pi connected
    # to one of these: http://www.pololu.com/catalog/product/1250
    # Datasheet: http://www.pololu.com/file/download/LSM303DLH.pdf?file_id=0J433

    def main():
    bus = smbus.SMBus(1)

    # Power-on the accelerometer, enabling only the z-axis
    bus.write_byte_data(0x18, 0x20, 0x24)

    try:
    while True:
    # get z-axis acceleration
    tilt = bus.read_byte_data(0x18, 0x2D)

    # if it's supposed to be negative
    if tilt > 127:
    # then convert it to the absolute value of the negative value
    tilt = 256 + ~tilt
    positive = False
    else:
    positive = True

    # format and print it
    pos = tilt / 2
    print str(tilt).rjust(6),
    if positive:
    print 65*' ' + '|' + (pos*'#').ljust(65)
    else:
    print (pos*'#').rjust(65) + '|' + 65*' '

    # sleep
    time.sleep(0.1)

    except KeyboardInterrupt:
    # restore default settings
    bus.write_byte_data(0x18, 0x20, 0x07)

    if __name__ == '__main__':
    main()