-
IMU sensor (MPU-6500) python code with thonnyAutonomous Lawn Mower/Raspberry pi & STM32 2025. 2. 15. 11:55반응형

MPU-6500 문제: MPU-6500은 가속도 값과 자이로 값만 출력한다. 필요한 값은 거리 값. 가속도를 적분해서 속도를 얻고 속도를 적분해서 거리를 얻는 코드는 가속도 값의 편차 때문에 속도와 거리값이 계속 증가한다. 다른 방법을 생각해 봐야겠다.
- MPU-6500과 라즈베리파이 연결

- I2C 연결 방법

- Raspberry Pi Congifuration에서 I2C를 설정하고, 터미널에서 sudo reboot 실행.

- 업데이트가 오래된 경우 또는 smbus, i2c install
sudo apt update
sudo apt install python3-smbus i2c-tools
- I2C 연결하고 default address 확인

- 파이썬 코드
import smbus
import time
# MPU-6500 I2C address
MPU6500_ADDR = 0x68
# Register addresses
PWR_MGMT_1 = 0x6B
ACCEL_XOUT_H = 0x3B
GYRO_XOUT_H = 0x43
# Initialize I2C bus
bus = smbus.SMBus(1) # Use SMBus(0) for older Raspberry Pi models
# Wake up the MPU-6500 (disable sleep mode)
bus.write_byte_data(MPU6500_ADDR, PWR_MGMT_1, 0)
def read_raw_data(addr):
"""Read two bytes of data and convert to signed 16-bit integer."""
high = bus.read_byte_data(MPU6500_ADDR, addr)
low = bus.read_byte_data(MPU6500_ADDR, addr + 1)
value = (high << 8) | low
if value > 32767: # Convert to signed value
value -= 65536
return value
try:
while True:
# Read accelerometer data
accel_x = read_raw_data(ACCEL_XOUT_H) / 16384.0 # Convert to g-force
accel_y = read_raw_data(ACCEL_XOUT_H + 2) / 16384.0
accel_z = read_raw_data(ACCEL_XOUT_H + 4) / 16384.0
# Read gyroscope data
gyro_x = read_raw_data(GYRO_XOUT_H) / 131.0 # Convert to degrees/sec
gyro_y = read_raw_data(GYRO_XOUT_H + 2) / 131.0
gyro_z = read_raw_data(GYRO_XOUT_H + 4) / 131.0
# Print the values
print(f"Accel (g) X:{accel_x:.2f}, Y:{accel_y:.2f}, Z:{accel_z:.2f}")
print(f"Gyro (degree/s) X:{gyro_x:.2f}, Y:{gyro_y:.2f}, Z:{gyro_z:.2f}")
print("-" * 40)
time.sleep(1)
except KeyboardInterrupt:
print("\nStopped by user")
except Exception as e:
print(f"Error: {e}")- 출력 결과

※ 참고자료
https://www.ti.com/lit/an/sbaa565/sbaa565.pdf?ts=1739534033146&ref_url=https%253A%252F%252Fwww.google.com%252F A Basic Guide to I2C (TI 사)
반응형'Autonomous Lawn Mower > Raspberry pi & STM32' 카테고리의 다른 글
라즈베리파이 → STM32 uart를 통한 모터 제어 2 (0) 2025.04.08 STM32cubeIDE와 github 연동 (1) 2025.04.06 DMA를 이용한 2ch ADC (0) 2025.02.08 Systick callback function (1) 2025.02.01 라즈베리파이 RealVNC로 직접 연결 (2) 2025.01.11