Сделана документация на то, что есть сейчас

This commit is contained in:
2024-10-16 16:03:37 +03:00
parent 6a08b0462d
commit 8939ab257f
750 changed files with 10725 additions and 350180 deletions

View File

@@ -1,17 +1,40 @@
/**
**************************************************************************
* @file MCU.c
* @brief Исходный код S-Function.
**************************************************************************
@details
Данный файл содержит функции S-Function, который вызывает MATLAB.
**************************************************************************
@note
Описание функций по большей части сгенерировано MATLAB'ом, поэтому на английском
**************************************************************************/
/**
* @addtogroup WRAPPER_SFUNC S-Function funtions
* @ingroup MCU_WRAPPER
* @brief Дефайны и функции блока S-Function
* @details Здесь собраны функции, с которыми непосредственно работает S-Function
* @note Описание функций по большей части сгенерировано MATLAB'ом, поэтому на английском
* @{
*/
#define S_FUNCTION_NAME MCU
#define S_FUNCTION_LEVEL 2
#include "mcu_wrapper_conf.h"
#define MDL_UPDATE
/* Function: mdlUpdate ====================================================
* Abstract:
#define MDL_UPDATE ///< для подключения mdlUpdate()
/**
* @brief Update S-Function at every step of simulation
* @param S - pointer to S-Function (library struct from "simstruc.h")
* @details Abstract:
* This function is called once for every major integration time step.
* Discrete states are typically updated here, but this function is useful
* for performing any tasks that should only take place once per
* integration step.
*/
static void mdlUpdate(SimStruct *S, int_T tid)
static void mdlUpdate(SimStruct *S)
{
// get time of simulation
time_T TIME = ssGetT(S);
@@ -21,13 +44,15 @@ static void mdlUpdate(SimStruct *S, int_T tid)
//------------------------------------------
}//end mdlUpdate
/* Function: mdlOutputs ===================================================
* Abstract:
/**
* @brief Writting outputs of S-Function
* @param S - pointer to S-Function (library struct from "simstruc.h")
* @details Abstract:
* In this function, you compute the outputs of your S-function
* block. Generally outputs are placed in the output vector(s),
* ssGetOutputPortSignal.
*/
static void mdlOutputs(SimStruct *S, int_T tid)
static void mdlOutputs(SimStruct *S)
{
SIM_writeOutputs(S);
}//end mdlOutputs
@@ -117,8 +142,10 @@ static void mdlInitializeSizes(SimStruct *S)
#define MDL_START /* Change to #undef to remove function */
#if defined(MDL_START)
/* Function: mdlStart =====================================================
* Abstract:
/**
* @brief Initialize S-Function at start of simulation
* @param S - pointer to S-Function (library struct from "simstruc.h")
* @details Abstract:
* This function is called once at start of model execution. If you
* have states that should be initialized once, this is the place
* to do it.
@@ -129,8 +156,10 @@ static void mdlStart(SimStruct *S)
}
#endif // MDL_START
/* Function: mdlInitializeSampleTimes =========================================
* Abstract:
/**
* @brief Initialize Sample Time of Simulation
* @param S - pointer to S-Function (library struct from "simstruc.h")
* @details Abstract:
* This function is used to specify the sample time(s) for your
* S-function. You must register the same number of sample times as
* specified in ssSetNumSampleTimes.
@@ -145,20 +174,28 @@ static void mdlInitializeSampleTimes(SimStruct *S)
ssSetOffsetTime(S, 0, 0.0);
}
/* Function: mdlTerminate =====================================================
* Abstract:
/**
* @brief Terminate S-Function at the end of simulation
* @param S - pointer to S-Function (library struct from "simstruc.h")
* @details Abstract:
* In this function, you should perform any actions that are necessary
* at the termination of a simulation. For example, if memory was
* allocated in mdlStart, this is the place to free it.
*/
static void mdlTerminate(SimStruct *S)
{
hmcu.MCU_Stop = 1;
hmcu.fMCU_Stop = 1;
ResumeThread(hmcu.hMCUThread);
WaitForSingleObject(hmcu.hMCUThread, 10000);
SIM_deInitialize_Simulation();
mexUnlock();
}
/** WRAPPER_SFUNC
* @}
*/
#ifdef MATLAB_MEX_FILE /* Is this file being compiled as a
MEX-file? */
#include "simulink.c" /* MEX-file interface mechanism */

View File

@@ -1,25 +1,37 @@
/**************************************************************************
/**
**************************************************************************
* @file mcu_wrapper.c
* @brief Исходный код оболочки МК.
**************************************************************************
@details
Данный файл содержит функции для симуляции МК в Simulink (S-Function).
**************************************************************************/
#include "mcu_wrapper_conf.h"
SIM__MCUHandleTypeDef hmcu; // для управления контекстом программы МК
/**
* @addtogroup WRAPPER_CONF
* @{
*/
double SystemClockDouble = 0; // для симуляции системных тиков, прока просто по приколу
double SystemClock_step = 0; // для симуляции системных тиков, прока просто по приколу
uint64_t SystemClock; // для симуляции системных тиков, прока просто по приколу
SIM__MCUHandleTypeDef hmcu; ///< Хендл для управления потоком программы МК
double SystemClockDouble = 0; ///< Счетчик в формате double для точной симуляции системных тиков С промежуточными значений
uint64_t SystemClock; ///< Счетчик тактов для симуляции системных тиков (в целочисленном формате)
double SystemClock_step = 0; ///< Шаг тиков для их симуляции, в формате double
/** MCU_WRAPPER
* @}
*/
//-------------------------------------------------------------//
//-----------------CONTROLLER SIMULATE FUNCTIONS---------------//
/* THREAD FOR MCU APP */
/**
* @brief Main function of MCU app.
* @brief Главная функция приложения МК.
* @details Функция с которой начинается выполнение кода МК. Выход из данной функции происходит только в конце симуляции @ref mdlTerminate
*/
extern int main(void); // extern while from main.c
/** THREAD FOR MCU APP */
/**
* @brief Thread that run MCU code.
* @brief Поток приложения МК.
* @details Поток, который запускает и выполняет код МК (@ref main).
*/
unsigned __stdcall MCU_App_Thread(void) {
@@ -27,13 +39,16 @@ unsigned __stdcall MCU_App_Thread(void) {
return 0; // end thread
// note: this return will reached only at the end of simulation, when all whiles will be skipped due to @ref sim_while
}
/** SIMULATE MCU FOR ONE SIMULATION STEP */
/* SIMULATE MCU FOR ONE SIMULATION STEP */
/**
* @brief Read from simulink S-Block Inputs and write to MCU I/O ports.
* @param time - current time of simulation (in second).
* @brief Симуляция МК на один такт симуляции.
* @param S - указатель на структуру S-Function из "simstruc.h"
* @param time - текущее время симуляции.
* @details Запускает поток, который выполняет код МК и управляет ходом потока:
* Если прошел таймаут, поток прерывается, симулируется периферия
* и на следующем шаге поток возобнавляется.
*
* Вызывается из mdlUpdate()
*/
void MCU_Step_Simulation(SimStruct* S, time_T time)
{
@@ -50,9 +65,9 @@ void MCU_Step_Simulation(SimStruct* S, time_T time)
MCU_writeOutputs(S); // запись портов (по факту запись в буфер. запись в порты в mdlOutputs)
}
/** SIMULATE MCU PERIPHERAL */
/* SIMULATE MCU PERIPHERAL */
/**
* @brief Simulate peripheral of MCU
* @brief Симуляция периферии МК
* @details Пользовательский код, который симулирует работу периферии МК.
*/
void MCU_Periph_Simulation(void)
@@ -64,11 +79,11 @@ void MCU_Periph_Simulation(void)
Simulate_TIMs();
}
/** READ INPUTS S-FUNCTION TO MCU REGS */
/* READ INPUTS S-FUNCTION TO MCU REGS */
/**
* @brief Read from simulink S-Block Inputs and write to MCU I/O ports.
* @param in - inputs of S-Function.
* @details Пользовательский код, который записывает в порты ввода-вывода из disc.
* @brief Считывание входов S-Function в порты ввода-вывода.
* @param S - указатель на структуру S-Function из "simstruc.h"
* @details Пользовательский код, который записывает порты ввода-вывода из входов S-Function.
*/
void MCU_readInputs(SimStruct* S)
{
@@ -78,18 +93,18 @@ void MCU_readInputs(SimStruct* S)
SFUNC_to_GPIO(IN);
}
/** WRITE OUTPUTS BUFFER S-FUNCTION FROM MCU REGS*/
/* WRITE OUTPUTS BUFFER S-FUNCTION FROM MCU REGS*/
/**
* @brief Read from MCU I/O ports and write to simulink S-Block Outputs.
* @param disc - discrete array of S-Function. Outputs would be written from disc.
* @details Пользовательский код, который записывает в disc порты ввода-вывода.
* @brief Запись портов ввода-вывода в буфер выхода S-Function
* @param S - указатель на структуру S-Function из "simstruc.h"
* @details Пользовательский код, который записывает буфер выходов S-Function из портов ввода-вывода.
*/
void MCU_writeOutputs(SimStruct* S)
{
/* Get S-Function descrete array */
real_T* DISC = ssGetDiscStates(S);
real_T* Out_Buff = ssGetDiscStates(S);
GPIO_to_SFUNC(DISC);
GPIO_to_SFUNC(Out_Buff);
}
//-----------------CONTROLLER SIMULATE FUNCTIONS---------------//
//-------------------------------------------------------------//
@@ -98,16 +113,16 @@ void MCU_writeOutputs(SimStruct* S)
//-------------------------------------------------------------//
//----------------------SIMULINK FUNCTIONS---------------------//
/** WRITE OUTPUTS OF S-BLOCK */
/* WRITE OUTPUTS OF S-BLOCK */
/**
* @brief Write S-Function Output ports to inputs.
* @param disc - discrete array of S-Function. Outputs would be written from disc.
* @details Пользовательский код, который записывает выходы S-Function.
* @brief Формирование выходов S-Function.
* @param S - указатель на структуру S-Function из "simstruc.h"
* @details Пользовательский код, который записывает выходы S-Function из буфера.
*/
void SIM_writeOutputs(SimStruct* S)
{
real_T* GPIO;
real_T* DISC = ssGetDiscStates(S);
real_T* Out_Buff = ssGetDiscStates(S);
//-------------WRITTING GPIOS---------------
for (int j = 0; j < PORT_NUMB; j++)
@@ -115,30 +130,33 @@ void SIM_writeOutputs(SimStruct* S)
GPIO = ssGetOutputPortRealSignal(S, j);
for (int i = 0; i < PORT_WIDTH; i++)
{
GPIO[i] = DISC[j * PORT_WIDTH + i];
DISC[j * PORT_WIDTH + i] = 0;
GPIO[i] = Out_Buff[j * PORT_WIDTH + i];
Out_Buff[j * PORT_WIDTH + i] = 0;
}
}
//------------------------------------------
}
/** MCU WRAPPER DEINITIALIZATION */
/* MCU WRAPPER DEINITIALIZATION */
/**
* @brief Initialize structures and variables for simulating MCU.
* @details Пользовательский код, который будет настраивать все структуры для симуляции.
* @brief Инициализация симуляции МК.
* @details Пользовательский код, который создает поток для приложения МК
и настраивает симулятор МК для симуляции.
*/
void SIM_Initialize_Simulation(void)
{
// инициализация потока, который будет выполнять код МК
hmcu.hMCUThread = (HANDLE)CreateThread(NULL, 0, MCU_App_Thread, 0, CREATE_SUSPENDED, &hmcu.idMCUThread);
/* user initialization */
Initialize_Periph_Sim();
/* wrapper initialization */
SystemClock_step = SystemCoreClock * hmcu.SIM_Sample_Time; // set system clock step
// инициализация потока, который будет выполнять код МК
hmcu.hMCUThread = (HANDLE)CreateThread(NULL, 0, MCU_App_Thread, 0, CREATE_SUSPENDED, &hmcu.idMCUThread);
}
/** MCU WRAPPER DEINITIALIZATION */
/* MCU WRAPPER DEINITIALIZATION */
/**
* @brief Deinitialize structures and variables for simulating MCU.
* @brief Деинициализация симуляции МК.
* @details Пользовательский код, который будет очищать все структуры после окончания симуляции.
*/
void SIM_deInitialize_Simulation(void)
@@ -149,12 +167,3 @@ void SIM_deInitialize_Simulation(void)
deInitialize_MCU();
}
//-------------------------------------------------------------//
////-----------INIT WRAPPER-----------
//if (hmcu.MCU_Start) // если надо получть указатель на "начало" стека
//{ // сброс флаша, чтобы сюда больше не попадать
// hmcu.MCU_Start = 0;
// // инициализация потока, который будет выполнять код МК
// hmcu.hMCUThread = (HANDLE)_beginthreadex(NULL, 0, MCU_App_Thread, 0, 0x00000004, &hmcu.idMCUThread); /* 0x00000004 - CREATE_SUSPENDED */
//}
////----------------------------------

View File

@@ -1,10 +1,25 @@
/**************************************************************************
/**
**************************************************************************
* @dir ../MCU_Wrapper
* @brief <b> Папка с исходным кодом оболочки МК. </b>
* @details
В этой папке содержаться оболочка(англ. wrapper) для запуска и контроля
эмуляции микроконтроллеров в MATLAB (любого МК, не только STM).
Оболочка представляет собой S-Function - блок в Simulink, который работает
по скомпилированому коду. Компиляция происходит с помощью MSVC-компилятора.
**************************************************************************/
/**
**************************************************************************
* @file mcu_wrapper_conf.h
* @brief Заголовочный файл для оболочки МК.
**************************************************************************
@details
Главный заголовочный файл для матлаба. Включает дейфайны для S-Function,
объявляет базовые функции для симуляции МК и подключает базовые библиотеки:
для симуляции "stm32fxxx_matlab_conf.h"
для S-Function "simstruc.h"
для потоков <process.h>
- для симуляции "stm32fxxx_matlab_conf.h"
- для S-Function "simstruc.h"
- для потоков <process.h>
**************************************************************************/
#ifndef _CONTROLLER_H_
#define _CONTROLLER_H_
@@ -16,15 +31,15 @@
/**
* @addtogroup MCU_WRAPPER
* @brief Stuff for running MCU app in MATLAB
* @defgroup MCU_WRAPPER MCU Wrapper
* @brief Всякое для оболочки МК
*/
/**
* @addtogroup WRAPPER_CONF
* @addtogroup WRAPPER_CONF Wrapper Configuration
* @ingroup MCU_WRAPPER
* @brief Configurations for wrapper to simulating MCU
* @details Здесь дефайнами задается параметры оболочки, которая управляет кодом МК
* @brief Параметры конфигурации для оболочки МК
* @details Здесь дефайнами задается параметры оболочки, которые определяют как она будет работать
* @{
*/
@@ -49,11 +64,10 @@
/**
* @ingroup MCU_WRAPPER
* @addtogroup MCU_WRAPPER
* @{
*/
typedef void* HANDLE; ///< MCU handle typedef
/**
@@ -69,7 +83,7 @@ typedef struct {
double SIM_Sample_Time; ///< sample time of simulation
}SIM__MCUHandleTypeDef;
extern SIM__MCUHandleTypeDef hmcu; ///< extern для видимости переменной во всех файлах
extern SIM__MCUHandleTypeDef hmcu; // extern для видимости переменной во всех файлах
//-------------------------------------------------------------//
//------------------ SIMULINK WHILE DEFINES -----------------//
@@ -89,7 +103,7 @@ extern SIM__MCUHandleTypeDef hmcu; ///< extern для видимо
* При выставлении флага окончания симуляции, все while будут пропускаться
* и поток сможет дойти до конца функции main и завершить себя.
*/
#define sim_while(_expression_) while((_expression_)&&(hmcu.MCU_Stop == 0))
#define sim_while(_expression_) while((_expression_)&&(hmcu.fMCU_Stop == 0))
/* DEFAULT WHILE */
/**
@@ -107,25 +121,25 @@ extern SIM__MCUHandleTypeDef hmcu; ///< extern для видимо
//-------------------------------------------------------------//
//---------------- SIMULATE FUNCTIONS PROTOTYPES -------------//
/* step simulation */
/* Step simulation */
void MCU_Step_Simulation(SimStruct *S, time_T time);
/* MCU peripheral simulation */
void MCU_Periph_Simulation(void);
/* initialize MCU simulation */
/* Initialize MCU simulation */
void SIM_Initialize_Simulation(void);
/* deinitialize MCU simulation */
/* Deinitialize MCU simulation */
void SIM_deInitialize_Simulation(void);
/* read inputs S-function */
void MCU_readInputs(real_T* in);
/* Read inputs S-function */
void MCU_readInputs(SimStruct* S);
/* write outputs S-function (disc states) */
void MCU_writeOutputs(real_T* disc);
/* Write pre-outputs S-function (out_buff states) */
void MCU_writeOutputs(SimStruct* S);
/* write outputs of block of S-Function*/
/* Write outputs of block of S-Function*/
void SIM_writeOutput(SimStruct* S);
//---------------- SIMULATE FUNCTIONS PROTOTYPES -------------//
//-------------------------------------------------------------//
@@ -133,4 +147,17 @@ void SIM_writeOutput(SimStruct* S);
/** MCU_WRAPPER
* @}
*/
#endif // _CONTROLLER_H_
#endif // _CONTROLLER_H_
//-------------------------------------------------------------//
//---------------------BAT FILE DESCRIBTION--------------------//
/**
* @file run_mex.bat
* @brief Батник для компиляции оболочки МК.
* @details
* Вызывается в матлабе из mexing.m.
*
* Исходный код батника:
* @include F:\Work\Projects\MATLAB\matlab_stm_emulate\MCU_Wrapper\run_mex.bat
*/

View File

@@ -35,7 +35,7 @@ for %%f in (.\Code\PWM\*.c) do (
:: -----MCU LIBRARIES STUFF----
:: заголовочные файлы
set includes_MCU= -I".\MCU_STM32F4xx_Matlab"^
-I".\MCU_STM32F4xx_Matlab\Drivers\STM32F4xx_SIMULINK"^
-I".\MCU_STM32F4xx_Matlab\STM32F4xx_SIMULINK"^
-I".\MCU_STM32F4xx_Matlab\Drivers\CMSIS"^
-I".\MCU_STM32F4xx_Matlab\Drivers\STM32F4xx_HAL_Driver\Inc"^
-I".\MCU_STM32F4xx_Matlab\Drivers\STM32F4xx_HAL_Driver\Inc\Legacy"
@@ -62,9 +62,9 @@ set code_MCU=.\MCU_STM32F4xx_Matlab\Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_h
:: --------MCU SIMULATOR-------
:: код, которая будет симулировать перефирию МК в симулинке
set code_MCU_Sim= .\MCU_STM32F4xx_Matlab\stm32f4xx_matlab_conf.c^
.\MCU_STM32F4xx_Matlab\Drivers\STM32F4xx_SIMULINK\stm32f4xx_matlab_gpio.c^
.\MCU_STM32F4xx_Matlab\Drivers\STM32F4xx_SIMULINK\stm32f4xx_matlab_tim.c^
.\MCU_STM32F4xx_Matlab\Drivers\STM32F4xx_SIMULINK\stm32f4xx_periph_registers.c
.\MCU_STM32F4xx_Matlab\STM32F4xx_SIMULINK\stm32f4xx_matlab_gpio.c^
.\MCU_STM32F4xx_Matlab\STM32F4xx_SIMULINK\stm32f4xx_matlab_tim.c^
.\MCU_STM32F4xx_Matlab\STM32F4xx_SIMULINK\stm32f4xx_periph_registers.c
::-------------------------------------------------------------------------