개발자/라즈베리파이4

Raspberry Pi와 인터페이싱 MPU6050 (가속도계 + 자이로 스코프)

지구빵집 2020. 11. 30. 10:20
반응형

 

Raspberry Pi와 인터페이싱 MPU6050 (가속도계 + 자이로 스코프) 

 

나 이렇게 살아도 되는 건지 모르겠네. 일이 너무 재미있어. 밤에 잠들기도 싫고, 아침에는 눈이 막 번쩍 떠지고, 일을 하면 할수록 재미있네. 낙엽 지고 비가 쏟아져도 눈길 한번 안 주네. 한 가지 일을 하다 보면 곁가지로 나오는 일이 연관되어 다른 일이 생기니 정신없이 재미있고, 또 그게 관계된 일이 더욱 재미있어지고 미친 듯이 돌고 도니 어쩜 좋냐. 도대체 왜 이런 저주가 나에게 온 건지 모르겠네. :)

 

소개

 

  • MPU6050 센서 모듈은 통합 6 축 모션 추적 장치입니다.
  • 3 축 자이로 스코프, 3 축 가속도계, 디지털 모션 프로세서 및 온도 센서가 모두 단일 IC에 있습니다.
  • 보조 I2C 버스를 사용하여 3 축 자력계 또는 압력 센서와 같은 다른 센서의 입력을 받을 수 있습니다.
  • 외부 3 축 자력계를 연결하면 완전한 9 축 Motion Fusion 출력을 제공할 수 있습니다.
  • 마이크로 컨트롤러는 I2C 통신 프로토콜을 사용하여이 모듈과 통신 할 수 있습니다. I2C 통신을 사용하여 특정 레지스터의 주소에서 값을 읽어서 다양한 매개 변수를 찾을 수 있습니다.
  • X, Y 및 Z 축을 따라 판독하는 자이로 스코프 및 가속도계는 2의 보수 형태로 제공됩니다.
  • 자이로 스코프 판독 값은 초당도 (dps) 단위입니다. 가속도계 판독 값은 g 단위입니다. 

 

MPU6050 센서 모듈 및 사용 방법에 대한 자세한 내용은 센서 및 모듈 섹션의 MPU6050 센서 모듈 항목을 참조하십시오 .

 

Raspberry Pi를 사용하여 MPU6050을 인터페이스 하려면 Raspberry Pi의 I2C 프로토콜이 켜져 있는지 확인해야 합니다. 따라서 MPU6050을 raspberry Pi와 인터페이스 하기 전에 Raspberry Pi I2C를 참조할 수 있는 Raspberry Pi에서 몇 가지 I2C 구성을 만들어야 합니다.

 

Raspberry Pi에서 I2C를 구성한 후 Raspberry Pi를 MPU6050과 인터페이스 해 보겠습니다.

 

 

인터페이스 다이어그램 

 

Raspberry Pi와 인터페이스하는 MPU6050. 참고 1 링크

 

여기에서는 MPU6050 모듈을 Raspberry Pi와 인터페이스 하여 자이로 스코프 및 가속도계 값을 읽고 인쇄합니다.

 

Python 및 C 언어를 사용하여 MPU6050 모듈을 Raspberry Pi와 인터페이스 할 수 있습니다. MPU6050 모듈에서 읽은 단말기에 가속도계와 자이로 스코프 값을 표시합니다.

 

Raspberry Pi에서 자주 사용되는 Python 기반 I2C 함수의 경우 Raspberry Pi 용 Python 기반 I2C 함수를 참조할 수 있습니다.

 

 

Python 프로그램 

 

'''
        Read Gyro and Accelerometer by Interfacing Raspberry Pi with MPU6050 using Python
	http://www.electronicwings.com
'''
import smbus			#import SMBus module of I2C
from time import sleep          #import

#some MPU6050 Registers and their Address
PWR_MGMT_1   = 0x6B
SMPLRT_DIV   = 0x19
CONFIG       = 0x1A
GYRO_CONFIG  = 0x1B
INT_ENABLE   = 0x38
ACCEL_XOUT_H = 0x3B
ACCEL_YOUT_H = 0x3D
ACCEL_ZOUT_H = 0x3F
GYRO_XOUT_H  = 0x43
GYRO_YOUT_H  = 0x45
GYRO_ZOUT_H  = 0x47


