Pages

Tuesday, July 20, 2010

how to trap errors in firmware

Programming a microcontroller sometimes makes you frustrated. Its because it has errors which we don't know where. So these is a little example:

-----------
for(;;)
{
   valueA = functionA();
   valueB = functionB();
   valueC = functionC();
}
------------ but my microcontroller seems not work??
Lets create a trap using leds attached on portA
--------------
//for(;;)
//{ //just make sure this piece of code run only one time
  portA = 1; 
  valueA = functionA();
  portA = 2;
  valueB = functionB();
  portA = 3;
  valueC = functionC();
  portA = 4;
//}
-------------
now look at leds, :
  • value = 4; it means all functions is working.
  • value = 2; it means functionA is never done, is must have some infinite loop like while (true value), or for(i=0;i>2;i--) but i value never goes below 2, etc. Now you know that the errors is inside functionA, you may delete the trap and create new trap just inside functionA
Another way is create some monitor to evaluate value. For example:
Suppose you have UART function working properly and called SendUsart(char data)
---------

for(;;)
{
   SendUsart('A'); SendUsart('0');
   valueA = functionA();
   SendUsart('B'); SendUsart(valueA);
   valueB = functionB();
   SendUsart('C'); SendUsart(valueB);
   valueC = functionC();
   SendUsart('D'); SendUsart(valueC);
   _delay_ms(500); //just to make your hyperterminal not flooded :D
}---------
now lets look at your hyperterminal:
....A0B2C3D5A0B2C3D5A0B2C3D5...
just look at the repeated value. Let suppose you have :
functionA(){
  return 50;
}
functionB(){
  return (valueA + 1);
}
functionC(){ 
  return (valueB + 1);
}
and the reading....
B2 : because on functionA you put 50, it will send 2 (ascii value of 2 is 50 decimal)
C3 : inside functionB, you add valueA with 1, the result is 51 (ascii : 3)
D5 : inside functionC, you add valueB with 1, the result must be 52 (ascii: 4), but in the reading is 53 (ascii value : 5). So the valueB must be changed somewhere. Usually from interrupt routine. You may check the routine.

so that is how using trap and monitor for finding bug inside firmware. Experienced programmer know where to put traps and monitor in error-prone routine.

No comments: