34 lines
959 B
Arduino
34 lines
959 B
Arduino
|
#define sensorPin A1 // Sharp 2Y0A21 sensor (10 to 80 cm)
|
||
|
|
||
|
void setup() {
|
||
|
Serial.begin(9600);
|
||
|
pinMode(sensorPin, INPUT);
|
||
|
}
|
||
|
|
||
|
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
|
||
|
|
||
|
// Print the raw analog value, voltage, and calculated 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.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
|
||
|
}
|