You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Python对Arduino UNO连接的MPU6050传感器数据执行FFT的技术问询

How to Perform FFT on MPU6050 Sensor Data in Python

Let's work through this step by step—turning your raw MPU6050 data into meaningful frequency domain results with FFT.

Step 1: Parse Your Raw Data

First, we need to clean up the sample data you provided. Each entry is a triplet of (X, Y, Z) values separated by spaces, so we'll split and convert them into a structured NumPy array for easy computation.

import numpy as np

# Your raw data string (truncated for example; replace with your full dataset)
raw_data = "0.13,0.04,1.03 0.14,0.01,1.02 0.15,-0.04,1.05 0.16,0.02,1.05 0.14,0.01,1.02 0.16,-0.03,1.04 0.15,-0.00,1.04 0.14,0.03,1.02 0.14,0.01,1.03 0.17,0.02,1.05 0.15,0.03,1.03 0.14,0.00,1.02 0.17,-0.02,1.05 0.16,0.01,1.04 0.14,0.02,1.01 0.15,0.00,1.03 0.16,0.03,1.05 0.11,0.03,1.01 0.15,-0.01,1.03 0.16,0.01,1.05 0.14,0.02,1.03 0.13,0.01,1.02 0.15,0.02,1.05"

# Split into individual triplets, then convert each value to float
data_points = [list(map(float, triplet.split(','))) for triplet in raw_data.split()]
sensor_data = np.array(data_points)

# Separate X, Y, Z axis data
x_data = sensor_data[:, 0]
y_data = sensor_data[:, 1]
z_data = sensor_data[:, 2]

Step 2: Define Critical FFT Parameters

FFT depends entirely on your sampling frequency (Fs)—this is how often your Arduino took readings from the MPU6050. For example, if you used delay(20) in your Arduino code, that's a 50Hz sampling rate. Replace Fs with your actual value.

Fs = 50  # Sampling frequency in Hz (adjust to match your Arduino setup)
n_samples = len(x_data)  # Total number of data points

Step 3: Compute FFT and Frequency Spectrum

We'll use NumPy's built-in FFT functions, then process the results to get a readable magnitude spectrum. We'll only keep positive frequencies since FFT outputs are symmetric for real-valued data.

def compute_fft(data, fs, num_samples):
    # Apply a Hanning window to reduce spectral leakage (optional but recommended)
    window = np.hanning(num_samples)
    windowed_data = data * window
    
    # Perform FFT on the windowed data
    fft_result = np.fft.fft(windowed_data)
    
    # Calculate magnitude of the complex FFT result
    magnitude = np.abs(fft_result)
    
    # Generate corresponding frequency axis
    frequencies = np.fft.fftfreq(num_samples, 1/fs)
    
    # Filter to keep only positive frequencies
    positive_mask = frequencies >= 0
    freq_pos = frequencies[positive_mask]
    mag_pos = magnitude[positive_mask]
    
    # Normalize magnitude for easier comparison across axes
    mag_pos = mag_pos / np.max(mag_pos)
    
    return freq_pos, mag_pos

# Compute FFT for each axis
x_freq, x_mag = compute_fft(x_data, Fs, n_samples)
y_freq, y_mag = compute_fft(y_data, Fs, n_samples)
z_freq, z_mag = compute_fft(z_data, Fs, n_samples)

Step 4: Visualize the Frequency Spectra

Let's plot the results using Matplotlib to see the dominant frequencies in each axis:

import matplotlib.pyplot as plt

plt.figure(figsize=(12, 8))

# Plot X axis spectrum
plt.subplot(3, 1, 1)
plt.plot(x_freq, x_mag, color='#1f77b4')
plt.title('X Axis Frequency Spectrum')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Normalized Magnitude')
plt.grid(True, alpha=0.3)

# Plot Y axis spectrum
plt.subplot(3, 1, 2)
plt.plot(y_freq, y_mag, color='#ff7f0e')
plt.title('Y Axis Frequency Spectrum')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Normalized Magnitude')
plt.grid(True, alpha=0.3)

# Plot Z axis spectrum
plt.subplot(3, 1, 3)
plt.plot(z_freq, z_mag, color='#2ca02c')
plt.title('Z Axis Frequency Spectrum')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Normalized Magnitude')
plt.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

Quick Tips for Better Results

  • Double-check Sampling Rate: If your Arduino code uses dynamic delays or interrupts, calculate Fs accurately (e.g., count how many samples you collect per second).
  • Power-of-2 Data Length: For cleaner FFT output, pad your data to a length that's a power of 2 (like 256 or 512) using np.pad() if needed.
  • Windowing: The Hanning window we used reduces artifacts from non-periodic data. If you don't need it, just remove the windowing step.

内容的提问来源于stack exchange,提问作者user9557119

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:04:18