기본 콘텐츠로 건너뛰기

[BBAir] [활용기] IMU(MPU6050) 값 읽어오기(raw data) : I2C를 활용한

[BBAir] [활용기] IMU(MPU6050) 값 읽어오기(raw data) : I2C를 활용한

"" "This program handles the communication over I2C

between a Raspberry Pi and a MPU-6050 Gyroscope / Accelerometer combo.

Made by: MrTijn/Tijndagamer

Released under the MIT License

Copyright 2015

" ""

import smbus

from time import sleep

class MPU6050:

# Global Variables

GRAVITIY_MS2 = 9. 80665

address = None

bus = smbus.SMBus( 1 )

# Scale Modifiers

ACCEL_SCALE_MODIFIER_2G = 16384. 0

ACCEL_SCALE_MODIFIER_4G = 8192. 0

ACCEL_SCALE_MODIFIER_8G = 4096. 0

ACCEL_SCALE_MODIFIER_16G = 2048. 0

GYRO_SCALE_MODIFIER_250DEG = 131. 0

GYRO_SCALE_MODIFIER_500DEG = 65. 5

GYRO_SCALE_MODIFIER_1000DEG = 32. 8

GYRO_SCALE_MODIFIER_2000DEG = 16. 4

# Pre-defined ranges

ACCEL_RANGE_2G = 0x00

ACCEL_RANGE_4G = 0x08

ACCEL_RANGE_8G = 0x10

ACCEL_RANGE_16G = 0x18

GYRO_RANGE_250DEG = 0x00

GYRO_RANGE_500DEG = 0x08

GYRO_RANGE_1000DEG = 0x10

GYRO_RANGE_2000DEG = 0x18

# MPU-6050 Registers

PWR_MGMT_1 = 0x6B

PWR_MGMT_2 = 0x6C

SELF_TEST_X = 0x0D

SELF_TEST_Y = 0x0E

SELF_TEST_Z = 0x0F

SELF_TEST_A = 0x10

ACCEL_XOUT0 = 0x3B

ACCEL_XOUT1 = 0x3C

ACCEL_YOUT0 = 0x3D

ACCEL_YOUT1 = 0x3E

ACCEL_ZOUT0 = 0x3F

ACCEL_ZOUT1 = 0x40

TEMP_OUT0 = 0x41

TEMP_OUT1 = 0x42

GYRO_XOUT0 = 0x43

GYRO_XOUT1 = 0x44

GYRO_YOUT0 = 0x45

GYRO_YOUT1 = 0x46

GYRO_ZOUT0 = 0x47

GYRO_ZOUT1 = 0x48

ACCEL_CONFIG = 0x1C

GYRO_CONFIG = 0x1B

def __init__(self, address):

self.address = address

# Wake up the MPU-6050 since it starts in sleep mode

self.bus.write_byte_data(self.address, self.PWR_MGMT_1, 0x00 )

# I2C communication methods

def read_i2c_word(self, register):

"" "Read two i2c registers and combine them.

register -- the first register to read from.

Returns the combined read results.

" ""

# Read the data from the registers

high = self.bus.read_byte_data(self.address, register)

low = self.bus.read_byte_data(self.address, register + 1 )

value = (high < < 8 ) + low

if (value > = 0x8000 ):

return - (( 65535 - value) + 1 )

else :

return value

# MPU-6050 Methods

def get_temp(self):

"" "Reads the temperature from the onboard temperature sensor of the MPU-6050.

Returns the temperature in degrees Celcius.

" ""

# Get the raw data

raw_temp = self.read_i2c_word(self.TEMP_OUT0)

# Get the actual temperature using the formule given in the

# MPU-6050 Register Map and Descriptions revision 4.2, page 30

actual_temp = (raw_temp / 340 ) + 36. 53

# Return the temperature

return actual_temp

def set_accel_range(self, accel_range):

"" "Sets the range of the accelerometer to range.

accel_range -- the range to set the accelerometer to. Using a

pre-defined range is advised.

" ""

