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