Josh Goldberg / Mbed 2 deprecated count_pills

Dependencies:   Servo mbed

weight.cpp

Committer:
jgoldberg
Date:
2014-12-12
Revision:
1:9ebe670d8a19
Parent:
0:15d3cdafd311

File content as of revision 1:9ebe670d8a19:

#include "mbed.h"
#include "weight.h"

static const int batches = 5; // number of times you will add batch_size number of pills for calibration
static const int batch_size = 10; // number of pills added per batch for calibration
static uint16_t cal_vals[batches + 1] = {23102, 23547, 23993, 24494, 24960, 25390}; // = {0}; // initialize to zero if re-calibrating
// calibration for 4,5  {23748, 23986, 24216, 24460, 24674};
// calibration for 5,10 {23758, 24221, 24672, 25124, 25588, 26034};
static int calibrated = 1; // change to 0 to re-calibrate

int calibrate_pills() {
    uint16_t val;
    uint16_t val_avg;
    calibrated = 0;
    
    for (int b = 0; b <= batches; b++) {
        myled1 = 0;
        if (b == 0) {
            pc.printf("Press enter when bottle is empty.\n\r");
        } else {
            pc.printf("Please add %d more pills and press enter. Total pills: %d\n\r", batch_size, b*batch_size);
        }
        pc.getc();
        myled1 = 1;
        myled2 = 0;
        pc.printf("Measuring...\n\r");
        mvgAvg(0,1);
        for (int i = 0; i < 100; i++) { //will measure for ~5 seconds
            val = myADC.read_u16();
            val_avg = mvgAvg(val, 0);
            pc.printf("%d\n\r", val_avg);
            wait(0.05);
        }
        cal_vals[b] = val_avg;
        pc.printf("Calibration value for %d pills is: %d\n\r", b*batch_size, cal_vals[b]);
        myled2 = 1;
    }
    calibrated = 1;
    return 0;
}

int measure_pills() {
    
    if (!calibrated) {
        calibrate_pills();
    }
    
    uint16_t val;
    uint16_t val_avg;
    float number_pills = 0;

    val = myADC.read_u16();
    val_avg = mvgAvg(val, 0);
    //pc.printf("raw: %d  avg: %d\n\r", val, val_avg);
    for (int b = 0; b < batches; b++) {
        if (val_avg <= cal_vals[b]) { break; }
        number_pills = (float) (val_avg - cal_vals[b]) / (cal_vals[b + 1] - cal_vals[b]) * batch_size + b * batch_size;
    }
    pc.printf("Number of pills: %f  rounded: %d\n\r", number_pills, round(number_pills));
    return round(number_pills);
}