MATLAB: How to use control characters other than \n with serial/fprintf and icinterface/fprintf

fprintficinterfaceMATLAB

I am trying to use the control characters \r and \t with FPRINTF on a serial port. When I use FPRINTF on a text file \t and \r work as expected.

Best Answer

The use of control characters other than \n is not a functional specification for serial/fprintf and icinterface/fprintf.
To work around this, use ASCII control characters. The following example illustrates the use of ASCII control characters:
% Open a serial interface and a text file:
s = serial('COM1')
fopen(s)
t = fopen('test.txt','w')
fopen(t)
% Try using regular control characters when printing to the serial port and to the text file:
fprintf(s,'Hello\tWorld\r\n')
fprintf(t,'Hello\tWorld\r\n')
fscanf(s)
fscanf(s);
% Display data written to serial port and to the text file:
Disp('Using ASCII control characters');
fprintf(s,['Hello' 9 'World' 13 '\n'])
fprintf(t,['Hello' 9 'World' 13 '\n'])
fscanf(s)
% Close serial interface and text file:
fclose(s)
delete(s)
fclose(t)
The FSCANF output from the serial port is as follows:
ans =
Hello\tWorld\r
Using ASCII control characters:
ans =
HelloWorld
In the text file, text.txt, this code writes:
Hello World
Hello World
This code demonstrates how control characters work for a serial interface. To implement this code, you must have a serial port loopback connector that allows you to send and receive data from the same MATLAB session.