# First change it to 0x00 to make sure we write the correct value later

self.bus.write_byte_data(self.address, self.ACCEL_CONFIG, 0x00 )

# Write the new range to the ACCEL_CONFIG register

self.bus.write_byte_data(self.address, self.ACCEL_CONFIG, accel_range)

def read_accel_range(self, raw = False):

"" "Reads the range the accelerometer is set to.

If raw is True, it will return the raw value from the ACCEL_CONFIG

register

If raw is False, it will return an integer: -1, 2, 4, 8 or 16. When it

returns -1 something went wrong.

" ""

# Get the raw value

raw_data = self.bus.read_byte_data(self.address, self.ACCEL_CONFIG)

if raw is True:

return raw_data

elif raw is False:

if raw_data = = self.ACCEL_RANGE_2G:

return 2

elif raw_data = = self.ACCEL_RANGE_4G:

return 4

elif raw_data = = self.ACCEL_RANGE_8G:

return 8

elif raw_data = = self.ACCEL_RANGE_16G:

return 16

else :

return - 1

def get_accel_data(self, g = False):

"" "Gets and returns the X, Y and Z values from the accelerometer.

If g is True, it will return the data in g

If g is False, it will return the data in m/s^2

Returns a dictionary with the measurement results.

" ""

# Read the data from the MPU-6050

x = self.read_i2c_word(self.ACCEL_XOUT0)

y = self.read_i2c_word(self.ACCEL_YOUT0)

z = self.read_i2c_word(self.ACCEL_ZOUT0)

accel_scale_modifier = None

accel_range = self.read_accel_range(True)

if accel_range = = self.ACCEL_RANGE_2G:

accel_scale_modifier = self.ACCEL_SCALE_MODIFIER_2G

elif accel_range = = self.ACCEL_RANGE_4G:

accel_scale_modifier = self.ACCEL_SCALE_MODIFIER_4G

elif accel_range = = self.ACCEL_RANGE_8G:

accel_scale_modifier = self.ACCEL_SCALE_MODIFIER_8G

elif accel_range = = self.ACCEL_RANGE_16G:

accel_scale_modifier = self.ACCEL_SCALE_MODIFIER_16G

else :

print ( "Unkown range - accel_scale_modifier set to self.ACCEL_SCALE_MODIFIER_2G" )

accel_scale_modifier = self.ACCEL_SCALE_MODIFIER_2G

x = x / accel_scale_modifier

y = y / accel_scale_modifier

z = z / accel_scale_modifier

if g is True:

return { 'x' : x, 'y' : y, 'z' : z}

elif g is False:

x = x * self.GRAVITIY_MS2

y = y * self.GRAVITIY_MS2

z = z * self.GRAVITIY_MS2

return { 'x' : x, 'y' : y, 'z' : z}

def set_gyro_range(self, gyro_range):

"" "Sets the range of the gyroscope to range.

gyro_range -- the range to set the gyroscope to. Using a pre-defined

range is advised.

" ""

# First change it to 0x00 to make sure we write the correct value later

self.bus.write_byte_data(self.address, self.GYRO_CONFIG, 0x00 )

# Write the new range to the ACCEL_CONFIG register

self.bus.write_byte_data(self.address, self.GYRO_CONFIG, gyro_range)

def read_gyro_range(self, raw = False):

"" "Reads the range the gyroscope is set to.

If raw is True, it will return the raw value from the GYRO_CONFIG

register.

If raw is False, it will return 250, 500, 1000, 2000 or -1. If the

returned value is equal to -1 something went wrong.

" ""

# Get the raw value

raw_data = self.bus.read_byte_data(self.address, self.GYRO_CONFIG)

if raw is True:

return raw_data

elif raw is False:

if raw_data = = self.GYRO_RANGE_250DEG:

return 250

elif raw_data = = self.GYRO_RANGE_500DEG:

return 500

elif raw_data = = self.GYRO_RANGE_1000DEG:

return 1000

elif raw_data = = self.GYRO_RANGE_2000DEG:

return 2000

else :

return - 1

def get_gyro_data(self):

"" "Gets and returns the X, Y and Z values from the gyroscope.

Returns the read values in a dictionary.

" ""

# Read the raw data from the MPU-6050

x = self.read_i2c_word(self.GYRO_XOUT0)

y = self.read_i2c_word(self.GYRO_YOUT0)

z = self.read_i2c_word(self.GYRO_ZOUT0)

gyro_scale_modifier = None

gyro_range = self.read_gyro_range(True)

if gyro_range = = self.GYRO_RANGE_250DEG:

gyro_scale_modifier = self.GYRO_SCALE_MODIFIER_250DEG

elif gyro_range = = self.GYRO_RANGE_500DEG:

gyro_scale_modifier = self.GYRO_SCALE_MODIFIER_500DEG

elif gyro_range = = self.GYRO_RANGE_1000DEG:

gyro_scale_modifier = self.GYRO_SCALE_MODIFIER_1000DEG

elif gyro_range = = self.GYRO_RANGE_2000DEG:

gyro_scale_modifier = self.GYRO_SCALE_MODIFIER_2000DEG

else :

print ( "Unkown range - gyro_scale_modifier set to self.GYRO_SCALE_MODIFIER_250DEG" )

gyro_scale_modifier = self.GYRO_SCALE_MODIFIER_250DEG

x = x / gyro_scale_modifier

y = y / gyro_scale_modifier

z = z / gyro_scale_modifier

return { 'x' : x, 'y' : y, 'z' : z}

def get_all_data(self):

"" "Reads and returns all the available data." ""

temp = get_temp()

accel = get_accel_data()

gyro = get_gyro_data()

return [accel, gyro, temp]

# Create a new instance of the MPU6050 class

sensor = MPU6050( 0x68 )

while True:

accel_data = sensor.get_accel_data()

gyro_data = sensor.get_gyro_data()

temp = sensor.get_temp()

print ( "Accelerometer data" )

print ( "x: " + str (accel_data[ 'x' ]))

print ( "y: " + str (accel_data[ 'y' ]))

print ( "z: " + str (accel_data[ 'z' ]))

print ( "Gyroscope data" )

print ( "x: " + str (gyro_data[ 'x' ]))

print ( "y: " + str (gyro_data[ 'y' ]))

print ( "z: " + str (gyro_data[ 'z' ]))

print ( "" )

from http://openmaker.tistory.com/42 by ccl(S) rewrite - 2020-03-06 09:54:35

댓글

이 블로그의 인기 게시물

[Angular] Router 라우터 정리

