Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

S-function simulink for serial communication

  1. Apr 12, 2012 #1
    I'm trying to read data from a serial port in simulink. The serial configuration blocks and query instrument are not working properly for the device I try to read over COM port.

    In matlab, I can easily read out data from the device using fopen() and fscanf().

    Using the matlab function block in simulink, I get the same result in simulink. Problem is: it needs to open and close the serial connection every step, slowing down my system.

    I'm trying to write level1 s-function to overcome this problem. Right now I have:

    Code (Text):
    function [sys,x0,str,ts] = test1(t,x,u,flag)
    NMEA = serial('COM2', 'BaudRate', 4800);
    switch flag
    case 0
    [sys,x0,str,ts] = mdlInitializeSizes(NMEA);
    case 3
    sys = mdlOutputs(t,x,u, NMEA);
    case { 1, 2, 4, 9 }
    sys = [];
    error(['Unhandled flag = ',num2str(flag)]);

    function [sys,x0,str,ts] = mdlInitializeSizes(NMEA)
    sizes = simsizes;
    sizes.NumContStates= 0;
    sizes.NumDiscStates= 0;
    sizes.NumOutputs= 1;
    sizes.NumInputs= 1;
    sys = simsizes(sizes);
    x0 = [];
    str = [];
    ts = [-1 0];

    function sys = mdlOutputs(t,x,u,NMEA)
    sys = fscanf(NMEA);
    Giving me the error that the port needs to be opened at flag=3 (output). But I don't want to open the com2 every step as this will get really slow. How to solve this? I just want to open the connection once and constantly read from it (in simulink).
  2. jcsd
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Can you offer guidance or do you also need help?
Draft saved Draft deleted