def MPU_Init():
	#write to sample rate register
	bus.write_byte_data(Device_Address, SMPLRT_DIV, 7)
	
	#Write to power management register
	bus.write_byte_data(Device_Address, PWR_MGMT_1, 1)
	
	#Write to Configuration register
	bus.write_byte_data(Device_Address, CONFIG, 0)
	
	#Write to Gyro configuration register
	bus.write_byte_data(Device_Address, GYRO_CONFIG, 24)
	
	#Write to interrupt enable register
	bus.write_byte_data(Device_Address, INT_ENABLE, 1)

def read_raw_data(addr):
	#Accelero and Gyro value are 16-bit
        high = bus.read_byte_data(Device_Address, addr)
        low = bus.read_byte_data(Device_Address, addr+1)
    
        #concatenate higher and lower value
        value = ((high << 8) | low)
        
        #to get signed value from mpu6050
        if(value > 32768):
                value = value - 65536
        return value


bus = smbus.SMBus(1) 	# or bus = smbus.SMBus(0) for older version boards
Device_Address = 0x68   # MPU6050 device address

MPU_Init()

print (" Reading Data of Gyroscope and Accelerometer")

while True:
	
	#Read Accelerometer raw value
	acc_x = read_raw_data(ACCEL_XOUT_H)
	acc_y = read_raw_data(ACCEL_YOUT_H)
	acc_z = read_raw_data(ACCEL_ZOUT_H)
	
	#Read Gyroscope raw value
	gyro_x = read_raw_data(GYRO_XOUT_H)
	gyro_y = read_raw_data(GYRO_YOUT_H)
	gyro_z = read_raw_data(GYRO_ZOUT_H)
	
	#Full scale range +/- 250 degree/C as per sensitivity scale factor
	Ax = acc_x/16384.0
	Ay = acc_y/16384.0
	Az = acc_z/16384.0
	
	Gx = gyro_x/131.0
	Gy = gyro_y/131.0
	Gz = gyro_z/131.0
	

	print ("Gx=%.2f" %Gx, u'\u00b0'+ "/s", "\tGy=%.2f" %Gy, u'\u00b0'+ "/s", "\tGz=%.2f" %Gz, u'\u00b0'+ "/s", "\tAx=%.2f g" %Ax, "\tAy=%.2f g" %Ay, "\tAz=%.2f g" %Az) 	
	sleep(1)

 

C 프로그램

 

여기에서는 WiringPi C 라이브러리를 사용하여 MPU6050 모듈에서 데이터를 읽습니다. 라즈베리파이에 wiringPi 라이브러리를 설치하고 사용하는 방법은 참고 2번 링크를 확인하시시오. 

 

/*
	MPU6050 Interfacing with Raspberry Pi
	http://www.electronicwings.com
*/

#include <wiringPiI2C.h>
#include <stdlib.h>
#include <stdio.h>
#include <wiringPi.h>

#define Device_Address 0x68	/*Device Address/Identifier for MPU6050*/

#define PWR_MGMT_1   0x6B
#define SMPLRT_DIV   0x19
#define CONFIG       0x1A
#define GYRO_CONFIG  0x1B
#define INT_ENABLE   0x38
#define ACCEL_XOUT_H 0x3B
#define ACCEL_YOUT_H 0x3D
#define ACCEL_ZOUT_H 0x3F
#define GYRO_XOUT_H  0x43
#define GYRO_YOUT_H  0x45
#define GYRO_ZOUT_H  0x47

int fd;

void MPU6050_Init(){
	
	wiringPiI2CWriteReg8 (fd, SMPLRT_DIV, 0x07);	/* Write to sample rate register */
	wiringPiI2CWriteReg8 (fd, PWR_MGMT_1, 0x01);	/* Write to power management register */
	wiringPiI2CWriteReg8 (fd, CONFIG, 0);		/* Write to Configuration register */
	wiringPiI2CWriteReg8 (fd, GYRO_CONFIG, 24);	/* Write to Gyro Configuration register */
	wiringPiI2CWriteReg8 (fd, INT_ENABLE, 0x01);	/*Write to interrupt enable register */

	} 
