Skip to content

Instantly share code, notes, and snippets.

@icq4ever
Forked from SONGYEJI/fun_fun_poly_distance.ino
Created October 20, 2016 19:21
Show Gist options
  • Save icq4ever/d9bf194ec82d15128a2fca377b53d9b6 to your computer and use it in GitHub Desktop.
Save icq4ever/d9bf194ec82d15128a2fca377b53d9b6 to your computer and use it in GitHub Desktop.
const int numReadings = 10;
int readings[numReadings]; // the readings from the analog input
int readIndex = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average
int inputPin = A0;
int distance;
void setup() {
// initialize serial communication with computer:
Serial.begin(9600);
// initialize all the readings to 0:
for (int thisReading = 0; thisReading < numReadings; thisReading++) {
readings[thisReading] = 0;
}
}
void loop() {
// subtract the last reading:
total = total - readings[readIndex];
// read from the sensor:
readings[readIndex] = analogRead(inputPin);
// add the reading to the total:
total = total + readings[readIndex];
// advance to the next position in the array:
readIndex = readIndex + 1;
// if we're at the end of the array...
if (readIndex >= numReadings) {
// ...wrap around to the beginning:
readIndex = 0;
}
// calculate the average:
average = total / numReadings;
// send it to the computer as ASCII digits
if ( average >=280 && average <=512 ) {
Serial.print ("The distance is : ");
distance = 28250 /(average-229.5);
Serial.print(distance);
Serial.println("cm");
}
// Serial.println(average);
delay(200); // delay in between reads for stability
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment