views:

628

answers:

2

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.

+4  A: 

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.

gnovice
Ahh great, thank you very much! Ill vote best once i get it all up and running.
Faken
Sorry actually one more question: If the data inside the packet of 6 values are actually a triplet of 2 byte integers, how do i convert that? I think the value is signed though.
Faken
So, are there six values in `data1`, and you want to group each pair into a 2-byte integer?
gnovice
The packet contains 6 8-bit integers, i want to take any two of them and convert them to a single signed 16-bit integer
Faken
@Faken: The update to my answer should address your additional question.
gnovice
A: 

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.

mtrw