MATLAB: How can the Simulink model’s generated executable take keyboard inputs so that I can specify integers for an input Port at every step during execution

argumentcodegenembeddedEmbedded Coderinporttarget

I am building a Simulink model, and generating an executable for it. I am using rtwdemo_counter example to start.
How do I add keyboard inputs so that I can specify an integer for the input Port to the Amplifier at every step?

Best Answer

To use the executable file with inputs, you will have to modify several aspects of the generated code. You will have to be familiar with C/C++ development, in particular, input/output handling. Here is an example and guidelines to help you get started with this workflow.
Utilize keyboard inputs during program execution
You can use the keyboard to input numbers into the Inport-equivalent variable to the Amplifier in the generated code.
In the model configuration parameters, please ensure the following:
1) The solver type is set to Fixed-step.
2) Default parameter behavior under Optimization -> Signals and Parameters is set to "Tunable".
3) System target file under Code Generation is set to "ert.tlc".
4) "Generate code only" under Code Generation is unchecked.
5) In the "All Parameters" tab, search for "Generate an example main program" and check the box next to it.
6) Build model (generate code)
Inside the "rtwdemo_counter_step()" function, add the following C code *before *line 58 in rtwdemo_counter.c:
scanf("%i",&rtU.Input);
printf("integer = %i\n", rtU.Input);
The above will read numbers from your keyboard until you press enter, replace the value of rtU.Input with the new number, then display the value entered, and continue with the program. To step the executable program repeatedly, you will have to replace lines 86-92 in ert_main.c with something like this:
for(int i = 0; i <20; <i++)
{
rt_OneStep();
}
Note, every time you change the C code, you will have to go into the "rtw_demo_counter_ert_rtw" folder and run the bat script again:
>> !rtwdemo_counter.bat
Then go back to the top-level folder and run the executable to see your changes:
>> !rtwdemo_counter.exe
Utilize a file as inputs during program execution
Once the above example is understood and you can modify the generated code to provide inputs, you can make the executable more powerful by reading data from files during program execution. This is more involved but provides more power and flexiblity for your application. To see an example of how to read numbers from a file in C, take a look at the answers in the following link:
I have provided you with examples and a broad instructions on how to utilize inputs in C programming, after generating code from Simulink. I will close the case for record keeping purposes, but feel free to respond with any issues that may arise.