Josh Goldberg / Mbed 2 deprecated count_pills

Dependencies:   Servo mbed

Revision:
0:15d3cdafd311
Child:
1:9ebe670d8a19
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/weight.cpp	Thu Dec 11 21:54:03 2014 +0000
@@ -0,0 +1,61 @@
+#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] = {23758, 24221, 24672, 25124, 25588, 26034}; // = {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 < 60; i++) { //will measure for ~3 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);
+}