UltraSonic Sensor with an ESP-01 Standalone

I'm trying to build a cheap device to measure water level in a tank using HC-SR04 sensor and ESP-01 which send the data to MQTT topic. I used the same code with ESP-E12 which works just fine. As I'm trying to drive the cost down with ESP-01, I faced a problem with I/O pins. I searched the web and found some contradicting info about which pins could be used in this case.

Coming to the ESP-01, I used a USB adapter to program it and the code uploaded successfully. Here I'm just showing the Ultrasonic sensor part which I believe I have issues with.

#define echoPin 2 // Echo Pin
#define trigPin 0 // Trigger Pin
 
long duration, distance; // Duration used to calculate distance
 
void setup(){
  Serial.begin (115200);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);   
}
 
void loop(){
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration/58.2;
  Serial.println(distance);
  delay(200);
}

I read somewhere in the internet that GPIO2 can't be used and must be replaced with Rx = GPIO3. However, I tried that and it didn't work too.

this work using a SR04M waterproof ultrasonic sensor

// ESP-01S SR04M ultrasonic sensor

#define trig 2  //Pin 33 trigger Tx
#define echo 0  //Pin 32 echo Rx

void trigPuls();

float pulse;     //echo time duration
float dist_cm;   //distance in cm

void setup() 
{
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  
  digitalWrite(trig, LOW);
  Serial.begin(115200);
}

void loop() 
{
   trigPulse();
   pulse = pulseIn(echo, HIGH, 200000);
   dist_cm = pulse/58.82;
   // 340m/s
   // 34000cm/s  
   /*
        100000 us - 17000 cm/s
             x us - 1cm
           1E6
      x = -----
          17E3
   */  
   Serial.println(String(dist_cm) + " cm");
   delay(1000);
}

void trigPulse()
{
  digitalWrite(trig, HIGH);  //Trigger Pulse HIGH
  delayMicroseconds(10);     //for 10 micro seconds
  digitalWrite(trig, LOW);   //Trigger Pulse LOW
}

some sample readings

0.54 cm
20.21 cm
23.09 cm
24.06 cm
25.35 cm
26.28 cm
29.75 cm
30.79 cm
32.51 cm
34.17 cm
36.37 cm
20.54 cm
132.86 cm
133.49 cm
128.43 cm
123.33 cm
120.11 cm
120.55 cm

remember the ESP-01 uses 3.3V logic - if connecting it to a 5v device use a potential divider on any ESP-01 inputs

Where you read this?

The code should work. Btw, with ESP8266 01, CHIP_EN pin should be connected to +3V3.

in addition (from ESP8266_01_pin_magic)
GPIO0 and GPIO2 need to have pull-up resistors connected to ensure the module starts up correctly. The ESP-01S has 12K resistors on the board for GPIO0, RST and CH_PD
are you using a ESP-01 or ESP-01S?
what ultrasonic sensor are you using ? some may require 5V power
how are you programming the device, e.g. using a programmer module?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.