기본 콘텐츠로 건너뛰기

[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

댓글

이 블로그의 인기 게시물

(주)편두리 채용 정보: PYUNDOORI에서 핫한 개발자분들을 모십니다.

(주)편두리 채용 정보: PYUNDOORI에서 핫한 개발자분들을 모십니다. - 좋아요 아래와 같은 업무를 훌륭히 감당하실 분을 모십니다.서비스 관련 DB 모델링, DB 최적화 작업서버 & DB 관리Frontend & Backend 인터페이스의 최적화 작업 화합과 성장을 같이! - Angular JS의 경험 - Node.js - javascript 능숙자 - DRMS 사용 능숙자 더 많은 내용은 더 많은 내용은 더팀스 에서 확인하세요! from http://theteams.tistory.com/742 by ccl(A) rewrite - 2020-03-22 12:20:20

[020] 파동함수를 쓰기

[020] 파동함수를 쓰기 [020] 파동함수를 쓰기 [020] 파동함수를 알면 우리가 원하는 뭔가를 알 수 있다고 했는데, 정작 파동을 함수로 쓰는 것은 아직 다루지 않았고, 양자역학 내용을 좀 더 진행하려면 왜 파동이 삼각함수로 써 지는지를 한번은 정리를 해야겠다. 수학이 많이 나올 예정이다. 앞에서 파동함수를 아래 형태로 쓸 수 있다고 했었는데, 왜 이런 형태가 되는지 알아보자. [020-01] 파동함수 사인파의 일반형은 코사인 (cos) 을 이용해 쓰지만, 사인 (sin) 과 코사인은 위상차이만 있는 함수들이고, 우리는 앞으로 사인을 이용해 문제를 풀 예정이라 사인을 이용하기로 한다. 파동함수는 양자역학에서 갑자기 나온 말이 아니고, 원래 파동을 함수의 형태로 쓴 것을 파동함수라고 부른다. 파동-입자 이중성을 가지니까 기존에 파동을 함수의 형태로 쓰던 그 모양을 가져다 쓴 것. 주교재의 16장에 있는 내용이다. [020-02] 펄스 - Pulse 아래와 같이 하나의 진동이 왼쪽에서 오른쪽으로 진행하는 상황을 생각해보자. 시간 t 일 때, 위치 x 의 밧줄의 높이를 y 라 하고, 셋의 관계를 기호로 쓰면, 그러면 아래의 관계가 성립한다. 이게 무슨말이냐면, 시간 t 일 때 위치 x 의 밧줄의 높이 와 시간 0 일 때 위치 x-vt 의 밧줄의 높이가 같다 는 말인데, 그림으로 보면, 왼쪽은 시간 0, 오른쪽은 시간 t 이고, t 일 때 P 의 높이와 0 일 때 높이가 같다는 것. [020-03] 파동을 식으로 써보자. 아래의 파동을 보자. 지금 내용부터는 사인이든 코사인이든 상관없는데, 위 그림이 사인이니까 아래의 식 으로 쓸 수 있다. A는 진폭이고, 주기, 진동수, 파장 같은 값을 아직 모르니까 a 는 아직 정해지지 않은 값 이다. 일반적으로 알고있는 삼각함수는 가로축이 각도 이지만, 우리는 공간을 진행하고 있는 파동을 다루니까 위의 형태로 써진다고 생각하자. x=0 에서 진폭이 ...

[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...