Friday, June 19, 2020

Letters to a novice programmer

I decided to move software related posts to this blog. See my latest letter. Recently I saw C++ code similar to the following:
myAlgo.setInputs(inputStruct);
myAlgo.calculate();
myAlgo.getOutputs(outputStruct);
The correct way is to refactor calculate() method as follows:
outputStruct out = calculate(inputStruct)
Using this version would save the user of myAlgo from a couple of lines, he would not face the risk of forgetting to set inputs. In the previous version, if you forget to call setInputs(), the compiler will happily build your code and you will waste time finding the bug at run time. In the new version, if you forget to pass inputs to calculate(), it won't build and you will instantly see the bug.

Whenever you have multiple public initialization functions, try to combine them into a constructor. Your design should be such that when your code builds successfully, you should be confident that it has no initialization or finalizations related bugs. Let the compiler help you.

Tuesday, June 16, 2020

From Workspace uses first element as time

If you create a Simulink model with a From Workspace block and use it to get a vector, you will be surprised to see that the first element is missing:


The reason is that From Workspace treats the first element of a vector as time and the rest as data.

Tuesday, May 12, 2020

Applying derivative and integral on noisy data

Let's say you have a motion with sinusoidal acceleration, i.e. xddot(t) = sin(t). The analytic solution for speed and position will be xdot(t) = -cos(t)+1 (assuming zero initial speed) and x(t) = -sin(t) + t.  Let's say you don't know the analytical expressions of position, speed and acceleration and only have their values at a fixed sample rate. If you want to increase the samples, you can use Matlab's spline function.

If you have position as input and calculate speed and acceleration, if there is any noise in the signal, it will be amplified. If you have acceleration as input and calculate speed and position via integration, noise will be attenuated. Another advantage of using integration instead of derivation is that we can use linear interpolation since when integrating, we don't need smooth second derivatives. This both decreases computational load and lag due to two points in linear interpolation compared to four points in spline. See below Matlab code for an example:



Thursday, May 7, 2020

Mex only on file change

For large Simulink projects with lots of s-function, performing a mex of all files can be time consuming. Leaving it up to the user might result in simulation runs with older mex files because the user might forget to re-mex the updated file. You can automate the process as follows:
  • Create a hash list file that consists of file names used by s-functions and corresponding hashes.
  • Before simulation start, in InitFcn, 
    • Calculate hashes of files used by s-functions and compare them with the values saved in hash list file. Mark files whose hashes are different as "changed".
    • If an existing binary mex file date is earlier than any of the dates of the source files used in its build, mark that binary as "changed".
  • Mex files marked as "changed".
For hash calculation you can use [status, cmdout] = system(['certutil -hashfile', fileName, ' SHA256']) and parse cmdout via str=splitlines(cmdout); hash=str[2]; to get hash of file.

From Workspace Sample Time

Let's say you have a single Simulink model with plant and controller, and another that just has the plant.

If you save outputs of plant&controller with to workspace blocks, add from workspace blocks to plant only model and run it with outputs of plant&controller, you might see differences between results. In order to have a close match of results, you shouldn't leave the sample time of from workspace blocks as zero, you have to enter them equal to sample time of plant&controller model.

Tuesday, March 24, 2020

Documenting a real time system

A developer handbook is indispensible if you need to remember what you did a year ago (due to a bug or a new feature to be added) or if you want to bring a junior developer up to speed without baby sitting him. A good handbook should include the following:
  1. Introduction: Why does the system exist, what function does it serve?
  2. Components of the system, how they communicate with each other (serial, ethernet etc.). Photos of the real system and a mind map denoting peripherals (sensors, actuators) would be handy:

  3. Setup: All software and hardware setup procedures, links to software installation folders.
  4. Sanity tests to verify that setup works properly. For example, have a test to verify that the system really works in real time by comparing system time with an external time source. A very crude test would be using the timer in your smartphone.
  5. Development use cases: How to add a new state to the state machine.
  6. Design: 
    1. Architecture.
    2. Main workflow, especially external input/output.
    3. Task priorities and rationale.
    4. Design decisions and their reasons. Why is the current design the best one under existing constraints (time, budget, experience)? Why is there no simpler way to satisfy requirements? What were the disadvantages of the alternatives. Examples: Why did you write your own file transfer protocol instead of using an existing one? Why have you not used an OS like VxWorks but choose Micrium? Couldn't you have done it without an OS?
  7. Troubleshooting guide for frequent problems.

Thursday, March 12, 2020

HWIL development workflow

A typical HIL/HWIL development workflow starts with Simulink models and ends with code deployed on hardware with software that is expected to run in real time:

If there are differences between Simulink and Visual Studio runs, most of the time it is due to you forgetting to equalize all inputs. If you are sure about inputs being the same, the remaining sources of difference are details of floating point representations and sometime a block in Simulink generating wrong code. For example Aerospace blockset ECEF2LLA block code results in latitude lagging one time step behind, which does not occur during a Simulink run.

If there are differences between software running on hardware and Visual Studio results, it might be an indication of insufficient stack size allocation or tasks not meeting their deadlines. If you are lucky and have an advanced real time OS like VxWorks, it might throw a segmentation violation if there is too little stack available. If you don't want to count on luck, you have to test thoroughly, preferably using automated tests.