arduino-irmeter/SharpDistance_v0.ino

53 lines
1.4 KiB
Arduino
Raw Normal View History

2024-06-25 00:27:58 +02:00
#define sensorPin A1 // Sharp 2Y0A21 sensor (10 to 80 cm)
2024-06-27 12:01:27 +02:00
#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
2024-06-25 00:27:58 +02:00
void setup() {
Serial.begin(9600);
pinMode(sensorPin, INPUT);
2024-06-27 12:01:27 +02:00
for (int i = 0; i < numReadings; i++) {
readings[i] = 0; // Initialize the readings array
}
2024-06-25 00:27:58 +02:00
}
void loop() {
2024-06-27 12:01:27 +02:00
// 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;
2024-06-25 00:27:58 +02:00
2024-06-27 12:01:27 +02:00
// 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
2024-06-25 00:27:58 +02:00
Serial.print("Raw Value: ");
Serial.print(rawValue);
Serial.print(", Distance: ");
2024-06-27 12:01:27 +02:00
Serial.print(average);
2024-06-25 00:27:58 +02:00
Serial.println(" cm");
2024-06-27 12:01:27 +02:00
delay(250); // Approximately 250 ms delay
2024-06-25 00:27:58 +02:00
}