0% found this document useful (0 votes)
7 views8 pages

Arduino Data Filtering

The document provides a comprehensive guide for collecting live data from an Arduino, applying Kalman and Savitzky-Golay filters, and plotting the results in MATLAB. It includes Arduino code for reading sensor values, MATLAB code for real-time filtering and visualization, and detailed steps for implementation. The setup allows for live observation and analysis of filtered data streams from the Arduino.

Uploaded by

gouravspam48
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views8 pages

Arduino Data Filtering

The document provides a comprehensive guide for collecting live data from an Arduino, applying Kalman and Savitzky-Golay filters, and plotting the results in MATLAB. It includes Arduino code for reading sensor values, MATLAB code for real-time filtering and visualization, and detailed steps for implementation. The setup allows for live observation and analysis of filtered data streams from the Arduino.

Uploaded by

gouravspam48
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Arduino Data Filtering

import numpy as np
import pandas as pd
from scipy.signal import savgol_filter
import matplotlib.pyplot as plt

# Function to apply the Kalman filter


def apply_kalman_filter(data_column, Q=1e-5, R=0.01):
n = len(data_column)
x = np.zeros(n) # State estimate
P = np.zeros(n) # Error covariance

# Initial guesses
x[0] = data_column[0] # Initial estimate
P[0] = 1 # Initial error covariance

# Kalman filter implementation


for k in range(1, n):
# Prediction step
x_pred = x[k - 1]
P_pred = P[k - 1] + Q

# Update step
K = P_pred / (P_pred + R) # Kalman gain
x[k] = x_pred + K * (data_column[k] - x_pred) # Update state estimate
P[k] = (1 - K) * P_pred # Update error covariance

return x

# Function to apply the constrained Kalman filter (Savitzky-Golay filter)


def apply_constrained_kalman_filter(data_column, window_size=13, poly_order=3):
return savgol_filter(data_column, window_size, poly_order)

# Function to calculate error metrics


def calculate_metrics(original, filtered):
mse = np.mean((original - filtered) ** 2) # Mean Squared Error
rmse = np.sqrt(mse) # Root Mean Squared Error
ss_total = np.sum((original - np.mean(original)) ** 2) # Total sum of squares
ss_residual = np.sum((original - filtered) ** 2) # Residual sum of squares
r2 = 1 - (ss_residual / ss_total) # R-squared
return mse, rmse, r2

# Main function
def main():
# File paths

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/8
input_file = r"C:\Users\goura\Desktop\Case 2\case2_one_direction.csv"
output_file = r"C:\Users\goura\Desktop\legend_case1.xlsx"

# Load the CSV file


data = pd.read_csv(input_file)

# Columns to filter
ldr_columns = ["Q1", "Q2", "Q3", "Q4"]

# Verify input data


print("Preview of input data:")
print(data[ldr_columns].head())

# Iterate through each column and apply filters


for col in ldr_columns:
if col in data.columns:
original_data = data[col].values

# Apply Kalman filter


kalman_filtered_data = apply_kalman_filter(original_data)
data[f"Kalman_{col}"] = kalman_filtered_data

# Apply constrained Kalman filter on Kalman-filtered data


constrained_kalman_data = apply_constrained_kalman_filter(kalman_filtered_data)
data[f"Constrained_Kalman_{col}"] = constrained_kalman_data

# Visualize the data


plt.figure(figsize=(10, 6))
plt.plot(original_data, label=f"Original Data ({col})", linestyle="--", alpha=0.7)
plt.plot(kalman_filtered_data, label=f"Kalman Filtered ({col})", linestyle="-", alpha=0.8)
plt.plot(constrained_kalman_data, label=f"Constrained Kalman Filtered ({col})", linestyle="-")
plt.title(f"Visualization for {col}")
plt.xlabel("Time")
plt.ylabel("Signal Value")
plt.legend()
plt.grid()
plt.show()

# Calculate and print metrics


mse_kalman, rmse_kalman, r2_kalman = calculate_metrics(original_data,
kalman_filtered_data)
mse_constrained, rmse_constrained, r2_constrained = calculate_metrics(original_data,
constrained_kalman_data)

print(f"Metrics for {col}:")


