Friday, November 3, 2023

Handling left over carriage return

Lines in text files created in Windows end with '\r\n'. If you read that text file in Linux with C++ getline(), your line will have a '\r' at the end because in Linux, getline() only gets rid of '\n'. If you have code that reads a certain number of characters and converts it to floating point using std::stod(), you might get std::invalid_argument exception when trying to read multiple values. You can use the following to take care of this problem:

Simulink signal

After generating code from a Simulink model, if you want to read the value of a parameter inside the model which is not an output port, you can use signals. In Matlab R2022b, signal definition is different from R2019a. The following R2022b method (assuming you have Embedded Coder) is only valid if you generate C code, I have not been able to find a way to generate signal code for C++:
  1. Open Simulink model
  2. Open Configuration Parameter window, go to Code Generation
  3. System target file: ert.tlc (Embedded Coder)
  4. Language: C
  5. In Simulink APPS menu, click on Embedded Coder, A C CODE tabs appears to the right of APPS menu
  6. Find the signal line you want the generate code for and double click on it, give it a name, e.g. "mySignal"
  7. Single click on signal line, a pop up will appear, click on the left-most item, "Add selected signals to code mappings"
  8. Under C CODE tab, click on Code Interface and then click Default Code Mappings
  9. A Code Mappings panel will appear at the bottom of model
  10. Click on right most tab, Signals/States
  11. Under Signals, find mySignal
  12. Click to the right of mySignal (Store Class column), change Auto to Model Default.
  13. Generate code by pressing ctrl + b
  14. If your model name was MyModel, the generated code will have a file called MyModel_ert_rtw/MyModel.h containing the data structure MyModel_B which has mySignal as a field that you can access from your own C/C++ code. 
  15. If your code is C++, dont forget to use include in C wrapper: extern "C" {#include "MyModel_ert_rtw/MyModel.h"}