Clear a persistent variable in a MATLAB Fcn block as serial object
    조회 수: 12 (최근 30일)
  
       이전 댓글 표시
    
Hello! I am using following code for read data from serial port:
function y = fcn(u)
coder.extrinsic('only3')
coder.extrinsic('strncmp')
coder.extrinsic('serial', 'fopen','fread')
coder.extrinsic('get')
persistent s a b
y = uint8(zeros(2,1));  %signal is an uint8
   if isempty(s)
     % only do this the first time
      s = serial('COM12','Terminator','', 'InputBufferSize', 1024);
      a = '000';
      b = false;
      a = only3(get(s,'status'));
  b = strncmp(a,'clo',3);
      switch double(b)
      case 1
          fopen(s);
      otherwise
          fclose(s);
      end
  end
     y = uint8(fread(s,[2 1],'uint8'));
Where 'only3' is my function that takes only the first 3 chars from a string. The problem is that communication does not terminate with simulation stopping. Switch case has no effect (I thought that it shuts down reading after an other run). How can I clear persistent variable 's' and reset the block after stopping?
댓글 수: 0
답변 (3개)
  Friedrich
    
 2014년 2월 27일
        
      편집: Friedrich
    
 2014년 2월 27일
  
      Hi,
A MATLAB FCN Block is a bad idea here. Better would be a MATLAB LVL 2 S-function because you can better control your serial port. In the mdlStart you create your serial object and later in the mdlTerminate you close it propperly. In the mdlOutputs you calculate the signal as usual.
댓글 수: 6
  Friedrich
    
 2014년 3월 3일
				Yes. You open the serial port in the mdlInitializeSizes and close it in the mdlTerminate.
  Ryan Livingston
    
 2014년 4월 2일
        Another thought could be to use the serial port I/O blocks directly in Simulink. See the Blocks heading here:
I am not too familiar with them, but they may facilitate a simpler interface to your hardware.
These could perform the I/O and then you could process the data using the method of your choosing.
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



