Skip to content

Instantly share code, notes, and snippets.

@grodtron
Created February 10, 2013 20:52
Show Gist options
  • Save grodtron/4751014 to your computer and use it in GitHub Desktop.
Save grodtron/4751014 to your computer and use it in GitHub Desktop.
Test of i2c accelerometer + raspberry pi
#!/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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment