Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
i2c UDP Demon Read MPU6050 data and write socket [ USAGE: python i2cUDPMPU6050.py '127.0.0.1' 5005 1 'N' ]
#!/usr/bin/python
import smbus
import math
import socket
import sys
import time
if len(sys.argv) < 4:
sys.exit('Usage: %s IPADDRESS PORT ID_BUS_I2C' % sys.argv[0])
UDP_IP = str(sys.argv[1])
UDP_PORT = int(sys.argv[2])
ID_BUS = int(sys.argv[3])
DEBUG = str(sys.argv[4])
MESSAGE = ""
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
power_mgmt_1 = 0x6b
power_mgmt_2 = 0x6c
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)
bus = smbus.SMBus(ID_BUS)
address = 0x68
while True:
bus.write_byte_data(address, power_mgmt_1, 0)
gyro_xout = read_word_2c(0x43)
gyro_yout = read_word_2c(0x45)
gyro_zout = read_word_2c(0x47)
MESSAGE = str(gyro_xout)+","+str(gyro_yout)+","+str(gyro_zout)+"|";
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
MESSAGE = MESSAGE + str(accel_xout)+","+str(accel_yout)+","+str(accel_zout)+"|";
MESSAGE = MESSAGE + str(accel_xout_scaled)+","+str(accel_yout_scaled)+","+str(accel_zout_scaled);
if DEBUG == "S":
print MESSAGE
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.