MATLAB Answers

Get only numbers from serial port without any str2num() conversion

13 views (last 30 days)
Hi all!
In the serial com port channel values comes from 0 to 1023, this example from Arduino:
On the MATLAB side I parse it via function:
function sPs = GetsP()
global obj1;
sPs = 0;
Psvoltage = fscanf(obj1);
if (~isempty(Psvoltage))
sPs = str2num(Psvoltage) * (100 / 1023);
But I dont like this variant, because str2num() conversion is very slow. If I try to use Psvoltage = fread(obj1, 1, 'ushort'); I didnt see correct data, because fread() reads binary data.
So the question is: How can I try to read direct number data, without any slow string to number conversion? How can I need to use fread() to get numbers?


Ced on 25 Mar 2016
I don't have a serial port to test this out, but as I understand, you are reading the values from a file? Is that true?
If you are always getting a string, I'm afraid there is no other way than to perform a str2num conversion in some way. Also, as you have mentioned in your other post, Check Two String Data, the output is not always consistent, so you won't get around parsing either.
The only alternative I can think of is to fetch the data stream directly. I imagine the original stream is binary. So, instead of fetching stream -> converting to string -> writing to file -> reading from file -> parsing -> converting to double, it should be possible to just get the stream directly. Or at least have a binary buffer file instead of a string file.
That being said, I'm having a hard time imagining that this is really an issue with the Arduino. Is the sensor feedback rate really that high?
Sergey Makovkin
Sergey Makovkin on 28 Mar 2016
Arduino outputs a fluorescence value from a photomultiplier tube via COM port. The image has been created on the scanner by this data. We design two-photon laser microscope for medical purposes, therefore, a very important data transmission speed. Slow place here is the serial port, but these are the conditions of the project.
Walter Roberson
Walter Roberson on 28 Mar 2016
Reprogram the arduino code to send uint16 instead of text. You only need 10 bits of the 16, so you could even pack in some flags like "Beginning of Row" to help synchronize. Or you could take advantage of the extra 6 bits to add error correcting codes to make it easier to recover from potential dropped bytes.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 25 Mar 2016
str2num() uses a full eval() . str2double() is faster. You can also use fscanf with a format specifier,
fscanf(obj1, '%d')


Sign in to comment.

More Answers (0)

Sign in to answer this question.