MATLAB: How to transmit hexadecimal codes to the instrument using the Instrument Control Toolbox 2.6 (R2008a)

0xfprintffreadfscanffwritehexhexadecimalInstrument Control Toolbox

I am trying to transmit hex codes to my instrument via the serial port interface. I use the following commands to try and achieve this functionality:
s = serial('COM1');
fopen(s)
fprintf(s,'%X','E8')
fclose(s)
delete(s)
clear s
I also tried using FPRINTF in the following manner:
fprintf(s,'%X',dec2hex(232)) %232 decimal = 0xE8
However, when I use a third-party software (such as Portmon) to examine the contents of the packets transmitted by the Instrument Control Toolbox, I notice that the data is in ASCII format.

Best Answer

To transmit and receive hex codes to your device via the serial port interface, use the FWRITE and FREAD commands (used to transmit and receive binary data) as opposed to the FPRINTF and FSCANF command (used to write and read text).
Below is an example that uses the FWRITE and FREAD commands to transmit and receive a series of hex codes via the serial port interface:
s = serial('COM1');
fopen(s);
%%Specify hex codes to be transmitted
txdata = ['01';'E8';'C3';'00';'B2';'F9';'76'];
%Convert to decimal format
txdata_dec = hex2dec(txdata);
%Write using the UINT8 data format
fwrite(s,tcdata_dec,'uint8');
%Read back data in decimal format
rxdata_dec = fread(s);
% Convert data back to hexadecimal format
rxdata = dec2hex(rcdata_dec)
fclose(s)
delete(s)
clear s