print(f" Kalman Filter: MSE = {mse_kalman:.4f}, RMSE = {rmse_kalman:.4f}, R² =
{r2_kalman:.4f}")
print(f" Constrained Kalman Filter: MSE = {mse_constrained:.4f}, RMSE =
{rmse_constrained:.4f}, R² = {r2_constrained:.4f}\n")

# Save the filtered data to a new file


Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/8
data.to_excel(output_file, index=False)
print(f"Filtered data saved to {output_file}")

# Run the main function


if __name__ == "__main__":
main()

const int Q1 = A0; // Quadrant 1


const int Q2 = A1; // Quadrant 2
const int Q3 = A2; // Quadrant 3
const int Q4 = A3; // Quadrant 4

void setup() {
Serial.begin(9600); // Start serial communication at 9600 baud
}

void loop() {
// Read values from each quadrant
int v1 = analogRead(Q1);
int v2 = analogRead(Q2);
int v3 = analogRead(Q3);
int v4 = analogRead(Q4);

// Send intensity values in comma-separated format


Serial.print(v1);
Serial.print(",");
Serial.print(v2);
Serial.print(",");
Serial.print(v3);
Serial.print(",");
Serial.println(v4); // End the line with a newline

delay(500); // Adjust delay for data streaming


}

MATLAB CODE

% Define serial port and baud rate


port = 'COM8'; % Replace with the correct port for your system
baudRate = 9600; % Replace with the correct baud rate for your Arduino

% Open serial connection


s = serial(port, 'BaudRate', baudRate);
fopen(s);

% Set up real-time plotting in quadrants


figure;

% Subplot for Q1
subplot(2, 2, 1);
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/8
q1_line = animatedline('Color', 'r');
title('Q1');
xlabel('Time (s)');
ylabel('Intensity');
grid on;

% Subplot for Q2
subplot(2, 2, 2);
q2_line = animatedline('Color', 'g');
title('Q2');
xlabel('Time (s)');
ylabel('Intensity');
grid on;

% Subplot for Q3
subplot(2, 2, 3);
q3_line = animatedline('Color', 'b');
title('Q3');
xlabel('Time (s)');
ylabel('Intensity');
grid on;

% Subplot for Q4
subplot(2, 2, 4);
q4_line = animatedline('Color', 'k');
title('Q4');
xlabel('Time (s)');
ylabel('Intensity');
grid on;

% Initialize timer
startTime = datetime('now');

try
while true
% Read data from Arduino
data = fscanf(s);

% Parse the comma-separated data


values = str2double(split(data, ','));

% Ensure data has 4 values


if numel(values) == 4
% Get elapsed time
elapsedTime = seconds(datetime('now') - startTime);

% Update Q1
subplot(2, 2, 1);
addpoints(q1_line, elapsedTime, values(1));
drawnow limitrate;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/8
% Update Q2
subplot(2, 2, 2);
addpoints(q2_line, elapsedTime, values(2));
drawnow limitrate;

% Update Q3
subplot(2, 2, 3);
addpoints(q3_line, elapsedTime, values(3));
drawnow limitrate;

% Update Q4
subplot(2, 2, 4);
addpoints(q4_line, elapsedTime, values(4));
drawnow limitrate;
end
end
catch ME
% Close the serial connection if an error occurs
fclose(s);
delete(s);
rethrow(ME);
end

% Close the serial connection when done


fclose(s);
delete(s);

I need to collect live q1,2,3,4 data from arduino, perform filters on these values and i need to plot
them live in matlab after filtering

Give code & steps to implement this

To collect live data from Arduino, apply Kalman and Savitzky-Golay filters to the data, and plot the
filtered results in MATLAB in real-time, follow the steps below:

1. Arduino Code (already provided)

Upload the provided Arduino code to your Arduino device.


The Arduino will read analog values from the sensors (Q1, Q2, Q3, Q4) and send them to the serial
port in a comma-separated format.

2. MATLAB Real-Time Filtering and Plotting

Below is the MATLAB script to collect live data from the Arduino, apply the Kalman and Savitzky-Golay
filters, and plot the results in real-time:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 5/8
matlab

% Define serial port and baud rate


port = 'COM8'; % Replace with your Arduino's port
baudRate = 9600;

% Open serial connection


s = serial(port, 'BaudRate', baudRate);
fopen(s);

% Set up real-time plotting


figure;

% Subplot for Q1
subplot(2, 2, 1);
q1_orig = animatedline('Color', 'r', 'LineStyle', '--');
q1_kalman = animatedline('Color', 'r', 'LineStyle', '-');
q1_savgol = animatedline('Color', 'r', 'LineStyle', ':');
title('Q1');
xlabel('Time (s)');
ylabel('Intensity');
grid on;

% Subplot for Q2
subplot(2, 2, 2);
q2_orig = animatedline('Color', 'g', 'LineStyle', '--');
q2_kalman = animatedline('Color', 'g', 'LineStyle', '-');
q2_savgol = animatedline('Color', 'g', 'LineStyle', ':');
title('Q2');
xlabel('Time (s)');
ylabel('Intensity');
grid on;

% Subplot for Q3
subplot(2, 2, 3);
q3_orig = animatedline('Color', 'b', 'LineStyle', '--');
q3_kalman = animatedline('Color', 'b', 'LineStyle', '-');
q3_savgol = animatedline('Color', 'b', 'LineStyle', ':');
title('Q3');
xlabel('Time (s)');
ylabel('Intensity');
grid on;

% Subplot for Q4
subplot(2, 2, 4);
q4_orig = animatedline('Color', 'k', 'LineStyle', '--');
q4_kalman = animatedline('Color', 'k', 'LineStyle', '-');
q4_savgol = animatedline('Color', 'k', 'LineStyle', ':');
title('Q4');
xlabel('Time (s)');
ylabel('Intensity');
grid on;

% Initialize filter variables


kalman_state = zeros(4, 1); % Initial state for Kalman filter
kalman_cov = ones(4, 1); % Initial error covariance for Kalman filter
Q = 1e-5; % Process noise
R = 0.01; % Measurement noise
buffer_size = 51; % Buffer size for Savitzky-Golay filter
poly_order = 3; % Polynomial order for Savitzky-Golay filter
buffer = zeros(buffer_size, 4); % Circular buffer for filtering

% Initialize timer
startTime = datetime('now');

try
while true
% Read data from Arduino
data = fscanf(s);

% Parse the comma-separated data


values = str2double(split(data, ','));

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/8
% Ensure data has 4 values
if numel(values) == 4
% Get elapsed time
elapsedTime = seconds(datetime('now') - startTime);

% Update Savitzky-Golay buffer


buffer = circshift(buffer, -1, 1);
buffer(end, :) = values;

% Apply Kalman filter


for i = 1:4
% Prediction step
pred_state = kalman_state(i);
pred_cov = kalman_cov(i) + Q;

% Update step
kalman_gain = pred_cov / (pred_cov + R);
kalman_state(i) = pred_state + kalman_gain * (values(i) - pred_state);
kalman_cov(i) = (1 - kalman_gain) * pred_cov;
end

% Apply Savitzky-Golay filter (if enough data is collected)


if all(buffer(:, 1) ~= 0)
sg_filtered = sgolayfilt(buffer, poly_order, buffer_size);
sg_output = sg_filtered(end, :);
else
sg_output = values;
end

% Update plots
% Original Data
addpoints(eval(['q' num2str(1) '_orig']), elapsedTime, values(1));
addpoints(eval(['q' num2str(2) '_orig']), elapsedTime, values(2));
addpoints(eval(['q' num2str(3) '_orig']), elapsedTime, values(3));
addpoints(eval(['q' num2str(4) '_orig']), elapsedTime, values(4));

% Kalman Filtered Data


addpoints(eval(['q' num2str(1) '_kalman']), elapsedTime, kalman_state(1));
addpoints(eval(['q' num2str(2) '_kalman']), elapsedTime, kalman_state(2));
addpoints(eval(['q' num2str(3) '_kalman']), elapsedTime, kalman_state(3));
addpoints(eval(['q' num2str(4) '_kalman']), elapsedTime, kalman_state(4));

% Savitzky-Golay Filtered Data


addpoints(eval(['q' num2str(1) '_savgol']), elapsedTime, sg_output(1));
addpoints(eval(['q' num2str(2) '_savgol']), elapsedTime, sg_output(2));
addpoints(eval(['q' num2str(3) '_savgol']), elapsedTime, sg_output(3));
addpoints(eval(['q' num2str(4) '_savgol']), elapsedTime, sg_output(4));

% Redraw plots
drawnow limitrate;
end
end
catch ME
% Close the serial connection if an error occurs
fclose(s);
delete(s);
rethrow(ME);
end

% Close the serial connection when done


fclose(s);
delete(s);

Steps to Run

1. Connect Arduino:
Connect your Arduino to the computer and upload the Arduino code.
2. Identify Port:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 7/8
Replace `COM8` with the correct port number for your Arduino.
3. Run MATLAB Script:
Copy the MATLAB script into a `.m` file and run it.
4. Filters:
The script applies Kalman and Savitzky-Golay filters in real-time.
Adjust filter parameters (e.g., `Q`, `R`, `buffer_size`, `poly_order`) if necessary.
5. Live Plotting:
The script plots real-time data for Q1, Q2, Q3, and Q4, including original, Kalman-filtered, and
Savitzky-Golay-filtered signals.

This setup should allow you to observe and analyze live-filtered data streams from the Arduino in
MATLAB. Let me know if you need further adjustments or explanations!

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 8/8

You might also like