]> rtime.felk.cvut.cz Git - mf624-simulink.git/blob - sfIRCInput.c
Include license header to prepare code for publication.
[mf624-simulink.git] / sfIRCInput.c
1 /*
2  * S-function to support IRC inputs on Humusoft MF624 card
3  *
4  * Copyright (C) 2014 Pavel Pisa <pisa@cmp.felk.cvut.cz>
5  *
6  * Department of Control Engineering
7  * Faculty of Electrical Engineering
8  * Czech Technical University in Prague (CTU)
9  *
10  * The S-Function for ERT Linux can be distributed in compliance
11  * with GNU General Public License (GPL) version 2 or later.
12  * Other licence can negotiated with CTU.
13  *
14  * Next exception is granted in addition to GPL.
15  * Instantiating or linking compiled version of this code
16  * to produce an application image/executable, does not
17  * by itself cause the resulting application image/executable
18  * to be covered by the GNU General Public License.
19  * This exception does not however invalidate any other reasons
20  * why the executable file might be covered by the GNU Public License.
21  * Publication of enhanced or derived S-function files is required
22  * although.
23  *
24  * Linux ERT code is available from
25  *    http://rtime.felk.cvut.cz/gitweb/ert_linux.git
26  * More CTU Linux target for Simulink components are available at
27  *    http://lintarget.sourceforge.net/
28  *
29  * sfuntmpl_basic.c by The MathWorks, Inc. has been used to accomplish
30  * required S-function structure.
31  */
32
33
34 #define S_FUNCTION_NAME  sfIRCInput
35 #define S_FUNCTION_LEVEL 2
36
37 /*
38  * The S-function has next parameters
39  *
40  * Sample time     - sample time value or -1 for inherited
41  * Counter Mode    -
42  * Counter Gating
43  * Reset Control
44  * Digital Filter
45  */
46
47 #define PRM_TS(S)               (mxGetScalar(ssGetSFcnParam(S, 0)))
48 #define PRM_CHANNEL(S)          (mxGetScalar(ssGetSFcnParam(S, 1)))
49 #define PRM_COUNTER_MODE(S)     (mxGetScalar(ssGetSFcnParam(S, 2)))
50 #define PRM_COUNTER_GATING(S)   (mxGetScalar(ssGetSFcnParam(S, 3)))
51 #define PRM_RESET_CONTROL(S)    (mxGetScalar(ssGetSFcnParam(S, 4)))
52 #define PRM_DIGITAL_FILTER(S)   (mxGetScalar(ssGetSFcnParam(S, 5)))
53 #define PRM_RESET_AT_STARTUP(S) (mxGetScalar(ssGetSFcnParam(S, 6)))
54
55 #define PRM_COUNT                   7
56
57 #define IWORK_IDX_CHANNEL           0
58 #define IWORK_IDX_IRCCTRL           1
59 #define IWORK_IDX_USE_GATING_INPUT  2
60 #define IWORK_IDX_GATING_VALUE      3
61 #define IWORK_IDX_USE_RESET_INPUT   4
62 #define IWORK_IDX_RESET_VALUE       5
63
64 #define IWORK_COUNT                 6
65
66 #define IWORK_CHANNEL(S)            (ssGetIWork(S)[IWORK_IDX_CHANNEL])
67 #define IWORK_IRCCTRL(S)            (ssGetIWork(S)[IWORK_IDX_IRCCTRL])
68 #define IWORK_USE_GATING_INPUT(S)   (ssGetIWork(S)[IWORK_IDX_USE_GATING_INPUT])
69 #define IWORK_GATING_VALUE(S)       (ssGetIWork(S)[IWORK_IDX_GATING_VALUE])
70 #define IWORK_USE_RESET_INPUT(S)    (ssGetIWork(S)[IWORK_IDX_USE_RESET_INPUT])
71 #define IWORK_RESET_VALUE(S)        (ssGetIWork(S)[IWORK_IDX_RESET_VALUE])
72
73 /*
74  * Need to include simstruc.h for the definition of the SimStruct and
75  * its associated macro definitions.
76  */
77 #include "simstruc.h"
78 #include "mf624_SIMULINK.h"
79
80 static const int32_T irc_channel2reg[] = {
81     IRC0_reg,
82     IRC1_reg,
83     IRC2_reg,
84     IRC3_reg
85 };
86
87 /* Error handling
88  * --------------
89  *
90  * You should use the following technique to report errors encountered within
91  * an S-function:
92  *
93  *       ssSetErrorStatus(S,"Error encountered due to ...");
94  *       return;
95  *
96  * Note that the 2nd argument to ssSetErrorStatus must be persistent memory.
97  * It cannot be a local variable. For example the following will cause
98  * unpredictable errors:
99  *
100  *      mdlOutputs()
101  *      {
102  *         char msg[256];         {ILLEGAL: to fix use "static char msg[256];"}
103  *         sprintf(msg,"Error due to %s", string);
104  *         ssSetErrorStatus(S,msg);
105  *         return;
106  *      }
107  *
108  * See matlabroot/simulink/src/sfuntmpl_doc.c for more details.
109  */
110
111 /*====================*
112  * S-function methods *
113  *====================*/
114
115 #define MDL_CHECK_PARAMETERS   /* Change to #undef to remove function */
116 #if defined(MDL_CHECK_PARAMETERS) && defined(MATLAB_MEX_FILE)
117   /* Function: mdlCheckParameters =============================================
118    * Abstract:
119    *    mdlCheckParameters verifies new parameter settings whenever parameter
120    *    change or are re-evaluated during a simulation. When a simulation is
121    *    running, changes to S-function parameters can occur at any time during
122    *    the simulation loop.
123    */
124 static void mdlCheckParameters(SimStruct *S)
125 {
126     if ((PRM_TS(S) < 0) && (PRM_TS(S) != -1))
127         ssSetErrorStatus(S, "Ts has to be positive or -1 for automatic step");
128     if ((PRM_CHANNEL(S) < 0) || (PRM_CHANNEL(S) > 3))
129         ssSetErrorStatus(S, "valid IRC channel is 0, 1, 2, or 3");
130     if ((PRM_COUNTER_MODE(S) < 0) || PRM_COUNTER_MODE(S) >
131             __mfld2val(IRCCTRL_IRC0MODE_mask, IRCCTRL_IRC0MODE_mask))
132         ssSetErrorStatus(S, "Counter Mode out of valid range");
133     if ((PRM_COUNTER_GATING(S) < 0) || PRM_COUNTER_GATING(S) >
134             __mfld2val(IRCCTRL_IRC0COUNT_mask, IRCCTRL_IRC0COUNT_mask))
135         if ((PRM_COUNTER_GATING(S) != -1))
136            ssSetErrorStatus(S, "Counter Gating out of valid range and -1 for external input not set");
137     if ((PRM_RESET_CONTROL(S) < 0) || PRM_RESET_CONTROL(S) >
138             __mfld2val(IRCCTRL_IRC0RESET_mask, IRCCTRL_IRC0RESET_mask))
139         if (PRM_RESET_CONTROL(S) != -1)
140            ssSetErrorStatus(S, "Reset Control out of valid range and -1 for external input not set");
141     if ((PRM_DIGITAL_FILTER(S) < 0) || PRM_DIGITAL_FILTER(S) >
142             __mfld2val(IRCCTRL_IRC0FILTER_mask, IRCCTRL_IRC0FILTER_mask))
143         ssSetErrorStatus(S, "Digital Filter out of valid range");
144     if ((PRM_RESET_AT_STARTUP(S) != 0) && (PRM_RESET_AT_STARTUP(S) != 1))
145         ssSetErrorStatus(S, "Reset at startup can be only 0 or 1");
146 }
147 #endif /* MDL_CHECK_PARAMETERS */
148
149
150 /* Function: mdlInitializeSizes ===============================================
151  * Abstract:
152  *    The sizes information is used by Simulink to determine the S-function
153  *    block's characteristics (number of inputs, outputs, states, etc.).
154  */
155 static void mdlInitializeSizes(SimStruct *S)
156 {
157     int_T nInputPorts  = 0;
158     int_T i;
159
160     ssSetNumSFcnParams(S, PRM_COUNT);  /* Number of expected parameters */
161     if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) {
162         /* Return if number of expected != number of actual parameters */
163         ssSetErrorStatus(S, "6-parameters requited: Ts, Channel, Counter Mode, Counter Gating, Reset Control and Digital Filter");
164         return;
165     }
166
167   #if defined(MDL_CHECK_PARAMETERS) && defined(MATLAB_MEX_FILE)
168     mdlCheckParameters(S);
169     if (ssGetErrorStatus(S) != NULL) return;
170   #endif
171
172     if (PRM_COUNTER_GATING(S) == -1)
173         nInputPorts++;
174     if (PRM_RESET_CONTROL(S) == -1)
175         nInputPorts++;
176
177     ssSetNumContStates(S, 0);
178     ssSetNumDiscStates(S, 0);
179
180     if (!ssSetNumInputPorts(S, nInputPorts)) return;
181     for (i = 0; i < nInputPorts; i++) {
182         ssSetInputPortWidth(S, i, 1);
183         ssSetInputPortDataType(S, i, SS_UINT8);
184         ssSetInputPortRequiredContiguous(S, i, true); /*direct input signal access*/
185         ssSetInputPortDirectFeedThrough(S, i, 0);
186     }
187     /*
188      * Set direct feedthrough flag (1=yes, 0=no).
189      * A port has direct feedthrough if the input is used in either
190      * the mdlOutputs or mdlGetTimeOfNextVarHit functions.
191      * See matlabroot/simulink/src/sfuntmpl_directfeed.txt.
192      */
193
194     if (!ssSetNumOutputPorts(S, 1)) return;
195     ssSetOutputPortWidth(S, 0, 1);
196     ssSetOutputPortDataType(S, 0, SS_INT32);
197
198     ssSetNumSampleTimes(S, 1);
199     ssSetNumRWork(S, 0);
200     ssSetNumIWork(S, IWORK_COUNT);
201     ssSetNumPWork(S, 0);
202     ssSetNumModes(S, 0);
203     ssSetNumNonsampledZCs(S, 0);
204
205     /* Specify the sim state compliance to be same as a built-in block */
206     ssSetSimStateCompliance(S, USE_DEFAULT_SIM_STATE);
207
208     ssSetOptions(S, 0);
209 }
210
211
212
213 /* Function: mdlInitializeSampleTimes =========================================
214  * Abstract:
215  *    This function is used to specify the sample time(s) for your
216  *    S-function. You must register the same number of sample times as
217  *    specified in ssSetNumSampleTimes.
218  */
219 static void mdlInitializeSampleTimes(SimStruct *S)
220 {
221     if (PRM_TS(S) == -1) {
222         ssSetSampleTime(S, 0, CONTINUOUS_SAMPLE_TIME);
223         ssSetOffsetTime(S, 0, FIXED_IN_MINOR_STEP_OFFSET);
224     } else {
225         ssSetSampleTime(S, 0, PRM_TS(S));
226         ssSetOffsetTime(S, 0, 0.0);
227     }
228 }
229
230
231
232 #define MDL_INITIALIZE_CONDITIONS   /* Change to #undef to remove function */
233 #if defined(MDL_INITIALIZE_CONDITIONS)
234   /* Function: mdlInitializeConditions ========================================
235    * Abstract:
236    *    In this function, you should initialize the continuous and discrete
237    *    states for your S-function block.  The initial states are placed
238    *    in the state vector, ssGetContStates(S) or ssGetRealDiscStates(S).
239    *    You can also perform any other initialization activities that your
240    *    S-function may require. Note, this routine will be called at the
241    *    start of simulation and if it is present in an enabled subsystem
242    *    configured to reset states, it will be call when the enabled subsystem
243    *    restarts execution to reset the states.
244    */
245 static void mdlInitializeConditions(SimStruct *S)
246 {
247     int_T shift;
248     int_T mask;
249     int_T reset_mode;
250     int_T reset_mode_save;
251
252     if (mf624_check(S) != 0)
253         return;
254
255     if (PRM_RESET_AT_STARTUP(S)) {
256         shift = IWORK_CHANNEL(S) * IRCCTRL_CHANNEL_SHIFT;
257
258         mask = IRCCTRL_IRC0RESET_mask << shift;
259         reset_mode = __val2mfld(IRCCTRL_IRC0RESET_mask, IRCCTRL_RESET_ALWAYS) << shift;
260
261         reset_mode_save = IRC_mode_change(mfst, 0, 0);
262         IRC_mode_change(mfst, mask, reset_mode);
263         IRC_mode_change(mfst, mask, reset_mode_save & mask);
264     }
265 }
266 #endif /* MDL_INITIALIZE_CONDITIONS */
267
268
269
270 #define MDL_START  /* Change to #undef to remove function */
271 #if defined(MDL_START)
272   /* Function: mdlStart =======================================================
273    * Abstract:
274    *    This function is called once at start of model execution. If you
275    *    have states that should be initialized once, this is the place
276    *    to do it.
277    */
278 static void mdlStart(SimStruct *S)
279 {
280     int_T shift;
281     int_T mode;
282     int_T filter;
283     int_T mask;
284
285     if (mf624_init(NULL) != 0)
286         return;
287
288     mask = IRCCTRL_IRC0MODE_mask | IRCCTRL_IRC0COUNT_mask |
289            IRCCTRL_IRC0RESET_mask | IRCCTRL_IRC0FILTER_mask;
290
291     IWORK_CHANNEL(S) = PRM_CHANNEL(S);
292     IWORK_GATING_VALUE(S) = PRM_COUNTER_GATING(S);
293     IWORK_USE_GATING_INPUT(S) = (IWORK_GATING_VALUE(S) == -1)? 1: 0;
294     IWORK_RESET_VALUE(S) = PRM_RESET_CONTROL(S);
295     IWORK_USE_RESET_INPUT(S) = (IWORK_RESET_VALUE(S) == -1)? 1: 0;
296
297     mode = PRM_COUNTER_MODE(S);
298     filter = PRM_DIGITAL_FILTER(S);
299
300     IWORK_IRCCTRL(S) =
301         __val2mfld(IRCCTRL_IRC0MODE_mask, mode) |
302         (IWORK_USE_GATING_INPUT(S)? 0 :
303             __val2mfld(IRCCTRL_IRC0COUNT_mask, IWORK_GATING_VALUE(S))) |
304         (IWORK_USE_RESET_INPUT(S)? 0 :
305             __val2mfld(IRCCTRL_IRC0RESET_mask, IWORK_RESET_VALUE(S))) |
306         __val2mfld(IRCCTRL_IRC0FILTER_mask, filter);
307
308     shift = IWORK_CHANNEL(S) * IRCCTRL_CHANNEL_SHIFT;
309
310     IRC_mode_change(mfst, mask << shift, IWORK_IRCCTRL(S) << shift);
311
312     mdlInitializeConditions(S);
313 }
314 #endif /*  MDL_START */
315
316
317
318 /* Function: mdlOutputs =======================================================
319  * Abstract:
320  *    In this function, you compute the outputs of your S-function
321  *    block.
322  */
323 static void mdlOutputs(SimStruct *S, int_T tid)
324 {
325     int32_T *y = ssGetOutputPortSignal(S,0);
326
327     if (mf624_check(S) != 0)
328         return;
329
330     y[0] = mf624_read32(MFST2REG(mfst, 4, irc_channel2reg[IWORK_CHANNEL(S)]));
331 }
332
333
334
335 #define MDL_UPDATE  /* Change to #undef to remove function */
336 #if defined(MDL_UPDATE)
337   /* Function: mdlUpdate ======================================================
338    * Abstract:
339    *    This function is called once for every major integration time step.
340    *    Discrete states are typically updated here, but this function is useful
341    *    for performing any tasks that should only take place once per
342    *    integration step.
343    */
344 static void mdlUpdate(SimStruct *S, int_T tid)
345 {
346     int_T mask = 0;
347     int_T shift;
348     int_T inp_num = 0;
349
350     if (mf624_check(S) != 0)
351         return;
352
353     if (IWORK_USE_GATING_INPUT(S)) {
354         const uint8_T *u = (const uint8_T*) ssGetInputPortSignal(S, inp_num);
355         if (*u != IWORK_GATING_VALUE(S)) {
356             IWORK_GATING_VALUE(S) = *u;
357             IWORK_IRCCTRL(S) = (IWORK_IRCCTRL(S) & ~IRCCTRL_IRC0COUNT_mask) |
358                 __val2mfld(IRCCTRL_IRC0COUNT_mask, IWORK_GATING_VALUE(S));
359             mask |= IRCCTRL_IRC0COUNT_mask;
360         }
361         inp_num++;
362     }
363
364     if (IWORK_USE_RESET_INPUT(S)) {
365         const uint8_T *u = (const uint8_T*) ssGetInputPortSignal(S, inp_num);
366         if (*u != IWORK_RESET_VALUE(S)) {
367             IWORK_RESET_VALUE(S) = *u;
368             IWORK_IRCCTRL(S) = (IWORK_IRCCTRL(S) & ~IRCCTRL_IRC0RESET_mask) |
369                 __val2mfld(IRCCTRL_IRC0RESET_mask, IWORK_RESET_VALUE(S));
370             mask |= IRCCTRL_IRC0RESET_mask;
371         }
372         inp_num++;
373     }
374
375     if (mask) {
376         shift = IWORK_CHANNEL(S) * IRCCTRL_CHANNEL_SHIFT;
377         IRC_mode_change(mfst, mask << shift, IWORK_IRCCTRL(S) << shift);
378     }
379 }
380 #endif /* MDL_UPDATE */
381
382
383
384 #undef MDL_DERIVATIVES  /* Change to #undef to remove function */
385 #if defined(MDL_DERIVATIVES)
386   /* Function: mdlDerivatives =================================================
387    * Abstract:
388    *    In this function, you compute the S-function block's derivatives.
389    *    The derivatives are placed in the derivative vector, ssGetdX(S).
390    */
391   static void mdlDerivatives(SimStruct *S)
392   {
393   }
394 #endif /* MDL_DERIVATIVES */
395
396
397
398 /* Function: mdlTerminate =====================================================
399  * Abstract:
400  *    In this function, you should perform any actions that are necessary
401  *    at the termination of a simulation.  For example, if memory was
402  *    allocated in mdlStart, this is the place to free it.
403  */
404 static void mdlTerminate(SimStruct *S)
405 {
406     mf624_done();
407 }
408
409
410 /*======================================================*
411  * See sfuntmpl_doc.c for the optional S-function methods *
412  *======================================================*/
413
414 /*=============================*
415  * Required S-function trailer *
416  *=============================*/
417
418 #ifdef  MATLAB_MEX_FILE    /* Is this file being compiled as a MEX-file? */
419 #include "simulink.c"      /* MEX-file interface mechanism */
420 #else
421 #include "cg_sfun.h"       /* Code generation registration function */
422 #endif