'Octave: How can I plot unknown length serial data using the instrument-control package?

I found this example which sorta works... but it's not perfect. For starters it plots 10 at once but that's an easy fix. Problem is that it does not dynamically get line endings and instead relies on byte count.

pkg load instrument-control

s1 = serialport("/dev/ttyUSB0", 9600) 
flush(s1);

y_temp = cell(10,1)
y = 0
while true
  for i = 1:10
    y_serial = str2num(char(fread(s1,8)))
    y_temp {i,1} = y_serial
  endfor
  y = cat(1, y, y_temp{1:10})
  plot(y)
  pause(1)
endwhile
srl_close(s1)

This works... so long as the number of bytes per string is 8. How can I make this dynamic and split by line endings?

All I need to do is plot incrementing by 1 x_value and a float y_value from serial.



Solution 1:[1]

https://www.edn.com/read-serial-data-directly-into-octave/

Solution found. Their is no inbuilt solution but you can make your own function like:

function [char_array] = ReadToTermination (srl_handle, term_char)
    % parameter term_char is optional, if not specified
    % then CR = 'r' = 13dec is the default.
if (nargin == 1)
  term_char = 13;
end
not_terminated = true;
i = 1;
int_array = uint8(1);
while not_terminated
    val = fread(srl_handle, 1);
    if(val == term_char)
        not_terminated = false;
    end
  % Add char received to array
  int_array(i) = val;
  i = i + 1;
end
  % Change int array to a char array and return a string array
  char_array = char(int_array);
endfunction

This does not actually work straight off and I had to add \n to my Arduino script.

Solution 2:[2]

disp('load instrument control:');
pkg load instrument-control
disp('SerialPort:');
serialportlist
cpx = serialport ("COM6", 57600);
disp(cpx);

disp(sprintf('InBuffer:%3d', cpx.NumBytesAvailable));
if (cpx.NumBytesAvailable > 0)  
  zx = read(cpx, cpx.NumBytesAvailable); 
  disp(sprintf("IN:\r\n%s", zx));
endif;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 James Lee
Solution 2 Xtest