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