Write a code using 3 pins instead of 4 for ultrasonic 28015 and esp32
Hello, I am using ultrasonic 28015 and esp32 to measure distance, but the ultrasonic has only 3 pins, +5V, ground, and sig. I wrote code as having trig and echo and put two wires in the sig, but it did not work. So, can some please tell me what should I change in my code to make it work??
https://ibb.co/YN0LjCQ
https://ibb.co/JnD5WhX
This is my code
// defines pins number
const int trigPin = 2;
const int echoPin = 5;
// defines varibles
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
}
[img][/img]
https://ibb.co/YN0LjCQ
https://ibb.co/JnD5WhX
This is my code
// defines pins number
const int trigPin = 2;
const int echoPin = 5;
// defines varibles
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
}
[img][/img]
Comments
Additionally look at the Parallax Manual for that sensor ,,, https://www.parallax.com/sites/default/files/downloads/28015-PING-Sensor-Product-Guide-v2.0.pdf
In addition to making the trigPin = echoPin, you may also have to change or ADD to capture the beginning of the returned pulse vs. the end of the returned pulse...
Option1:
duration = pulseIn(echoPin, HIGH);
so that it reads ...
duration = pulseIn(echoPin, LOW);
Option2:
duration1 = pulseIn(echoPin, HIGH);
duration2 = pulseIn(echoPin, LOW);
duration = duration2 - duration1;