Page 338 - Programming Microcontrollers in C
P. 338

Table Look-Up    323

                   {
                       int i;
                       for(i=0;i< 256; i++)
                         printf(“ i = %d r = %d\n”,i,table_look_up(i));
                   }

                          where tlu.h contains the function and the table above. This code
                          compiles and runs on a MS-DOC PC, and the result is as expected.
                          Here, the program scans the entire input range and prints out the
                          resultant value at each point. A check of the outputs will show that
                          the function hits the break value at each break, and creates a linear
                          interpolation between all points. For values above or below the range,
                          the proper output is observed.
                              In a normal control system, there will often be need for several table
                          look-up operations. The above code is not too good in this case because
                          the code to do the look-up must be repeated with each table. This extra
                          code can be eliminated if the function table_look_up( ) is passed
                          two parameters: the first parameter is the interpolation value, and the
                          second value is a pointer to the look-up table as is shown below:

                   char table_look_up( char x_in, struct lut* table)
                   {
                       int i;
                       for(i=0;x_in>table->data[i].x && i<=table->entries; i++) ;
                   if(i>=table->entries)
                          return table->data[table->entries-1].y;
                       else if (i==0)
                          return table->data[0].y;
                       else
                          return table->data[i-1].y+
                              (((x_in-table->data[i-1].x)*table->data[i- 1].slope)>>8);
                   }

                              Listing 6-7: Table Look-Up, Version 2
                              This form of the table look-up should probably be used in all
                          cases. Here is another example of where it is wise to examine the
                          code generated by a compiler. It will not be listed here, but the as­
                          sembly code required for Listing 6-6 is 182 bytes long, and that for
                          listing 6-7 is but 142 bytes. This greatly improved utility automati­
                          cally gives a substantial savings in code.
                              It was pointed out that the compiler optimizer will sometimes
                          change the basic code dictated by the programmer. Perhaps, it should
   333   334   335   336   337   338   339   340   341   342   343