The instrument's serial communication interface was mainly intended for terminal device applications, where commands (and end-of-line characters) are manually typed one letter at a time, whereas MATLAB serial write functions send all characters in quick succession. A custom fuction writing one character at a time with a pause between characters is needed.
The instrument manual describes only the terminal device communication workflow using PuTTY.
Below are some properties of this particular device that we have observed:
- The instrument takes "CR/LF" for read terminator and "CR" for write, instead of "LF".
- The instrument cannot take multiple characters at once, it requires pauses between characters.
- The instrument echoes back the command characters received.
- The instrument does not appear to have consistent behavior, for the same command, sometimes it works, sometimes it returns "command not found"
- The output is spread over multiple lines, so you have to do fscanf several times to get the whole output.
From the properties above, the intended use of serial communication of this device is for terminal interaction, where commands and line terminators are typed in one letter at a time.
To correctly use this device, please first connect to the device using the "serial" object as below:
FT = serial('COM18','BaudRate',115200);
FT.Terminator = {'CR/LF','CR'};
fopen(FT)
Then define a function that takes a command string as argument and sends one character at a time to the device.
Since we are sending one character at a time, we use fwrite instead of fprintf.
function writeCommand(obj, cmd)
for i = 1:numel(cmd)
fwrite(obj, cmd(i))
pause(0.25)
end
fwrite(obj, 13)
end
Then use the function defined above to send command to the device and read with fscanf. Note that as mentioned above, the output might spread over multiple lines, so you have to scanf multiple times to read the whole output:
writeCommand(FT, 'm')
pause(0.5)
while (FT.BytesAvailable > 0)
fscanf(FT)
end
writeCommand(FT, 'r')
pause(0.5)
while (FT.BytesAvailable) > 0
fscanf(FT)
end
Close the connection after use:
Best Answer