short read_raw_data(int addr){
	short high_byte,low_byte,value;
	high_byte = wiringPiI2CReadReg8(fd, addr);
	low_byte = wiringPiI2CReadReg8(fd, addr+1);
	value = (high_byte << 8) | low_byte;
	return value;
}

void ms_delay(int val){
	int i,j;
	for(i=0;i<=val;i++)
		for(j=0;j<1200;j++);
}

int main(){
	
	float Acc_x,Acc_y,Acc_z;
	float Gyro_x,Gyro_y,Gyro_z;
	float Ax=0, Ay=0, Az=0;
	float Gx=0, Gy=0, Gz=0;
	fd = wiringPiI2CSetup(Device_Address);   /*Initializes I2C with device Address*/
	MPU6050_Init();		                 /* Initializes MPU6050 */
	
	while(1)
	{
		/*Read raw value of Accelerometer and gyroscope from MPU6050*/
		Acc_x = read_raw_data(ACCEL_XOUT_H);
		Acc_y = read_raw_data(ACCEL_YOUT_H);
		Acc_z = read_raw_data(ACCEL_ZOUT_H);
		
		Gyro_x = read_raw_data(GYRO_XOUT_H);
		Gyro_y = read_raw_data(GYRO_YOUT_H);
		Gyro_z = read_raw_data(GYRO_ZOUT_H);
		
		/* Divide raw value by sensitivity scale factor */
		Ax = Acc_x/16384.0;
		Ay = Acc_y/16384.0;
		Az = Acc_z/16384.0;
		
		Gx = Gyro_x/131;
		Gy = Gyro_y/131;
		Gz = Gyro_z/131;
		
		printf("\n Gx=%.3f °/s\tGy=%.3f °/s\tGz=%.3f °/s\tAx=%.3f g\tAy=%.3f g\tAz=%.3f g\n",Gx,Gy,Gz,Ax,Ay,Az);
		delay(500);
		
	}
	return 0;
}

 

MPU6050 출력 출력 창에 아래 언급된 모든 값이 표시됩니다.

  • Gx =도 / 초 단위의 자이로 X 축 데이터
  • Gy =도 / 초 단위의 자이로 Y 축 데이터
  • Gz =도 / 초 단위의 자이로 Z 축 데이터
  • Ax = 가속도계 X 축 데이터 (g)
  • Ay = 가속도계 Y 축 데이터 (g)
  • Az = 가속도계 Z 축 데이터 (g) 

 

출력 결과 이미지 출처 참고1번 링크

 

참고:

1. MPU6050 (Accelerometer+Gyroscope) Interfacing with Raspberry Pi 

2. WiringPi C 라이브러리 사용법 

 

아래는 참고 1번 사이트에서 제공하는 문서 링크들인데 한결같이 아름답고 멋져 보이는 주제다. 이런 거 가져다 포스팅 안 하면 벌 받는데 틈틈이 옮겨야겠다.

 

Raspberry Pi와 인터페이싱하는 GPS 모듈

Raspberry Pi와 인터페이싱하는 MPU6050 (가속도계 + 자이로 스코프)

Raspberry Pi와 인터페이싱하는 3 축 자력계 HMC5883L

Raspberry Pi와 DHT11 인터페이스

Raspberry Pi와 Nokia5110 디스플레이 인터페이스

Python을 사용하는 Raspberry Pi와 Pi 카메라 모듈 인터페이스

Python을 사용하여 Raspberry Pi와 상호 작용하는 PIR 모션 센서

Raspberry Pi와의 스테퍼 모터 인터페이스 

 

 

자기 싫다. 포스팅도 더 해야 하고, 글도 쓰고, time about 영화도 봐야 하고, 서평 쓸 책도 몇 권 있는데 3시에는 자야 내일 또 노는데 아오~~~ :)

 

 

 

 

반응형