Hello. I have two Arduino, and each of which is connected to the ultrasonic sensor HC-SR04. I try to calculate the distance between them, sending a signal from one Arduino and taking to another. I decided to make sure that if no signal was sent from the first Arduino, then on the second Arduino, when I try to receive the emitted signal (it is not being emitted at the moment), it will be output 0. But no, when measuring, it outputs not understandable values that are approximately equal to each other, similar either to some kind of interference or to noise. Both sensors are working. Can someone come across a similar problem or can suggest how to implement my idea. Thank you in advance.
P.S. I also tried to repeat this experiment, but I encountered the same problem.
How to measure distanse between two ultrasonic sensors
Setup:
Programming code for Transmitter (Arduino Mega 2560):
const int trigPin = 9;
const int echoPin = 10;
const int ledPin = 13;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
delay(2);
}
Programming code for Receiver (Arduino Uno):
const int trigPin = 9;
const int echoPin = 10;
const int ledPin = 13;
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop(){
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
while (digitalRead(echoPin)==HIGH){
delay(2);
}
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration*0.034;
Serial.println(distance);
delay(2);
}
Result:
I turn off the transmitter and try to make sure that the receiver does not receive anything:
Programming code for Receiver:
const int trigPin = 9;
const int echoPin = 10;
const int ledPin = 13;
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop(){
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
Serial.println(duration);
delay(2);
}
Result:
The result is the same. Similar values were obtained, although there is no signal from the transmitter.