]> rtime.felk.cvut.cz Git - mf624-simulink.git/blob - sfAnalogInput.c
Allow build of m624 AnalogInput by C89 compiler - i.e. MS Visual C.
[mf624-simulink.git] / sfAnalogInput.c
1 /*
2  * S-function to support analog inputs on Humusoft MF624 card
3  *
4  * Copyright (C) 2013 Michal Kreč <krecmich@fel.cvut.cz>
5  * Copyright (C) 2013 Michal Sojka <sojkam1@fel.cvut.cz>
6  *
7  * Department of Control Engineering
8  * Faculty of Electrical Engineering
9  * Czech Technical University in Prague (CTU)
10  *
11  * The S-Function for ERT Linux can be distributed in compliance
12  * with GNU General Public License (GPL) version 2 or later.
13  * Other licence can negotiated with CTU.
14  *
15  * Next exception is granted in addition to GPL.
16  * Instantiating or linking compiled version of this code
17  * to produce an application image/executable, does not
18  * by itself cause the resulting application image/executable
19  * to be covered by the GNU General Public License.
20  * This exception does not however invalidate any other reasons
21  * why the executable file might be covered by the GNU Public License.
22  * Publication of enhanced or derived S-function files is required
23  * although.
24  *
25  * Linux ERT code is available from
26  *    http://rtime.felk.cvut.cz/gitweb/ert_linux.git
27  * More CTU Linux target for Simulink components are available at
28  *    http://lintarget.sourceforge.net/
29  *
30  * sfuntmpl_basic.c by The MathWorks, Inc. has been used to accomplish
31  * required S-function structure.
32  */
33
34 /*
35  * You must specify the S_FUNCTION_NAME as the name of your S-function
36  * (i.e. replace sfuntmpl_basic with the name of your S-function).
37  */
38
39 #define S_FUNCTION_NAME  sfAnalogInput
40 #define S_FUNCTION_LEVEL 2
41 #define MASK_PRM(S)     (mxGetScalar(ssGetSFcnParam(S, 0)))
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
49 #include <stdint.h>
50 #include <malloc.h>
51
52 #ifndef WITHOUT_HW
53 #include "mf624_SIMULINK.h"
54 #endif /*WITHOUT_HW*/
55
56   #ifdef __GNUC__
57     #define my_popcount __builtin_popcount
58   #else
59     int my_popcount(uint32_t patt)
60     {
61        int pops = 0;
62        while (patt) {
63           if (patt & 1)
64               pops++;
65           patt >>= 1;
66        }
67        return pops;
68     }
69   #endif
70
71
72 /* Error handling
73  * --------------
74  *
75  * You should use the following technique to report errors encountered within
76  * an S-function:
77  *
78  *       ssSetErrorStatus(S,"Error encountered due to ...");
79  *       return;
80  *
81  * Note that the 2nd argument to ssSetErrorStatus must be persistent memory.
82  * It cannot be a local variable. For example the following will cause
83  * unpredictable errors:
84  *
85  *      mdlOutputs()
86  *      {
87  *         char msg[256];         {ILLEGAL: to fix use "static char msg[256];"}
88  *         sprintf(msg,"Error due to %s", string);
89  *         ssSetErrorStatus(S,msg);
90  *         return;
91  *      }
92  *
93  * See matlabroot/simulink/src/sfuntmpl_doc.c for more details.
94  */
95
96 /*====================*
97  * S-function methods *
98  *====================*/
99
100 /* Function: mdlInitializeSizes ===============================================
101  * Abstract:
102  *    The sizes information is used by Simulink to determine the S-function
103  *    block's characteristics (number of inputs, outputs, states, etc.).
104  */
105 static void mdlInitializeSizes(SimStruct *S)
106 {
107     int ADCCMask;
108     int i;
109     int ADCChannels;
110     /* See sfuntmpl_doc.c for more details on the macros below */
111
112     ssSetNumSFcnParams(S, 1);  /* Number of expected parameters */
113     if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) {
114         /* Return if number of expected != number of actual parameters */
115         ssSetErrorStatus(S,"Parameter mismatch");
116         return;
117     }
118
119     ssSetNumContStates(S, 0);
120     ssSetNumDiscStates(S, 0);
121     
122     ADCCMask = (int)MASK_PRM(S);
123
124     if(ADCCMask > 255 || ADCCMask < 0) {
125         ssSetErrorStatus(S,"Invalid parameter mask, set to 0-255");
126     }
127     
128     ADCChannels = my_popcount((uint32_t)ADCCMask);           //Counts number of set bits in ADCCMask
129
130     if (!ssSetNumInputPorts(S, 0)) return;
131     
132     
133
134     if (!ssSetNumOutputPorts(S, ADCChannels)) return;
135     for(i=0; i < ADCChannels;i++){
136         ssSetOutputPortWidth(S, i, 1);
137     }
138     ssSetNumSampleTimes(S, 1);
139     ssSetNumRWork(S, 0);
140     ssSetNumIWork(S, 1);
141     ssSetNumPWork(S, 0);
142     ssSetNumModes(S, 0);
143     ssSetNumNonsampledZCs(S, 0);
144
145     /* Specify the sim state compliance to be same as a built-in block */
146     ssSetSimStateCompliance(S, USE_DEFAULT_SIM_STATE);
147
148     ssSetOptions(S, 0);
149     
150
151 }
152
153
154
155 /* Function: mdlInitializeSampleTimes =========================================
156  * Abstract:
157  *    This function is used to specify the sample time(s) for your
158  *    S-function. You must register the same number of sample times as
159  *    specified in ssSetNumSampleTimes.
160  */
161 static void mdlInitializeSampleTimes(SimStruct *S)
162 {
163     ssSetSampleTime(S, 0, CONTINUOUS_SAMPLE_TIME);
164     ssSetOffsetTime(S, 0, FIXED_IN_MINOR_STEP_OFFSET);
165
166 }
167
168
169
170 #undef MDL_INITIALIZE_CONDITIONS   /* Change to #undef to remove function */
171 #if defined(MDL_INITIALIZE_CONDITIONS)
172   /* Function: mdlInitializeConditions ========================================
173    * Abstract:
174    *    In this function, you should initialize the continuous and discrete
175    *    states for your S-function block.  The initial states are placed
176    *    in the state vector, ssGetContStates(S) or ssGetRealDiscStates(S).
177    *    You can also perform any other initialization activities that your
178    *    S-function may require. Note, this routine will be called at the
179    *    start of simulation and if it is present in an enabled subsystem
180    *    configured to reset states, it will be call when the enabled subsystem
181    *    restarts execution to reset the states.
182    */
183   static void mdlInitializeConditions(SimStruct *S)
184   {
185   }
186 #endif /* MDL_INITIALIZE_CONDITIONS */
187
188
189
190 #define MDL_START  /* Change to #undef to remove function */
191 #if defined(MDL_START) 
192   /* Function: mdlStart =======================================================
193    * Abstract:
194    *    This function is called once at start of model execution. If you
195    *    have states that should be initialized once, this is the place
196    *    to do it.
197    */
198   static void mdlStart(SimStruct *S)
199   {
200     int ADCChannels;
201
202   #ifndef WITHOUT_HW
203     if (mf624_init(NULL) != 0)
204         return;
205   #endif /*WITHOUT_HW*/
206
207     int ADCCMask = (int)MASK_PRM(S);
208
209     if(ADCCMask > 255 || ADCCMask < 0) {
210         ssSetErrorStatus(S,"Invalid parameter mask, set to 0-255");
211     }
212
213     ADCChannels = my_popcount((uint32_t)ADCCMask);           //Counts number of set bits in ADCCMask
214
215     ssSetIWorkValue(S, 0, ADCChannels);
216   #ifndef WITHOUT_HW
217     mfst->ADC_enabled = ADCCMask;
218     mfst->ADC_enabled &= 0xFF;
219
220     mf624_write16(mfst->ADC_enabled, MFST2REG(mfst, 2, ADCTRL_reg));
221   #endif /*WITHOUT_HW*/
222   }
223 #endif /*  MDL_START */
224
225
226
227 /* Function: mdlOutputs =======================================================
228  * Abstract:
229  *    In this function, you compute the outputs of your S-function
230  *    block.
231  */
232 static void mdlOutputs(SimStruct *S, int_T tid)
233 {
234
235     int ADCChannels = ssGetIWorkValue(S, 0);
236     real_T**       y;
237     int i;
238     int res,res1;
239   #ifndef WITHOUT_HW
240     if (mf624_check(S) != 0)
241         return;
242
243     // Activate trigger to start conversion
244     mf624_read16(MFST2REG(mfst, 2, ADSTART_reg));
245   #endif /*WITHOUT_HW*/
246
247     y = alloca(ADCChannels * sizeof(*y));
248
249     for(i=0; i < ADCChannels;i++){
250         y[i]=ssGetOutputPortSignal(S,i);
251     }
252
253   #ifndef WITHOUT_HW
254     // Check if conversion has finished
255     while((mf624_read32(MFST2REG(mfst, 0, GPIOC_reg)) & GPIOC_EOLC_mask)) { 
256         for (i = 0; i < 1000; i++) {} // small wait
257     }
258
259     for(i=1; i < ADCChannels;i+=2){
260         res = mf624_read32(MFST2REG(mfst, 2, ADDATA0_reg));
261         res1= res >> 16;
262         res = res & 0xFFFF;
263         *y[i-1] = (real_T) (10.0 * ((int16_t) (res << 2)) / (double) 0x8000);
264         *y[i] = (real_T) (10.0 * ((int16_t) (res1 << 2)) / (double) 0x8000);
265     }
266
267     if(i == ADCChannels){
268         res = mf624_read16(MFST2REG(mfst, 2, ADDATA0_reg));
269         *y[ADCChannels-1]=(real_T)(10.0 * ((int16_t) (res << 2)) / (double) 0x8000);
270     }
271   #else /*WITHOUT_HW*/
272     for(i=0; i < ADCChannels; i++){
273         *y[i] = 0;
274     }
275   #endif /*WITHOUT_HW*/
276 }
277
278
279
280 #undef MDL_UPDATE  /* Change to #undef to remove function */
281 #if defined(MDL_UPDATE)
282   /* Function: mdlUpdate ======================================================
283    * Abstract:
284    *    This function is called once for every major integration time step.
285    *    Discrete states are typically updated here, but this function is useful
286    *    for performing any tasks that should only take place once per
287    *    integration step.
288    */
289   static void mdlUpdate(SimStruct *S, int_T tid)
290   {
291   }
292 #endif /* MDL_UPDATE */
293
294
295
296 #undef MDL_DERIVATIVES  /* Change to #undef to remove function */
297 #if defined(MDL_DERIVATIVES)
298   /* Function: mdlDerivatives =================================================
299    * Abstract:
300    *    In this function, you compute the S-function block's derivatives.
301    *    The derivatives are placed in the derivative vector, ssGetdX(S).
302    */
303   static void mdlDerivatives(SimStruct *S)
304   {
305   }
306 #endif /* MDL_DERIVATIVES */
307
308
309
310 /* Function: mdlTerminate =====================================================
311  * Abstract:
312  *    In this function, you should perform any actions that are necessary
313  *    at the termination of a simulation.  For example, if memory was
314  *    allocated in mdlStart, this is the place to free it.
315  */
316 static void mdlTerminate(SimStruct *S)
317 {
318   #ifndef WITHOUT_HW
319     mf624_done(S);
320   #endif /*WITHOUT_HW*/
321 }
322
323
324 /*======================================================*
325  * See sfuntmpl_doc.c for the optional S-function methods *
326  *======================================================*/
327
328 /*=============================*
329  * Required S-function trailer *
330  *=============================*/
331
332 #ifdef  MATLAB_MEX_FILE    /* Is this file being compiled as a MEX-file? */
333 #include "simulink.c"      /* MEX-file interface mechanism */
334 #else
335 #include "cg_sfun.h"       /* Code generation registration function */
336 #endif