Hey, I am using a hc-sr04 and a Arduino Leonardo to measure the distance of a moving object. The problem is that the serial monitor sometimes stop updating the distance and I have to manually wave something in front of the sensor to update it so it continues to write values. But sometimes when the value stays constant it updates perfectly fine. So the problem only exists sometimes and I don't know why? I would be grateful for any help.
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Pin für Trigger
int TRIGGER = 8;
// Pin für reflektiertes Signal
int ECHO = 7;
long Entfernung = 0;
// declare an SSD1306 display object connected to I2C
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
void setup() {
pinMode(TRIGGER, OUTPUT);
pinMode(ECHO, INPUT);
Serial.begin(9600);
// initialize OLED display with address 0x3C for 128x64
if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
while (true);
}
delay(2000); // wait for initializing
oled.clearDisplay(); // clear display
oled.setTextSize(3); // text size
oled.setTextColor(WHITE); // text color
}
int getEntfernung()
{
// Sender kurz ausschalten um Störungen des Signal zu vermeiden
digitalWrite(TRIGGER, LOW);
delayMicroseconds(3);
noInterrupts();
// Signal für 10 Micrsekunden TRIGGER, danach wieder ausschalten
digitalWrite(TRIGGER, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER, LOW);
// pulseIn -> Zeit messen, bis das Signal zurückkommt
long Zeit = pulseIn(ECHO, HIGH);
interrupts();
// Entfernung in cm berechnen
// Zeit/2 -> nur Strecke
return Entfernung = (Zeit / 2) * 0.03432;
}
void loop() {
int Entfernung = getEntfernung();
delay(200);
// nur Entfernungen < 100 anzeigen
if (Entfernung < 100) {
// Messdaten anzeigen
Serial.println(Entfernung);
oled.setCursor(0, 10); // position to display
oled.clearDisplay(); //clear display
oled.println(Entfernung); // text to display
oled.display(); // show on OLED
}
}