STM MATLAB Simulator
Loading...
Searching...
No Matches
MCU.c
Go to the documentation of this file.
1/**
2**************************************************************************
3* @file MCU.c
4* @brief Исходный код S-Function.
5**************************************************************************
6@details
7Данный файл содержит функции S-Function, который вызывает MATLAB.
8**************************************************************************
9@note
10Описание функций по большей части сгенерировано MATLAB'ом, поэтому на английском
11**************************************************************************/
12
13/**
14 * @addtogroup WRAPPER_SFUNC S-Function funtions
15 * @ingroup MCU_WRAPPER
16 * @brief Дефайны и функции блока S-Function
17 * @details Здесь собраны функции, с которыми непосредственно работает S-Function
18 * @note Описание функций по большей части сгенерировано MATLAB'ом, поэтому на английском
19 * @{
20 */
21
22#define S_FUNCTION_NAME MCU
23#define S_FUNCTION_LEVEL 2
24
25#include "mcu_wrapper_conf.h"
26
27#define MDL_UPDATE ///< для подключения mdlUpdate()
28/**
29 * @brief Update S-Function at every step of simulation
30 * @param S - pointer to S-Function (library struct from "simstruc.h")
31 * @details Abstract:
32 * This function is called once for every major integration time step.
33 * Discrete states are typically updated here, but this function is useful
34 * for performing any tasks that should only take place once per
35 * integration step.
36 */
37static void mdlUpdate(SimStruct *S)
38{
39 // get time of simulation
40 time_T TIME = ssGetT(S);
41
42 //---------------SIMULATE MCU---------------
43 MCU_Step_Simulation(S, TIME); // SIMULATE MCU
44 //------------------------------------------
45}//end mdlUpdate
46
47/**
48 * @brief Writting outputs of S-Function
49 * @param S - pointer to S-Function (library struct from "simstruc.h")
50 * @details Abstract:
51 * In this function, you compute the outputs of your S-function
52 * block. Generally outputs are placed in the output vector(s),
53 * ssGetOutputPortSignal.
54 */
55static void mdlOutputs(SimStruct *S)
56{
58}//end mdlOutputs
59
60#define MDL_CHECK_PARAMETERS /* Change to #undef to remove function */
61#if defined(MDL_CHECK_PARAMETERS) && defined(MATLAB_MEX_FILE)
62static void mdlCheckParameters(SimStruct *S)
63{
64 int i;
65
66 // Проверяем и принимаем параметры и разрешаем или запрещаем их менять
67 // в процессе моделирования
68 for (i=0; i<1; i++)
69 {
70 // Input parameter must be scalar or vector of type double
71 if (!mxIsDouble(ssGetSFcnParam(S,i)) || mxIsComplex(ssGetSFcnParam(S,i)) ||
72 mxIsEmpty(ssGetSFcnParam(S,i)))
73 {
74 ssSetErrorStatus(S,"Input parameter must be of type double");
75 return;
76 }
77 // Параметр м.б. только скаляром, вектором или матрицей
78 if (mxGetNumberOfDimensions(ssGetSFcnParam(S,i)) > 2)
79 {
80 ssSetErrorStatus(S,"Параметр м.б. только скаляром, вектором или матрицей");
81 return;
82 }
83// sim_dt = mxGetPr(ssGetSFcnParam(S,0))[0];
84 // Parameter not tunable
85// ssSetSFcnParamTunable(S, i, SS_PRM_NOT_TUNABLE);
86 // Parameter tunable (we must create a corresponding run-time parameter)
87 ssSetSFcnParamTunable(S, i, SS_PRM_TUNABLE);
88 // Parameter tunable only during simulation
89// ssSetSFcnParamTunable(S, i, SS_PRM_SIM_ONLY_TUNABLE);
90
91 }//for (i=0; i<NPARAMS; i++)
92
93}//end mdlCheckParameters
94#endif //MDL_CHECK_PARAMETERS
95static void mdlInitializeSizes(SimStruct *S)
96{
97 ssSetNumSFcnParams(S, 1);
98 // Кол-во ожидаемых и фактических параметров должно совпадать
99 if(ssGetNumSFcnParams(S) == ssGetSFcnParamsCount(S))
100 {
101 // Проверяем и принимаем параметры
102 mdlCheckParameters(S);
103 }
104 else
105 {
106 return;// Parameter mismatch will be reported by Simulink
107 }
108
109 // set up discrete states
110 ssSetNumContStates(S, 0); // number of continuous states
111 ssSetNumDiscStates(S, DISC_STATES_WIDTH); // number of discrete states
112
113 // set up input port
114 if (!ssSetNumInputPorts(S, 1)) return;
115 for (int i = 0; i < IN_PORT_NUMB; i++)
116 ssSetInputPortWidth(S, i, IN_PORT_WIDTH);
117 ssSetInputPortDirectFeedThrough(S, 0, 0);
118 ssSetInputPortRequiredContiguous(S, 0, 1); // direct input signal access
119
120 // set up output port
121 if (!ssSetNumOutputPorts(S, OUT_PORT_NUMB)) return;
122 for (int i = 0; i < OUT_PORT_NUMB; i++)
123 ssSetOutputPortWidth(S, i, OUT_PORT_WIDTH);
124
125
126 ssSetNumSampleTimes(S, 1);
127
128
129 ssSetNumRWork( S, 5); // number of real work vector elements
130 ssSetNumIWork( S, 5); // number of integer work vector elements
131 ssSetNumPWork( S, 0); // number of pointer work vector elements
132 ssSetNumModes( S, 0); // number of mode work vector elements
133 ssSetNumNonsampledZCs( S, 0); // number of nonsampled zero crossings
134
135
136 ssSetRuntimeThreadSafetyCompliance(S, RUNTIME_THREAD_SAFETY_COMPLIANCE_TRUE);
137 /* Take care when specifying exception free code - see sfuntmpl.doc */
138 ssSetOptions(S, SS_OPTION_EXCEPTION_FREE_CODE);
139
140
141}
142
143#define MDL_START /* Change to #undef to remove function */
144#if defined(MDL_START)
145/**
146 * @brief Initialize S-Function at start of simulation
147 * @param S - pointer to S-Function (library struct from "simstruc.h")
148 * @details Abstract:
149 * This function is called once at start of model execution. If you
150 * have states that should be initialized once, this is the place
151 * to do it.
152 */
153static void mdlStart(SimStruct *S)
154{
156}
157#endif // MDL_START
158
159/**
160 * @brief Initialize Sample Time of Simulation
161 * @param S - pointer to S-Function (library struct from "simstruc.h")
162 * @details Abstract:
163 * This function is used to specify the sample time(s) for your
164 * S-function. You must register the same number of sample times as
165 * specified in ssSetNumSampleTimes.
166 */
167static void mdlInitializeSampleTimes(SimStruct *S)
168{
169 // Шаг дискретизации
170 hmcu.SIM_Sample_Time = mxGetPr(ssGetSFcnParam(S,NPARAMS-1))[0];
171
172 // Register one pair for each sample time
173 ssSetSampleTime(S, 0, hmcu.SIM_Sample_Time);
174 ssSetOffsetTime(S, 0, 0.0);
175}
176
177/**
178 * @brief Terminate S-Function at the end of simulation
179 * @param S - pointer to S-Function (library struct from "simstruc.h")
180 * @details Abstract:
181 * In this function, you should perform any actions that are necessary
182 * at the termination of a simulation. For example, if memory was
183 * allocated in mdlStart, this is the place to free it.
184 */
185static void mdlTerminate(SimStruct *S)
186{
187 hmcu.fMCU_Stop = 1;
188 ResumeThread(hmcu.hMCUThread);
189 WaitForSingleObject(hmcu.hMCUThread, 10000);
191 mexUnlock();
192}
193
194
195/** WRAPPER_SFUNC
196 * @}
197 */
198
199#ifdef MATLAB_MEX_FILE /* Is this file being compiled as a
200 MEX-file? */
201#include "simulink.c" /* MEX-file interface mechanism */
202#else
203#include "cg_sfun.h" /* Code generation registration
204 function */
205#endif
void SIM_Initialize_Simulation(void)
Инициализация симуляции МК.
void SIM_deInitialize_Simulation(void)
Деинициализация симуляции МК.
void MCU_Step_Simulation(SimStruct *S, time_T time)
Симуляция МК на один такт симуляции.
Definition mcu_wrapper.c:53
#define IN_PORT_NUMB
number of input ports
SIM__MCUHandleTypeDef hmcu
Хендл для управления потоком программы МК
Definition mcu_wrapper.c:16
#define OUT_PORT_NUMB
number of output ports
#define DISC_STATES_WIDTH
width of discrete states array
#define IN_PORT_WIDTH
width of input ports
#define OUT_PORT_WIDTH
width of output ports
#define NPARAMS
number of input parametrs (only Ts)
static void mdlStart(SimStruct *S)
Initialize S-Function at start of simulation.
Definition MCU.c:153
static void mdlTerminate(SimStruct *S)
Terminate S-Function at the end of simulation.
Definition MCU.c:185
static void mdlInitializeSampleTimes(SimStruct *S)
Initialize Sample Time of Simulation.
Definition MCU.c:167
static void mdlOutputs(SimStruct *S)
Writting outputs of S-Function.
Definition MCU.c:55
static void mdlInitializeSizes(SimStruct *S)
Definition MCU.c:95
static void mdlUpdate(SimStruct *S)
Update S-Function at every step of simulation.
Definition MCU.c:37
void SIM_writeOutputs(SimStruct *S)
Формирование выходов S-Function.
Заголовочный файл для оболочки МК.
double SIM_Sample_Time
sample time of simulation
unsigned fMCU_Stop
флаг для выхода из потока программы МК
HANDLE hMCUThread
Хендл для потока МК