]> rtime.felk.cvut.cz Git - mf624-simulink.git/blob - sfPWMOutput.c
Use correct header file for alloca for Linux build.
[mf624-simulink.git] / sfPWMOutput.c
1 /*
2  * S-function to support PWM Output 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  sfPWMOutput
35 #define S_FUNCTION_LEVEL 2
36
37 /*
38  * The S-function has next parameters
39  *
40  * PWM Channel number
41  * PWM Frequency   - value -1 for external input
42  */
43
44 #define PRM_CHANNEL(S)          (mxGetScalar(ssGetSFcnParam(S, 0)))
45 #define PRM_FREQUENCY(S)        (mxGetScalar(ssGetSFcnParam(S, 1)))
46
47 #define PRM_COUNT                      2
48
49 #define IWORK_IDX_CHANNEL              0
50 #define IWORK_IDX_CTR_MODE             1
51 #define IWORK_IDX_USE_FREQUENCY_INPUT  2
52 #define IWORK_IDX_LAST_MODE            3
53 enum {CTR_LAST_MODE_OUT0, CTR_LAST_MODE_OUT1, CTR_LAST_MODE_PWM};
54
55 #define IWORK_COUNT                    4
56
57 #define IWORK_CHANNEL(S)               (ssGetIWork(S)[IWORK_IDX_CHANNEL])
58 #define IWORK_CTR_MODE(S)              (ssGetIWork(S)[IWORK_IDX_CTR_MODE])
59 #define IWORK_USE_FREQUENCY_INPUT(S)   (ssGetIWork(S)[IWORK_IDX_USE_FREQUENCY_INPUT])
60 #define IWORK_LAST_MODE(S)             (ssGetIWork(S)[IWORK_IDX_LAST_MODE])
61
62 #define RWORK_IDX_BASE_FREQUENCY       0
63
64 #define RWORK_COUNT                    1
65
66 #define RWORK_BASE_FREQUENCY(S)        (ssGetRWork(S)[RWORK_IDX_BASE_FREQUENCY])
67
68
69 /*
70  * Need to include simstruc.h for the definition of the SimStruct and
71  * its associated macro definitions.
72  */
73 #include "simstruc.h"
74
75
76 #ifndef WITHOUT_HW
77 #include "mf624_SIMULINK.h"
78 #endif /*WITHOUT_HW*/
79
80 #define CTR_MAX_PWM_CHANNEL            3
81
82 #ifndef WITHOUT_HW
83 typedef struct {
84     int32_T STATUS_reg;
85     int32_T MODE_reg;
86     int32_T CTR_reg;
87     int32_T A_reg;
88     int32_T B_reg;
89     int32_T CTRL_reg;
90 } ctr_channel_regs_t;
91
92 static const ctr_channel_regs_t ctr_channel2regs[] = {
93     {CTR0STATUS_reg, CTR0MODE_reg, CTR0_reg, CTR0A_reg, CTR0B_reg, CTRXCTRL_reg},
94     {CTR1STATUS_reg, CTR1MODE_reg, CTR1_reg, CTR1A_reg, CTR1B_reg, CTRXCTRL_reg},
95     {CTR2STATUS_reg, CTR2MODE_reg, CTR2_reg, CTR2A_reg, CTR2B_reg, CTRXCTRL_reg},
96     {CTR3STATUS_reg, CTR3MODE_reg, CTR3_reg, CTR3A_reg, CTR3B_reg, CTRXCTRL_reg},
97     {CTR4STATUS_reg, CTR4MODE_reg, CTR4_reg, CTR4A_reg, -1,        CTRXCTRL_reg}
98 };
99 #endif /*WITHOUT_HW*/
100
101 /* Error handling
102  * --------------
103  *
104  * You should use the following technique to report errors encountered within
105  * an S-function:
106  *
107  *       ssSetErrorStatus(S,"Error encountered due to ...");
108  *       return;
109  *
110  * Note that the 2nd argument to ssSetErrorStatus must be persistent memory.
111  * It cannot be a local variable. For example the following will cause
112  * unpredictable errors:
113  *
114  *      mdlOutputs()
115  *      {
116  *         char msg[256];         {ILLEGAL: to fix use "static char msg[256];"}
117  *         sprintf(msg,"Error due to %s", string);
118  *         ssSetErrorStatus(S,msg);
119  *         return;
120  *      }
121  *
122  * See matlabroot/simulink/src/sfuntmpl_doc.c for more details.
123  */
124
125 /*====================*
126  * S-function methods *
127  *====================*/
128
129 #define MDL_CHECK_PARAMETERS   /* Change to #undef to remove function */
130 #if defined(MDL_CHECK_PARAMETERS) && defined(MATLAB_MEX_FILE)
131   /* Function: mdlCheckParameters =============================================
132    * Abstract:
133    *    mdlCheckParameters verifies new parameter settings whenever parameter
134    *    change or are re-evaluated during a simulation. When a simulation is
135    *    running, changes to S-function parameters can occur at any time during
136    *    the simulation loop.
137    */
138 static void mdlCheckParameters(SimStruct *S)
139 {
140     if ((PRM_CHANNEL(S) < 0) || (PRM_CHANNEL(S) > CTR_MAX_PWM_CHANNEL))
141         ssSetErrorStatus(S, "valid PWM channel is 0, 1, 2, or 3");
142     if ((PRM_FREQUENCY(S) <= 0) && (PRM_FREQUENCY(S) != -1))
143         ssSetErrorStatus(S, "Frequency out of valid range");
144 }
145 #endif /* MDL_CHECK_PARAMETERS */
146
147
148
149 /* Function: mdlInitializeSizes ===============================================
150  * Abstract:
151  *    The sizes information is used by Simulink to determine the S-function
152  *    block's characteristics (number of inputs, outputs, states, etc.).
153  */
154 static void mdlInitializeSizes(SimStruct *S)
155 {
156     int_T nInputPorts  = 1;
157
158     ssSetNumSFcnParams(S, PRM_COUNT);  /* Number of expected parameters */
159     if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) {
160         /* Return if number of expected != number of actual parameters */
161         ssSetErrorStatus(S, "2-parameters requited: Channel, PWM Frequncy or -1");
162         return;
163     }
164
165     ssSetNumContStates(S, 0);
166     ssSetNumDiscStates(S, 0);
167
168   #if defined(MDL_CHECK_PARAMETERS) && defined(MATLAB_MEX_FILE)
169     mdlCheckParameters(S);
170     if (ssGetErrorStatus(S) != NULL) return;
171   #endif
172
173     if (PRM_FREQUENCY(S) == -1)
174         nInputPorts++;
175
176     if (!ssSetNumInputPorts(S, nInputPorts)) return;
177     ssSetInputPortWidth(S, 0, 1);
178     ssSetInputPortRequiredContiguous(S, 0, true); /*direct input signal access*/
179
180     if (PRM_FREQUENCY(S) == -1) {
181         ssSetInputPortWidth(S, 1, 1);
182         ssSetInputPortRequiredContiguous(S, 1, true); /*direct input signal access*/
183     }
184
185     /*
186      * Set direct feedthrough flag (1=yes, 0=no).
187      * A port has direct feedthrough if the input is used in either
188      * the mdlOutputs or mdlGetTimeOfNextVarHit functions.
189      * See matlabroot/simulink/src/sfuntmpl_directfeed.txt.
190      */
191     ssSetInputPortDirectFeedThrough(S, 0, 0);
192
193     if (!ssSetNumOutputPorts(S, 0)) return;
194
195     ssSetNumSampleTimes(S, 1);
196     ssSetNumRWork(S, RWORK_COUNT);
197     ssSetNumIWork(S, IWORK_COUNT);
198     ssSetNumPWork(S, 0);
199     ssSetNumModes(S, 0);
200     ssSetNumNonsampledZCs(S, 0);
201
202     /* Specify the sim state compliance to be same as a built-in block */
203     ssSetSimStateCompliance(S, USE_DEFAULT_SIM_STATE);
204
205     ssSetOptions(S, 0);
206 }
207
208
209
210 /* Function: mdlInitializeSampleTimes =========================================
211  * Abstract:
212  *    This function is used to specify the sample time(s) for your
213  *    S-function. You must register the same number of sample times as
214  *    specified in ssSetNumSampleTimes.
215  */
216 static void mdlInitializeSampleTimes(SimStruct *S)
217 {
218     ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME);
219     ssSetOffsetTime(S, 0, 0.0);
220 }
221
222
223
224 #define MDL_INITIALIZE_CONDITIONS   /* Change to #undef to remove function */
225 #if defined(MDL_INITIALIZE_CONDITIONS)
226   /* Function: mdlInitializeConditions ========================================
227    * Abstract:
228    *    In this function, you should initialize the continuous and discrete
229    *    states for your S-function block.  The initial states are placed
230    *    in the state vector, ssGetContStates(S) or ssGetRealDiscStates(S).
231    *    You can also perform any other initialization activities that your
232    *    S-function may require. Note, this routine will be called at the
233    *    start of simulation and if it is present in an enabled subsystem
234    *    configured to reset states, it will be call when the enabled subsystem
235    *    restarts execution to reset the states.
236    */
237   static void mdlInitializeConditions(SimStruct *S)
238   {
239   }
240 #endif /* MDL_INITIALIZE_CONDITIONS */
241
242
243
244 #define MDL_START  /* Change to #undef to remove function */
245 #if defined(MDL_START)
246   /* Function: mdlStart =======================================================
247    * Abstract:
248    *    This function is called once at start of model execution. If you
249    *    have states that should be initialized once, this is the place
250    *    to do it.
251    */
252 static void mdlStart(SimStruct *S)
253 {
254     int32_T ctr_mode;
255
256   #ifndef WITHOUT_HW
257     if (mf624_init(NULL) != 0)
258         return;
259
260     IWORK_CHANNEL(S) = PRM_CHANNEL(S);
261
262     IWORK_USE_FREQUENCY_INPUT(S) = (PRM_FREQUENCY(S) == -1)? 1: 0;
263
264     RWORK_BASE_FREQUENCY(S) = 50e6;
265
266     IWORK_CTR_MODE(S) = 0;
267
268     IWORK_LAST_MODE(S) = CTR_LAST_MODE_OUT0;
269
270     /* Force output low during startup */
271     ctr_mode = __val2mfld(CTR_MODE_OUTPUT_CONTROL_mask, CTR_MODE_OUTPUT_CONTROL_FORCE_LO);
272     mf624_write32(ctr_mode, MFST2REG(mfst, 4, ctr_channel2regs[IWORK_CHANNEL(S)].MODE_reg));
273   #endif /*WITHOUT_HW*/
274 }
275 #endif /*  MDL_START */
276
277
278
279 /* Function: mdlOutputs =======================================================
280  * Abstract:
281  *    In this function, you compute the outputs of your S-function
282  *    block.
283  */
284 static void mdlOutputs(SimStruct *S, int_T tid)
285 {
286     real_T duty = *(const real_T*) ssGetInputPortSignal(S, 0);
287     real_T frequency;
288     int32_T ctr_mode;
289     int32_T ctr_ctrl;
290     real_T T;
291     real_T T1;
292     uint32_T T1_uint;
293     uint32_T T2_uint;
294
295   #ifndef WITHOUT_HW
296     if (mf624_check(S) != 0)
297             return;
298
299     if (IWORK_USE_FREQUENCY_INPUT(S))
300         frequency = *(const real_T*) ssGetInputPortSignal(S, 1);
301     else
302         frequency = PRM_FREQUENCY(S);
303
304
305     if (duty>=1)
306     {
307         if (IWORK_LAST_MODE(S) != CTR_LAST_MODE_OUT1) {
308             IWORK_LAST_MODE(S) = CTR_LAST_MODE_OUT1;
309             ctr_mode = __val2mfld(CTR_MODE_OUTPUT_CONTROL_mask, CTR_MODE_OUTPUT_CONTROL_FORCE_HI);
310             mf624_write32(ctr_mode, MFST2REG(mfst, 4, ctr_channel2regs[IWORK_CHANNEL(S)].MODE_reg));
311             /*printf("duty >=1: ctr_mode = 0x%08lx\n", ctr_mode);*/
312         }
313         return;
314     }
315     if ((duty<=0) || (frequency <= 0) || (frequency > RWORK_BASE_FREQUENCY(S) / 2))
316     {
317         if (IWORK_LAST_MODE(S) != CTR_LAST_MODE_OUT0) {
318             IWORK_LAST_MODE(S) = CTR_LAST_MODE_OUT0;
319             ctr_mode = __val2mfld(CTR_MODE_OUTPUT_CONTROL_mask, CTR_MODE_OUTPUT_CONTROL_FORCE_LO);
320             mf624_write32(ctr_mode, MFST2REG(mfst, 4, ctr_channel2regs[IWORK_CHANNEL(S)].MODE_reg));
321             /*printf("duty <=0: ctr_mode = 0x%08lx\n", ctr_mode);*/
322         }
323         return;
324     }
325
326     T = RWORK_BASE_FREQUENCY(S) / frequency;
327
328     T1 = T * duty;
329
330     if (T <= 0xffffffff)
331       T2_uint = T;
332     else
333       T2_uint = 0xffffffff;
334
335     if (T1 <= 0xffffffff)
336       T1_uint = T1;
337     else
338       T1_uint = 0xffffffff;
339
340     if (!T1_uint)
341         T1_uint = 1;
342     if (T1_uint >= T2_uint)
343         T1_uint = T2_uint - 1;
344
345     T2_uint -= T1_uint;
346
347     mf624_write32(T1_uint, MFST2REG(mfst, 4, ctr_channel2regs[IWORK_CHANNEL(S)].A_reg));
348     mf624_write32(T2_uint, MFST2REG(mfst, 4, ctr_channel2regs[IWORK_CHANNEL(S)].B_reg));
349
350     if (IWORK_LAST_MODE(S) != CTR_LAST_MODE_PWM) {
351         IWORK_LAST_MODE(S) = CTR_LAST_MODE_PWM;
352
353         ctr_ctrl = CTRXCTRL_CTR0STOP_mask | CTRXCTRL_CTR0LOAD_mask | CTRXCTRL_CTR0RESET_mask | CTRXCTRL_CTR0TRESET_mask;
354         ctr_ctrl <<= IWORK_CHANNEL(S) * CTRXCTRL_CHANNEL_SHIFT;
355         mf624_write32(ctr_ctrl, MFST2REG(mfst, 4, ctr_channel2regs[IWORK_CHANNEL(S)].CTRL_reg));
356
357         ctr_mode = IWORK_CTR_MODE(S) |
358                    __val2mfld(CTR_MODE_COUNT_DIR_mask, CTR_MODE_COUNT_DIR_DOWN) |
359                    __val2mfld(CTR_MODE_REPETITION_mask, CTR_MODE_REPETITION_ENABLED) |
360                    __val2mfld(CTR_MODE_LOAD_TOGGLE_mask, CTR_MODE_LOAD_TOGGLE_ENABLED) |
361                    __val2mfld(CTR_MODE_OUTPUT_TOGGLE_mask, CTR_MODE_OUTPUT_TOGGLE_ENABLED) |
362                    __val2mfld(CTR_MODE_OUTPUT_CONTROL_mask, CTR_MODE_OUTPUT_CONTROL_DIRECT) |
363                    __val2mfld(CTR_MODE_TRIGGER_SOURCE_mask, CTR_MODE_TRIGGER_SOURCE_DISABLED) |
364                    __val2mfld(CTR_MODE_TRIGGER_TYPE_mask, CTR_MODE_TRIGGER_TYPE_DISABLED) |
365                    __val2mfld(CTR_MODE_RETRIGGER_mask, CTR_MODE_RETRIGGER_DISABLED);
366
367         /*printf("duty %e: ctr_mode = 0x%08lx T1_uint = 0x%08lx, T2_uint = 0x%08lx\n", duty, ctr_mode, T1_uint, T2_uint);*/
368
369         mf624_write32(ctr_mode, MFST2REG(mfst, 4, ctr_channel2regs[IWORK_CHANNEL(S)].MODE_reg));
370
371         ctr_ctrl = CTRXCTRL_CTR0START_mask;
372         ctr_ctrl <<= IWORK_CHANNEL(S) * CTRXCTRL_CHANNEL_SHIFT;
373         mf624_write32(ctr_ctrl, MFST2REG(mfst, 4, ctr_channel2regs[IWORK_CHANNEL(S)].CTRL_reg));
374     }
375   #endif /*WITHOUT_HW*/
376 }
377
378
379
380 #undef MDL_UPDATE  /* Change to #undef to remove function */
381 #if defined(MDL_UPDATE)
382   /* Function: mdlUpdate ======================================================
383    * Abstract:
384    *    This function is called once for every major integration time step.
385    *    Discrete states are typically updated here, but this function is useful
386    *    for performing any tasks that should only take place once per
387    *    integration step.
388    */
389   static void mdlUpdate(SimStruct *S, int_T tid)
390   {
391   }
392 #endif /* MDL_UPDATE */
393
394
395
396 #undef MDL_DERIVATIVES  /* Change to #undef to remove function */
397 #if defined(MDL_DERIVATIVES)
398   /* Function: mdlDerivatives =================================================
399    * Abstract:
400    *    In this function, you compute the S-function block's derivatives.
401    *    The derivatives are placed in the derivative vector, ssGetdX(S).
402    */
403   static void mdlDerivatives(SimStruct *S)
404   {
405   }
406 #endif /* MDL_DERIVATIVES */
407
408
409
410 /* Function: mdlTerminate =====================================================
411  * Abstract:
412  *    In this function, you should perform any actions that are necessary
413  *    at the termination of a simulation.  For example, if memory was
414  *    allocated in mdlStart, this is the place to free it.
415  */
416 static void mdlTerminate(SimStruct *S)
417 {
418     int32_T ctr_mode;
419
420   #ifndef WITHOUT_HW
421     if (mf624_check(S) == 0) {
422         /* Force output low when finished */
423         ctr_mode = __val2mfld(CTR_MODE_OUTPUT_CONTROL_mask, CTR_MODE_OUTPUT_CONTROL_FORCE_LO);
424         mf624_write32(ctr_mode, MFST2REG(mfst, 4, ctr_channel2regs[IWORK_CHANNEL(S)].MODE_reg));
425     }
426
427     mf624_done();
428   #endif /*WITHOUT_HW*/
429 }
430
431
432 /*======================================================*
433  * See sfuntmpl_doc.c for the optional S-function methods *
434  *======================================================*/
435
436 /*=============================*
437  * Required S-function trailer *
438  *=============================*/
439
440 #ifdef  MATLAB_MEX_FILE    /* Is this file being compiled as a MEX-file? */
441 #include "simulink.c"      /* MEX-file interface mechanism */
442 #else
443 #include "cg_sfun.h"       /* Code generation registration function */
444 #endif