开发者

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 pac开发者_运维技巧ket 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.


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.


You can use cstruct by AJ Johnson from MATLAB File Exchange. This allows you to specify a C-language data structure that corresponds to your packet of characters. Then one function call translates the characters (bytes) into MATLAB data types. This is fast and quite maintainable if the data format ever changes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