Defect Detector – Code

The most interesting part of the code for our project was, without a doubt, the code used to filter out false positives read by the ADC. There were two main methods we utilized to do this:

  • Get a good threshold value
// in main

int baseline_reading[25];
for (int i = 0; i < 25; i++) {
    _delay_ms(100);
    baseline_reading[i] = last_result;
}
THRESHOLD = get_threshold(baseline_reading, 25);

CUTOFF = THRESHOLD + OFFSET;

/* … */

int get_threshold(int readings[], int read_count)
{
    float xbar = 0.0, s = 0.0;
    for (int i = 0; i < read_count; i++) {
        xbar += readings[i];
    }
    xbar /= read_count;
    for (int i = 0; i < read_count; i++) {
        s += squared(readings[i] - xbar);
    }
    s /= read_count - 1;
    s = sqrt(s);
    return (int) (xbar + 0.75 * s);
}

The first method employed is simply setting a good threshold that the readings must surpass in order for the program to act upon them. To obtain this threshold a number of readings are taken at the start of the program. These preliminary readings are then used to get a good baseline for the threshold by finding the arithmetic mean of them and adding a fraction of a standard deviation. The precise number of standard deviations we added was arrived at through trial and error.

  • Ensure that the reading is consistent
do {
     // busy loops 200 ms at a time until a sufficiently large weight is placed on the sensor
     int streak = 0;
     do {
         _delay_ms(100);
         if (last_result < THRESHOLD)
             streak = 0;
         else
             streak++;
     } while (streak < STREAK_THRESHOLD);
     streak = 0;
     // sorts the object appropriately
     sort_object(&mypwm, last_result, CUTOFF);
} while (1);

The other method employed is to ensure that the readings we get from the ADC are consistently significant. To do this, instead of calling the sort routine whenever a result is significant, we only call the sort routine when each of the last N results have been significant. This helps to filter out fleeting spikes of voltage read by the ADC whether they are from simple noise or from the spike that results when an object is dropped onto the sensor rather than placed on top of it.