#Python Code to capture data points:
import serial
import mDb
class Looper():
def __init__(self):
username = ""
password = ""
host = "localhost"
dbName = "loop_controller"
self.db = mDb.Db(host, username, password, dbName)
self.checkTable("ir_cal_data2", [
{"name": "id", "type": "INT NOT NULL AUTO_INCREMENT PRIMARY KEY"},
{"name": "distance", "type": "TEXT"},
{"name": "pin_measurement", "type": "TEXT"}])
self.ser = serial.Serial(port='COM17', baudrate=9600)
self.ser.flushInput()
self.ser.flushOutput()
distance = 8
while distance < 61:
raw_input("Press Enter when ready for next reading. Currently at " + str(distance) + ".")
self.log_data(distance)
distance += 1
def checkTable(self, table, data):
try:
self.db.beginTransaction()
self.db.checkTable(table, data)
self.db.commitTransaction()
except Exception as e:
print("WARNING")
print(e)
def log_data(self, distance):
counter = 0
data_raw = None
minVal = 0
maxVal = 0
avgVal = 0
firstVal = True
while counter < 250:
try:
data_raw = self.ser.readline()
data_raw = int(data_raw)
data = {"distance": str(distance), "pin_measurement": str(data_raw)}
try:
self.db.beginTransaction()
self.db.insert("ir_cal_data2", data)
self.db.commitTransaction()
except Exception as e:
print("WARNING")
print(e)
if firstVal:
firstVal = False
minVal = data_raw
maxVal = data_raw
avgVal += data_raw
else:
if data_raw < minVal:
minVal = data_raw
if data_raw > maxVal:
maxVal = data_raw
avgVal += data_raw
counter += 1
except Exception as e:
print("Could not log value: " + str(data_raw))
print(e)
#break
try:
avgVal = (avgVal * 1.0) / counter
print("Min. Reading: " + str(minVal))
print("Max. Reading: " + str(maxVal))
print("Avg. Reading: " + str(avgVal))
except:
pass
Arduino Code:
As you can see I set the intercept at 85.07 instead of the 89.92 that I got from the regression line. This shift produced better results. While my test setup doesn't allow me to gain dead on accuracy, the results were very close. This is a good fit for this sensor, and I will write an R script so that it is easier in the future to calibrate each sensor.
#include "FastRunningMedian.h"
int sensorPin = A3;
unsigned int value = 0;
FastRunningMedian<unsigned int,32, 0> newMedian;
void setup ()
{
while (!Serial) ;
Serial.begin(9600);
};
void loop()
{
unsigned int xmedian;
value = analogRead(sensorPin);
newMedian.addValue(value);
xmedian = newMedian.getMedian();
Serial.print(" median=");
Serial.println(xmedian);
unsigned long x3 = pow(xmedian, 3);
unsigned long x2 = pow(xmedian, 2);
float distance = (-0.000001805 * x3) + (0.001796 * x2) + (-0.6168 * xmedian) + 85.07;
Serial.print("Distance= ");
Serial.println(distance);
};
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.