I have been working on this project where the ESP32 connects to a web server and sends it the measurements from the Ultra Sonic sensor.
Before starting the project, I tested the sensor alone with this dummy code:
/*
* HC-SR04 example sketch
*/
const int trigPin = 4;
const int echoPin = 2;
const int ledPin = 0;
bool ledState = false;
float duration, distance;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(115200);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration*.0343)/2;
if (distance < 50 && !ledState){
Serial.println("ON");
ledState = true;
digitalWrite(ledPin, HIGH);
} else if (distance > 50 && ledState){
Serial.println("OFF");
ledState = false;
digitalWrite(ledPin, LOW);
}
Serial.print("Distance: ");
Serial.println(distance);
delay(2000);
}
And all seemed to be working fine.
In the final project, readings become unstable and without any sense.
I started brainstorming and though about testing the dummy code, but with Wi-Fi connection:
/*
* HC-SR04 example sketch
*
* https://create.arduino.cc/projecthub/Isaac100/getting-started-with-the-hc-sr04-ultrasonic-sensor-036380
*
* by Isaac100
*/
#include <WiFi.h>
const int trigPin = 4;
const int echoPin = 2;
const int ledPin = 0;
bool ledState = false;
// WIFI LOGIN
const char* ssid = "**";
const char* password = "**";
float duration, distance;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(115200);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration*.0343)/2;
if (distance < 50 && !ledState){
Serial.println("ON");
ledState = true;
digitalWrite(ledPin, HIGH);
} else if (distance > 50 && ledState){
Serial.println("OFF");
ledState = false;
digitalWrite(ledPin, LOW);
}
Serial.print("Distance: ");
Serial.println(distance);
delay(2000);
}
And I am now encountering the same exact problem, nonsense unstable readings.
Anyone has an idea on what may be causing the problem? I have tried reading the voltage with a Multimeter, but the voltage seems to be the same in the two cases. I also considered Wi-Fi interference with the readings, but I don’t really think that’s the case.