Writing software as we design hardware
As a low-level software guy, I often have to work with electrical engineers to build custom hardware and software systems. I am constantly amazed by the tricks necessary to make the hardware part work and the experience needed to build reliable electrical components. I decided to apply the same techniques to my software.
First of all, I have noticed that electrical engineers often use ground planes on their boards. A ground plane is just a large area connected to the ground. This reduces the crosstalk effect, where the signal on two wires located near to each other may influence each other.
I did the same thing in my C programs. I have inserted large areas of zeroes between my functions:
int f (...)
{
...
}
char _ground_plane_1[1024] = {0};
int g (...)
{
...
}
char _ground_plane_2[1024] = {0};
int h (...)
{
...
}
The second important thing was about metastability. In a FPGA (an electronic device that you can customize so that it does what you want in hardware, to make it short), if you sample a signal while it is going from GND to Vcc and store it in a register, the register may take a value of Vcc/2 (I’ve seen this happen when sampling the input of a digital video camera). This value will be propagated and will eventually be resolved after passing through some gates into either GND or Vcc. The problem is that it may be resolved into different values at different places. To avoid this problem, you insert intermediate registers between the sampling of the signal and its propagation in the FPGA. There is a good chance that you get GND or Vcc after the first register. A better chance after the second one. A very good chance after the third one.
So in my code, I changed every assignment from a function result from:
int a = f (x, y);
into
int _a0 = f (x, y);
int _a1 = _a0;
int _a2 = _a1;
int a = _a2;
I ran my test programs and noticed that they were much more stable than before! I encourage everyone to do the same thing, in every programming language.
We have so much to learn from electrical engineering…