How to read text and strings from serial port?
Show older comments
I’m designing a motor controller using an Arduino Mega board. I need to be able to log the speeds of the motors, so right now I’m using the Arduino to read the speeds and print those to the serial monitor. Unfortunately, my motors only output speed, not direction, so it will output the same speed for clockwise or counterclockwise rotation. I need to be able to distinguish between the two and plot the resulting data.
Whenever the Arduino commands the motor to change directions I have it send the direction of rotation over the serial monitor, "CW", or "CCW". The problem is that I’m storing the motor speeds received by the Arduino in an array, and whenever a direction change command comes in, this is getting stored as a NaN in my array. How do I fix this?
Code shown below and below that is the data I’m currently getting back from the Arduino. It should be more of a sine wave with positive and negative values.
clear;
clc;
clf;
data=zeros(2,100000); % Initalize array that data will be stored in
% Create Serial Object
s=serialport('COM4',115200);
% Initalize varriables for data reading loop
i=2;
t=0;
tic;
h=plot(NaN,NaN,'r'); % Open plot object to speed up plotting speed
while (t <= 30)
t=toc; % log time since loop start
data(1,i) = readline(s); % Read data sent over serialport and log it
data(2,i) = t; % Save the time the data was aquired in an array
set(h, 'XData', data(2,1:i),'YData',data(1,1:i)); % Used to speed up plotting
drawnow
i=i+1; % increment array index
end
data=data(:,1:i-1); % Remove data beyond the final read value
SampleSpeed = i/t % Calcuate sample speed, used for debugging
clear s; % Close serial port object

This is what the data should look like:

Accepted Answer
More Answers (0)
Categories
Find more on MATLAB Support Package for Arduino Hardware in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!