Skip to content

Instantly share code, notes, and snippets.

@kcranley1
Last active August 29, 2015 14:11
Show Gist options
  • Save kcranley1/11c404d7977264476ef6 to your computer and use it in GitHub Desktop.
Save kcranley1/11c404d7977264476ef6 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
#This python program serves a web page which can be accessed via
#local wifi network, giving x and y rotations of the MPU-6050
# Written by Andrew Birkett
# (http://blog.bitify.co.uk/2013/11/3d-opengl-visualisation-of-data-from.html)
# and modified by S&S Dec 2014
import web
import smbus
import math
urls = (
'/', 'index'
)
# Power management registers
power_mgmt_1 = 0x6b
power_mgmt_2 = 0x6c
bus = smbus.SMBus(1) # or bus = smbus.SMBus(0) for pre-Revision 2 boards
address = 0x68 # This is the address value read via the i2cdetect command
def read_byte(adr):
return bus.read_byte_data(address, adr)
def read_word(adr):
high = bus.read_byte_data(address, adr)
low = bus.read_byte_data(address, adr+1)
val = (high << 8) + low
return val
def read_word_2c(adr):
val = read_word(adr)
if (val >= 0x8000):
return -((65535 - val) + 1)
else:
return val
def dist(a,b):
return math.sqrt((a*a)+(b*b))
def get_y_rotation(x,y,z):
radians = math.atan2(x, dist(y,z))
return -math.degrees(radians)
def get_x_rotation(x,y,z):
radians = math.atan2(y, dist(x,z))
return math.degrees(radians)
class index:
def GET(self):
accel_xout = read_word_2c(0x3b)
accel_yout = read_word_2c(0x3d)
accel_zout = read_word_2c(0x3f)
accel_xout_scaled = accel_xout / 16384.0
accel_yout_scaled = accel_yout / 16384.0
accel_zout_scaled = accel_zout / 16384.0
xrot = get_x_rotation(accel_xout_scaled, accel_yout_scaled, accel_zout_scaled)
yrot = get_y_rotation(accel_xout_scaled, accel_yout_scaled, accel_zout_scaled)
# Return angle values to 1 decimal place
return "x-rotation: %.1f" %xrot+" degrees. y-rotation: %.1f" %yrot+" degrees"
if __name__ == "__main__":
# Now wake the 6050 up as it starts in sleep mode
bus.write_byte_data(address, power_mgmt_1, 0)
app = web.application(urls, globals())
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment