There are several possible ways to generate code which reads data from a binary file and uses those values as block parameters. One of the easiest ways is to manually include the code to read the binary file in 'ert_main.c' file of the generated code. For its implementation, the block parameters whose values are read from the binary file during execution, need to be declared as Simulink global parameters.
Please find the attached example model 'read_bin.slx' and a binary file 'abc.bin'. This model has a block parameter value 'gain' in the 'Gain' block whose value is supposed to be read from the binary file 'abc.bin' everytime we run the executable file generated from code generation. Please open the attached model and execute the following steps -
1. Create a global parameter 'gain' in the MATLAB Workspace by entering the following commands in the MATLAB Command Window:
>> gain = Simulink.Parameter;
>> gain.Value = 0;
>> gain.CoderInfo.StorageClass = 'SimulinkGlobal';
2. Generate code and the executable file by building the model using Ctrl+B.
3. Navigate to, and open the generated code file 'ert_main.c' in the folder 'read_bin_ert_rtw'.
4. Include the following code inside the main function 'int_T main(int_T argc, const char *argv[])', in the 'ert_main.c' file:
/* Open file for reading */
FILE *f;
f = fopen("abc.bin", "rb");
fread(&read_bin_P.gain, 1,sizeof(double),f);
printf("gain is %lf",read_bin_P.gain);
fclose(f);
5. Generate the executable again by executing the following command:
6. Make sure to find the new generated executable file 'read_bin.exe' in the Current directory or the Parent directory and have the 'abc.bin' file stored in the same directory. Please run the executable by entering the following command:
7. To verify the gain value, load the generated MAT logged file ' read_bin.mat' in MATLAB Workspace, and inspect the values of 'rt_yout'. The output would be 5 times (constant * gain), the value read from the binary file.
8. Modify the value in the binary file by entering the following commands:
>> fid = fopen ('abc.bin', 'w');
>> fwrite(fid, 2400, 'double');
>> fclose(fid);
9. Repeat steps 6 and 7. The output has changed to 12000 (5* 2400) now.
Best Answer