PERIODIC MOTION ANALYSIS WITH FFT (FOURIER TRASFORMATION) BY EMPLOYING ARDUINO FOR DATA CAPTURING



 FFT- Fourier transformation is a mathematical function which is use to convert a time signal data into frequency domain. Today i will share my experience of using Arduino for reading the data and further processing to getting the result in frequency domain, for  further learning about the FFT follow the link

Captured Data

I have analyze a simple spring mass system. The property of the system is as follow.

M = 2 Kg

Spring stiffness K = 116 N/m

we can find it natural frequency directly.

 f = (1/2*pi)*squareroot(K/M)

f  =  1.21 Hz


Experiment setup is shown in the figure a weight of 2 Kg is hanged on the spring with the known stiffness. a MPU 6050 is attached on it with double sided tape. 

Initial displacement is provided to the weight and let the system to oscillate freely.

Test Setup

Analysis of the data perfectly align with the Theoretical results as shown in the graph below. With these results we are now become confident on our system and can further analyze much more complicated system which will we done on up coming blog post.

Results






For this I have use the following Hardware.

  • Arduino UNO
  • Accelerometer - MPU-6050 
  • Jumper Wires

Pin out of the Sensor and Arduino are shown in the image.



The code for Arduino is below

#include <Wire.h>

#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
Adafruit_MPU6050 mpu;

int measurementDuration = 0; // Duration in seconds
unsigned long startTime = 0;
bool isMeasuring = false;

void setup() {
  Serial.begin(9600);

  if (!mpu.begin()) {
    Serial.println("Failed to find MPU6050 device. Please check wiring.");
    while (1);
  }

  Serial.println("MPU6050 found!");

  mpu.setAccelerometerRange(MPU6050_RANGE_2_G);
  mpu.setGyroRange(MPU6050_RANGE_250_DEG);

  Serial.println("Enter the measurement duration in seconds:");
}

void loop() {
  if (Serial.available() > 0) {
    if (!isMeasuring) {
      measurementDuration = Serial.parseInt();
      if (measurementDuration > 0) {
        startTime = millis();
        isMeasuring = true;
        Serial.print("Measuring data for ");
        Serial.print(measurementDuration);
        Serial.println(" seconds...");
      } else {
        Serial.println("Please enter a valid duration in seconds:");
      }
    }
  }

  if (isMeasuring) {
    unsigned long currentTime = millis();
    if ((currentTime - startTime) / 1000 < measurementDuration) {
      sensors_event_t a, g, temp;
      mpu.getEvent(&a, &g, &temp);

      float accelX = a.acceleration.x;
      float accelY = a.acceleration.y;
      float accelZ = a.acceleration.z;

      float gyroX = g.gyro.x;
      float gyroY = g.gyro.y;
      float gyroZ = g.gyro.z;

      Serial.print(accelX); Serial.print(",");
      Serial.print(accelY); Serial.print(",");
      Serial.print(accelZ); Serial.print(",");

      Serial.print(gyroX); Serial.print(",");
      Serial.print(gyroY); Serial.print(",");
      Serial.println(gyroZ);

     // Delay for 1 second
    } else {
      Serial.println("Measurement completed.");
      isMeasuring = false;
      Serial.println("Enter the measurement duration in seconds:");
    }
  }
}

The Arduino code is written such that you need to enter the duration for which you want to record the data. Which can be copied by using putty and paste into the excel or you can even use the dedicated python script for directly recording the data. Here I am also providing the Python script, which you can be use for FFT

Putty can be downloaded from this link.

USING PUTTY.
  • open putty
  • choose serial from given three options of (SSH, serial, other).
  • text proper serial line COM 3 for Arduino Uno and band width.
  • click open.
  • serial terminal will open for further process.

After recording data, you can copy all data from putty and pasting in excel.

For spreading data in various columns in excel. Choose "text to column" from "data" tab.

Now according to sensor orientation column can be chosen for further analysis. The Arduino code is written such that it will print results as X,Y,Z,RX,RY,RZ of the sensor axis.

now come the analysis part now  we can even use a python script for doing so which is given below.

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt


# Set the filename to your Excel file

filename = 'E:/data.xlsx'


# Read the data from the first column of the Excel file

data = pd.read_excel(filename, usecols=[0]).values.flatten()


# Check if the data is successfully loaded

if len(data) == 0:

    raise ValueError('Failed to read data from the Excel file')


# Number of data points

N = len(data)


# Compute the Fourier Transform of the data

Y = np.fft.fft(data)


# Compute the two-sided spectrum P2

P2 = np.abs(Y / N)


# Compute the single-sided spectrum P1 based on P2 and the even-valued signal length N

P1 = P2[:N//2+1]

P1[1:-1] = 2 * P1[1:-1]


# Define the frequency domain f

Fs = 20.93  # Sampling frequency (assumed to be 20.93 Hz, modify as needed)

f = Fs * np.arange(N//2+1) / N


# Plot the single-sided amplitude spectrum

plt.figure()

plt.plot(f, P1)

plt.title('Single-Sided Amplitude Spectrum of Data')

plt.xlabel('f (Hz)')

plt.ylabel('|P1(f)|')

plt.grid(True)


# Save the plot as an image file

plt.savefig('FourierTransformPlot.png')

plt.show()


for running this code you need to install  libraries which you can do by using the below command in command manager

  • pip install pandas numpy matplotlib.
  • pip install openpyxl.

Before running and analyzing the data one of the crucial step is to set the sampling frequency in the python script.

This can be found out through the excel it self.to find the sampling freq divide the recording time in seconds with no of data points and the resulted value is need to be divided by 1 to get the results in Hz which then can be entered into the scripts.  


Comments

  1. This is a great blog post! The information provided is clear and helpful for anyone looking to understand and implement FFT using Arduino. The step-by-step explanation of the experiment, from setting up the hardware to analyzing the data, makes it easy to follow along. I particularly appreciate the inclusion of the Arduino code and the Python script, which will be very useful for beginners. Overall, it's a nice and helpful resource for anyone interested in frequency domain analysis. Keep up the good work!

    ReplyDelete

Post a Comment