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