Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format this data read from a serial port in MATLAB?

I'm trying to interface a digital sensor to my computer via MATLAB.

I first send a request for data to the sensor, then the sensor replies with a six byte stream.

MATLAB reads the sensor like this:

data1 = fscanf(obj1, '%c', 6);

I know exactly what the contents of the data is supposed to be, but I don't know how to read the data in the packet that MATLAB produced.

The packet (data1) is simply 6 bytes, but how do I access each individual element as an integer?

I've never touched MATLAB programming before so I'm kind of lost.

Side question: What do MATLAB's data formats %c, %s, %c\n, and %s\n mean? I tried searching for it, but I couldn't find anything.

like image 232
Faken Avatar asked Dec 30 '25 02:12

Faken


1 Answers

The format specifier %c indicates that FSCANF is reading six characters. You should be able to convert those characters to integer values using the DOUBLE function:

data1 = double(data1);

Now data1 should be a six-element array containing integer values. You can access each by indexing into the array:

a = data1(1);  %# Gets the first value and puts it in a

If you want to combine pairs of values in data1 such that one value represents the highest 8 bits of a number and one value represents the lowest 8 bits, the following should work:

a = int16(data1(1)*2^8+data1(2));

The above uses data1(1) as the high bits and data1(2) as the low bits, then converts the result to an INT16 type. You could also leave off the call to INT16 to just leave the result as type DOUBLE (the value it stores would still be an integer).

The format specifier %s is used to read a string of characters, up until white space is encountered. Format specifiers are discussed in the documentation for FSCANF that I linked to above.

like image 97
gnovice Avatar answered Dec 31 '25 19:12

gnovice