class HCSR04 {
private:
int triggerPin;
int echoPin;
public:
HCSR04(int triggerPin, int echoPin) {
this->triggerPin = triggerPin;
this->echoPin = echoPin;
pinMode(this->triggerPin, OUTPUT);
pinMode(this->echoPin, INPUT);
}
float distance_mm() {
float duration, distance;
digitalWrite(this->triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(this->triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(this->triggerPin, LOW);
duration = pulseIn(this->echoPin, HIGH);
distance = duration * 0.034 / 2;
return distance;
}
};
HCSR04 sensor(12, 11);
void setup() {
Serial.begin(9600);
}
void loop() {
long distance = sensor.distance_mm();
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" mm");
delay(1000);
}