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