// @author Fabian Moron Zirfas
#define BUFFERLENGTH 5 // numbers of places in buffer
int sensorreadingraw; // raw value reading from the shapr sensor
// this is for calibrationg the reading
int maxsensorval = 0; // will hold the max value
int minsensorval = 1023; // will hold the min value
int average = 0; // will hold the calculated average from sensor reading
int sensorbuffer [BUFFERLENGTH] = {0, 0, 0, 0, 0}; // buffer for averaging
void setup() {
// put your setup code here, to run once:
Serial.begin(9600); //just for debugging
}// end of setup
void loop() {
sensorreadingraw = analogRead(A0); // read in the sharp sensor
average = calcaverage(sensorreadingraw); // calculate the average
calibrate(average); // calibrate our range of sensor values
Serial.println(average); // just fpr debugging oputput
}
// this function calculates the average of our read values
// see
// https://www.sparkfun.com/products/8958
// in the comments
// @param int sensorreadingraw = the value from analogRead
// @return int = the calulated average
int calcaverage(int sensorreadingraw) {
// loop the buffer from the end
for (int j = BUFFERLENGTH - 1; j >= 0; j--) {
if (j == BUFFERLENGTH - 1) {
sensorbuffer[j] = sensorreadingraw;
} else {
sensorbuffer[j] = sensorbuffer[j + 1];
}
}
int ave = 0;
for (int i = 0; i < BUFFERLENGTH; i++) {
ave += sensorbuffer[i];
}
return ave / BUFFERLENGTH;
}
// calibrate our min and max values
// @param int ave = the value to calibrate
void calibrate(int ave) {
if (ave < minsensorval ) {
minsensorval = ave;
}
if (ave > maxsensorval) {
maxsensorval = ave;
}
}