[Angular] Router 라우터 정리 Angular2 버전 이후를 기준으로 정리한 글입니다. 라우터는 URL을 사용하여 특정 영역에 어떤 뷰를 보여 줄지 결정하는 기능을 제공한다. 전통적인 서버사이드 렌더링을 하는 웹 사이트는 주소가 바뀔 때마다 서버에 전체 페이지를 요청하고 전체 페이지를 화면에 렌더링한다. 매 요청시 전체 페이지를 새로 랜더링하는 것은 비효율적이기 때문에 라우터를 이용하여 필요한 부분만 랜더링을 한다면 효율적일 것이다. 라우터는 URL에 해당하는 컴포넌트를 화면에 노출하고 네비게이션을 할 수 있는 기능을 가지고 있다. Router 구성 요소 Router – 라우터를 구현하는 객체이다. Navigate() 함수와 navigateByUrl() 함수를 사용하여 경로를 이동할 수 있다. RouterOulet – 라우터가 컴포넌트를 태그에 렌더링하는 영역을 구현하는 Directive이다. Routes – 특정 URL에 연결되는 컴포넌트를 지정하는 배열이다. RouterLink – HTML의 앵커 태그는 브라우저의 URL 주소를 변경하는 것이다. 앵귤러에서 RouterLink를 사용하면 라우터를 통해 렌더링할 컴포넌트를 변경할 수 있다. ActivatedRoute – 현재 동작하는 라우터 인스턴스 객체이다. Router 설정 라우터를 사용하기 위해서는 먼저 Router 모듈을 import 해야 한다. import { RouterModule, Routes } from '@angular/router'; 라우터에서 컴포넌트는 고유의 URL과 매칭된다. URL과 컴포넌트는 아래와 같이 Routes 객체를 설정하여 지정할 수 있다. 아래의 예에서는 디폴트 path에서는 MainComponent가 노출이 되고 product-list path에서는 ProductListComponent가 노출이 되도록 설정을 한 것을 볼 수 있다. const routes: Routes = [ { pa...

[Angular] Controller

[Angular] Controller Step02_controller.html // angular 모듈 만들기 var myApp = angular.module( "myApp" ,[]); // Ctrl1 이라는 이름의 컨트롤러 만들기 myApp.controller( "Ctrl1" ,[ "$scope" , function ($scope){ $scope. name = "김구라" ; $scope.clicked = function (){ alert ( "버튼을 눌렀네?" ); }; $scope.nums = [ 10 , 20 , 30 , 40 , 50 ]; }]); // Ctrl2 이라는 이름의 컨트롤러 만들기 myApp.controller( "Ctrl2" ,[ "$scope" , function ($scope){ $scope. name = "원숭이" ; $scope.friends = [ {num: 1 , name : "김구라" ,addr: "노량진" }, {num: 2 , name : "해골" ,addr: "행신동" }, {num: 3 , name : "원숭이" ,addr: "동물원" } ]; }]); 내이름은 : {{name}} 눌러보셈 {{tmp}} 너의 이름은 : {{name}} 번호 이름 주소 {{tmp.num}} from http://heekim0719.tistory.com/164 by ccl(A) rewrite - 2020-03-07 09:21:16

JQuery - $ 사용 유형.

JQuery - $ 사용 유형. 최근에 새로운 Javascript 프레임워크와 라이브러리들이 많이 등장했고 시장 점유율 또한 많이 변동 되었다고 한다. 특히 요새 대새는 Angular와 React라고들 한다. 그리고 Jquery 요즘 누가써? Jquery 퇴물이야 등등... 그런 이야기들을 종종 찾아볼 수 있는데, 유행은 돌고 돌듯이 결국 Jquery가 몰락할 일은 없다고 생각하는 바, 묵묵히 Jquery를 고집하기로 한다...ㅎㅎ 먼저 Jquery 교과서랄까.. 기본 문법을 배울 수 있는 링크를 걸어둔다. https://www.w3schools.com/jquery 여기서 기초들을 다 익힐 수 있다. 프로그래밍 문법을 한번이라도 봤다면 + - * / 같은 연산 while, for 등은 다 비슷하기 때문에 $ 사용법만 잘 알면 될 것 같다. $ syntax 사용유형 일단 기본적으로 $는 JQuery에서 미리 정해놓은 변수 값이다. : JQueryStatic 1. $( ) : JQueryObject 가장 많이 사용하는 형태이다. 괄호 안에 들어 갈 수 있는 것들은 클래스 이름, 아이디, 셀렉터 등이다. 예를 들어 $('p')이면 현재 html 페이지에 있는 모든 를 JqueryObject로 가져오겠다는 것이다. hide()는 제이쿼리 메서드이다. $('p')는 제이쿼리 오브젝트이기 때문에 제이쿼리 메서드를 사용할 수 있다. 그중의 하나인 hide()를 사용해 보았다. 결과이다. 에는 스타일이 적용이 되었다. 해당 태그에는 jquery의 메서드가 적용이 된 것을 확인할 수 있다. 2. $.함수 : 플러그인 개발 또는 기본 전역함수 플러그인을 개발 할 때나 Jquery가 갖고 있는 기본 전역함수들을 사용할 때 쓴다. 전역함수에는 여러개가 있는데 그중에 개인적으로 많이 쓰는 것은 $.ajax({}), $.each({}) 등이 있다. 이 함수들의 사용방법은 따...