#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() { // Subtract the last reading total = total - readings[readIndex]; // 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(", Distance: "); Serial.print(average); Serial.println(" cm"); delay(250); // Approximately 250 ms delay }