Read serial device and update uitable in loop

8 Ansichten (letzte 30 Tage)
Matthijs
Matthijs am 19 Jan. 2024
Bearbeitet: Hassaan am 22 Jan. 2024
Hi,
I have 24 sensors hooked up to an Arduino. The Arduino is programmed to print the reading of every sensor in one comma-separated line on every loop. The MATLAB script reads the line and update the table with the sensor readings.
The script works when I print the data to the command window and the sensors can be seen responding in real time. But, for some reason, when I add a UITable the script does show updated readings on every loop, but the sensors don't seem to respond to any changes (not in the table and not even in the command window). I've tried adding a delay, didn't work. Does anyone know?
clc
clear all;
close all;
% Connect to Arduino
s = serialport("COM5",115200); % connect to serial device (arduino)
% fid = fopen("yourfilename.txt",'a'); %create file for saving data
b = zeros(24); % create empty array for storing sensor data
% Create UI table
fig = uifigure;
uit = uitable(fig,"Data",b);
uitablehandle = findall(fig,'type','uitable');
% Read and print sensor data
while 1
sensordata = readline(s); % read arduino output
b = cell2mat(cellfun(@str2num,sensordata,'uniform',0)) % convert data to array
set(uitablehandle,'data',b'); % update table
drawnow;
end

Akzeptierte Antwort

Hassaan
Hassaan am 19 Jan. 2024
Bearbeitet: Hassaan am 22 Jan. 2024
  1. Buffer Overflow: Continuous reading from a serial port without adequate processing time can lead to a buffer overflow. This can cause data to be missed or not processed correctly.
  2. Graphical Rendering: MATLAB's graphical rendering can be quite resource-intensive. Updating a UI table in real-time can slow down the execution of the loop, causing delays in data processing.
  3. Data Conversion and Error Handling: Ensure that the data conversion from the serial input to the numerical format is happening correctly. Errors in conversion might cause the loop to stall or behave unexpectedly.
  4. Asynchronous Data Handling: Consider reading data from the serial port asynchronously. This can prevent the GUI from freezing and ensure smoother data updates.
  5. Limiting GUI Updates: Reducing the frequency of UI updates can significantly improve performance. You could update the UI table every few iterations instead of every single loop.
clc;
clear all;
close all;
% Connect to Arduino
s = serialport("COM5", 115200); % Connect to serial device (Arduino)
% Initialize variables
b = zeros(24, 1); % Create empty array for storing sensor data
% Create UI table
fig = uifigure;
uit = uitable(fig, "Data", b);
uitablehandle = findall(fig, 'type', 'uitable');
% Run indefinitely
while 1
pause(0.1); % Small delay to reduce CPU usage
drawnow; % Update figure window
end
% Set up asynchronous reading
configureCallback(s, "terminator", @readAndUpdate);
function readAndUpdate(src, ~)
persistent uitHandle b;
if isempty(uitHandle)
uitHandle = uitablehandle;
end
if isempty(b)
b = zeros(24, 1);
end
sensordata = readline(src); % Read Arduino output
try
b = cell2mat(cellfun(@str2num, sensordata, 'uniform', 0)); % Convert data to array
catch
% Handle data conversion errors
end
set(uitHandle, 'Data', b'); % Update table
end
-----------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
Professional Interests
  • Technical Services and Consulting
  • Embedded Systems | Firmware Developement | Simulations
  • Electrical and Electronics Engineering
It's important to note that the advice and code are based on limited information and meant for educational purposes. Users should verify and adapt the code to their specific needs, ensuring compatibility and adherence to ethical standards.
Feel free to contact me.
  2 Kommentare
Matthijs
Matthijs am 22 Jan. 2024
Thanks for your help, I really appreciate it! I tried your code, but I think you forgot to use the readAndUpdate function in the while loop. Also, I can only define a function at the end of a script, so I made a separate file for that. After implementing those changes, the script works nicely and also updates fast enough for practical use of the sensors.
However, I don't really understand the changes you've made to the script. What is a 'terminator'? Also, doesn't this loop still read the serial device on every iteration, except for the instances when there is a conversion error? Why is it that, with your script, the table updates that much faster?
Hassaan
Hassaan am 22 Jan. 2024
Bearbeitet: Hassaan am 22 Jan. 2024
  1. Terminator: The 'terminator' is a character or set of characters that indicate the end of a block of data when reading from a serial device. For example, the Arduino might send sensor data followed by a newline character (\n). When MATLAB reads from the serial port, it knows one set of data ends when it encounters this terminator.
  2. Asynchronous Reading: Instead of polling the serial device in a tight while loop, the configureCallback function sets up an event-based or callback-driven reading. When a terminator is read from the serial port, the readAndUpdate function is automatically called. This is more efficient and allows MATLAB to perform other tasks between data arrivals.
  3. Persistent Variables: The persistent keyword inside the readAndUpdate function maintains the state of variables across function calls. This way, you don't have to redefine the UI table handle and buffer b each time new data is read.
  4. Function Definition: readAndUpdate is an auxiliary function meant to be called by the serial port callback mechanism, not directly in a loop.
  5. Performance: The main loop with pause(0.1); drawnow; is not reading from the serial device directly. Instead, it keeps the MATLAB figure responsive. The actual reading is done asynchronously by the callback function. This design leads to a responsive GUI because the main thread of execution is not blocked by the serial read operation, which can be slow or blocking.
  6. Data Conversion: May or may needs to be changed. The line with cell2mat(cellfun(@str2num, sensordata, 'uniform', 0)) is trying to convert a cell array of strings to a numeric array. However, this conversion assumes that readline returns a cell array, which it does not. readline returns a string for each line read from the serial port, so this line should be changed to directly convert the string to a numeric array after parsing it appropriately, usually with str2double or strsplit if multiple numbers are expected per line.
function readAndUpdate(src, ~)
persistent uitHandle b;
if isempty(uitHandle)
uitHandle = uitablehandle;
end
if isempty(b)
b = zeros(24, 1);
end
sensordata = readline(src); % Read Arduino output
try
% Assuming the data is separated by commas, replace ',' with ' ' for str2num
sensordata = strrep(sensordata, ',', ' ');
b = str2num(sensordata); % Convert data to array
catch
% Handle data conversion errors
end
set(uitHandle, 'Data', b); % Update table
end
Replace uitablehandle with the actual handle to your uitable. Ensure your Arduino code formats the data with a terminator and matches the expected format in the MATLAB callback.
-----------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
It's important to note that the advice and code are based on limited information and meant for educational purposes. Users should verify and adapt the code to their specific needs, ensuring compatibility and adherence to ethical standards.
Professional Interests
  • Technical Services and Consulting
  • Embedded Systems | Firmware Developement | Simulations
  • Electrical and Electronics Engineering
Feel free to contact me.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu MATLAB Support Package for Arduino Hardware finden Sie in Help Center und File Exchange

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by