Page 119 -
P. 119

243_MasterPieces_02b.qxd  4/18/03  6:59 PM  Page 91




                                                                      The Learning Brick Sorter • Masterpiece 2  91



                    the Learning Brick Sorter adaptable to different situations.Thus, we won’t store any asso-
                    ciations between the colors and the bins, but we also won’t store any values to define
                    those colors.This way the Learning Brick Sorter will work with a set of any three colors,
                    provided that their readings are well separated.
                        A “color” (actually the amount of light reflected by that color) can be stored into a
                    single variable, but I find this approach a bit risky. If the user places the bricks at slightly
                    different distances from the light sensor, the same color can result in different readings.
                    For this reason, I chose to define colors using a range bounded by a lower and an upper
                    limit.The Learning Brick Sorter has three bins, thus we need three ranges for three dif-
                    ferent colors:

                    #define RANGES 3
                    int min[RANGES];      // lower limits of the ranges
                    int max[RANGES];      // upper limits of the ranges




                     NOTE
                         You don’t need to type any code, because you’ll find the complete program
                         included in the companion disk of this book.




                        To handle these ranges, we need an additional variable that tracks how many of them
                    have been used:
                    int top_range;        // highest used range index

                        Initially top_range is set to –1, meaning that no range has been used yet. When a
                    reading arrives, we scan the ranges from 0 to top_range, to see whether the value falls
                    inside one of the defined ranges. If it does, this means the color belongs to that of the
                    specified range, otherwise we increment top_range by one and define a new range.
                    light_value = SENSOR_1;
                    // search if the light value is contained in
                    // one of the already defined ranges
                    for(range=0;range<=top_range;range++) {
                       if (light_value>=min[range] && light_value<=max[range]) break;
                    }


                    // if not, define a new range
                    if (range>top_range) {
                       top_range++;
                       // if all ranges have been used, beep for error and terminate program
                       if (top_range>=RANGES) {
   114   115   116   117   118   119   120   121   122   123   124