-
-
Save icq4ever/d9bf194ec82d15128a2fca377b53d9b6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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