Der Code bedient das Modul AJ-SR04M (wasserdichter Ultraschall Abstandssensor), glättet die Werte und gibt mit 10 Hz die Werte auf dem seriellen Monitor aus (distance in cm). Unter Wasser gibt der Sensor keine vernünftigen Werte aus.
Autor: Christian
/* BEERLECADA PROGRAM
* Product: P211004_AJ-SRO4M_ultrasonic
* module: AJ-SRO4M waterproof
* origin: China
* recommendation: E211004
* connect: 5V to 5V
* Trig to Pin 13
* Echo to Pin 12
* Gnd to Gnd
* author: Christian Rempel
* Licence: beer (red wine) licence
*/
#define TRIG_PIN 13 //RX
#define ECHO_PIN 12 // TX
#define BAUD_RATE 9600 // Serial monitor baud rate
float distance;
long timer;
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
digitalWrite(TRIG_PIN, LOW);
Serial.begin(BAUD_RATE);
timer = millis();
}
void loop() {
// generate a ten microseconds high pulse
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// pulseIn returns the time in µs until the echo pulse appears
const unsigned long duration = pulseIn(ECHO_PIN, HIGH);
// the distance in cm computes from the travel time s= v*t with v = 340 m/s (in air)
// in water v = 1484 m/s but the sensor does not give reasonable values under water
// the distance have to be devided by 2, since this is the distance forth and back
// a gliding avarage is applied to distance with 99 % flattening
distance = distance * 0.99 + 0.01 * (float)duration * 0.034 / 2;
// a timer is organized, so that printing is only at 100 ms period
if (millis() - timer > 100) {
// printing the distance in cm
Serial.print("distance: ");
Serial.print(distance);
Serial.println(" cm");
timer = millis();
}
// force the loop to run at 1 kHz
delay(1);
}
Siehe E211008