Why does FREAD read data incorrectly from my instrument when using Instrument Control Toolbox 2.2 (R14SP2)?

13 views (last 30 days)
I am using the FREAD function in the Instrument Control Toolbox to read binary data from my instrument. However, the data that is read appears to be badly scaled, or the first few values are not what I expect.
I do not receive any error messages.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
It is likely that your instrument returns data in binblock format. This means that it comes back with a header that is as follows:
#XYYY<data>>
where:
the pound sign is literal
the X is an ASCII digit representing the number of bytes in YYY
YYY is the number of bytes in the waveform.
<data> is the data in binary format, 1 or 2 bytes per value depending on the FORMAT setting.
Note that X is the number of bytes, not values, so if you are transferring in WORD format, the number of bytes will be twice the number of values to read.
For example, with 2500 data points, a header would look like the following:
#42500<data in binary format>
If you are using a direct FREAD command to read everything (including this header information), then all of your waveform will still be read (except the last few bytes). You will probably find that the first few values of your data are not what you expect and that they are the same every time.
To solve the problem, read the data in as a binblock. There are two ways to do this. One is with the BINBLOCKREAD function in the Instrument Control Toolbox. Simply change
%get data
fprintf(s, 'waveform:data?');
out = fread(s, points, 'int16');
to:
%get data
fprintf(s, 'waveform:data?');
out = binblockread(s, 'int16');
Note: The use of the BINBLOCKREAD function requires Instrument Control Toolbox 1.1 (R12.1) or later.
If you want more control over the read, you can simply do the parts yourself. You can either go through the whole process of interpreting the header, or if you know how many points are going to be returned, precalculate the length of the header and discard those bytes.
For example, for 500000 bytes and a header of:
#6500000
you could use the following code:
fprintf(s, 'waveform:data?');
fread(s, 8, 'int8'); % discard header
fread(s, points, 'int16'); % get the waveform data of known length>
Additional information on binblocks and reading data from your instrument should be available in your hardware documentation.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!