diff --git a/SharpDistance_v0.ino b/SharpDistance_v0.ino index c60b6b5..75ad994 100644 --- a/SharpDistance_v0.ino +++ b/SharpDistance_v0.ino @@ -1,33 +1,52 @@ #define sensorPin A1 // Sharp 2Y0A21 sensor (10 to 80 cm) +#define numReadings 10 // Number of readings to average for the moving average + +int readings[numReadings]; // Array to store the readings +int readIndex = 0; // Index of the current reading +int total = 0; // Sum of the readings +int average = 0; // Average of the readings void setup() { Serial.begin(9600); pinMode(sensorPin, INPUT); + for (int i = 0; i < numReadings; i++) { + readings[i] = 0; // Initialize the readings array + } } void loop() { - int rawValue = analogRead(sensorPin); // Read the raw analog value - float volts = rawValue * 0.0048828125; // Convert the raw value to volts - int distance = 26 * pow(volts, -1); // Calculate distance using the formula + // Subtract the last reading + total = total - readings[readIndex]; - // Print the raw analog value, voltage, and calculated distance to the Serial Monitor + // Read the raw analog value + int rawValue = analogRead(sensorPin); + + // Calculate distance using the formula + int distance = 123.221814 * exp(-0.005895 * rawValue); + + // Add the current reading to the total + total = total + distance; + + // Store the reading in the array + readings[readIndex] = distance; + + // Advance to the next position in the array + readIndex = readIndex + 1; + + // If we're at the end of the array, wrap around to the beginning + if (readIndex >= numReadings) { + readIndex = 0; + } + + // Calculate the average + average = total / numReadings; + + // Print the raw analog value and the averaged distance to the Serial Monitor Serial.print("Raw Value: "); Serial.print(rawValue); - Serial.print(", Volts: "); - Serial.print(volts); Serial.print(", Distance: "); - Serial.print(distance); + Serial.print(average); Serial.println(" cm"); - delay(700); -} - -float readSensorAverage(int pin, int numSamples) { - long sum = 0; - for (int i = 0; i < numSamples; i++) { - sum += analogRead(pin); - delay(10); // Small pause between readings - } - float average = sum / numSamples; - return average * 0.0048828125; // Convert the average value to volts + delay(250); // Approximately 250 ms delay }