Processor
【라즈베리파이】 wiringPi Python : 자이로 센서 - 그래프 그리기
작성자 임베디드코리아
작성일26-02-20 00:44
조회103회
댓글0건
▶ 10초 동안 3축 가속도를 읽고, 그래프를 이미지로 저장하는 코드
--->>> 예제 : Gyro_MPU6050-pyplot.py <<<----------------------------
import smbus
import time
import matplotlib.pyplot as plt
# MPU6050 레지스터 주소
power_mgmt_1 = 0x6b
accel_x_out = 0x3b
accel_y_out = 0x3d
accel_z_out = 0x3f
# I2C 버스 생성
bus = smbus.SMBus(1)
# 센서 초기화
def init_sensor():
bus.write_byte_data(0x68, power_mgmt_1, 0)
# 가속도 값 읽기
def read_accel():
def read_word(reg):
high = bus.read_byte_data(0x68, reg)
low = bus.read_byte_data(0x68, reg+1)
val = (high << 8) + low
return val if val < 0x8000 else val - 65536
accel_x = read_word(accel_x_out)
accel_y = read_word(accel_y_out)
accel_z = read_word(accel_z_out)
return accel_x, accel_y, accel_z
def main():
init_sensor()
x_data = []
y_data = []
z_data = []
start_time = time.time()
try:
while time.time() - start_time < 10: # 10초 동안 데이터 읽기
accel_x, accel_y, accel_z = read_accel()
print(f"Accelerometer: X={accel_x}, Y={accel_y}, Z={accel_z}")
# 데이터 저장
x_data.append(accel_x)
y_data.append(accel_y)
z_data.append(accel_z)
time.sleep(0.1) # 0.1초마다 데이터 샘플링
except KeyboardInterrupt:
pass # 키보드인터럽트
# 그래프 그리기
plt.plot(x_data, label='X-Axis')
plt.plot(y_data, label='Y-Axis')
plt.plot(z_data, label='Z-Axis')
plt.xlabel('Time')
plt.ylabel('Acceleration')
plt.legend()
plt.savefig('acceleration_graph.png') # 이미지 파일로 저장
if __name__ == "__main__":
main()