Clear Filters
Clear Filters

Real time data acquisition

5 views (last 30 days)
Gianmarco Azzolin
Gianmarco Azzolin on 26 Jun 2021
Answered: Ayush on 3 May 2024
Hi everybody, I need to implement a code that acquires 5 measurement data in real time and plot the associated shape, how can I provide Matlab script real time data?Thank you all for your attention and help

Answers (1)

Ayush on 3 May 2024
To provide MATLAB script real-time data, you can use the "serialport" function to create a connection to the serial device. Make sure that your device is connected to your system. Then implement a loop which will send a command to the sensor "writeline(device, '*IDN?')" and then read the response with "readline(device)". Make note that you will need to adjust the command " '*IDN?' " to match what your sensor expects for data requests. Refer to a pseudo code below for better understanding:
% Example MATLAB script to acquire 5 measurement data points in real time using serialport and plot the data
% Parameters
Port = 'COM3'; % Change this to your serial port
baudRate = 9600; % Adjust as per your device's specifications
dataPoints = 5; % Number of data points to acquire
% Setup serial connection using serialport
device = serialport(Port, baudRate);
% Configure Terminator if necessary (uncomment and adjust as needed)
% configureTerminator(device,"CR/LF"); % Example: CR/LF, LF, CR, etc.
% Initialize a vector to store the data
data = zeros(1, dataPoints);
% Acquiring data
for i = 1:dataPoints
% Send a query to the device to get data (adjust according to your device)
writeline(device, '*IDN?'); % Example command, replace with your device's data request command
% Read the data returned by the device
% Adjust read function and format as per your data and device
dataStr = readline(device); % Reads data as string
data(i) = str2double(dataStr); % Convert string to double (adjust as needed)
% Optional: Wait a bit before the next query, adjust as necessary
pause(1); % Pauses for 1 second
% Clean up: Close and delete the serial port object
clear device;
% Display the acquired data
disp('Acquired Data:');
% Plot the acquired data
figure; % Creates a new figure window
plot(data, '-o', 'LineWidth', 2, 'MarkerSize', 10);
title('Real-Time Acquired Data');
xlabel('Measurement Number');
ylabel('Data Value');
grid on; % Adds a grid to the plot for better readability
For more information on "serialport", "writeline" and "readline" functions, refer to the below documentation:
  1. "serialport" :
  2. "writeline" :
  3. "readline" :


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!