I'm doing my project regarding 40khz ultrasonic sensor which will be used to get accurate distance measurements. I have a separate transmitter and receiver. I want to get the time between the moment my transmitter transmitted the waves and the time my receiver received it. However, I couldn't actually make it work. Does any of you give me a code that would help me transmit and receive the 40khz waves and get the time in between so I could use it to compute for the distance?Thank you in advance. I would greatly appreciate it!
2 Answers
This is the most basic ultrasound pulse and receive code. I wrote it to work with the HC-SR04
modules; so hopefully it will work fro you too as those also sound at 40khz
.
The main functionality comes from the pulseIn()
funciton.
#define TRIGPIN 9
#define ECHOPIN 10
void setup() {
Serial.begin(9600);
pinMode(TRIGPIN, OUTPUT);
pinMode(ECHOPIN, INPUT);
}
void loop() {
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW);
uint16_t duration = pulseIn(ECHOPIN, HIGH, 4000);
int distance = (duration*.0343)/2;
Serial.println(distance);
}
Note that you will need to adjust the 4000
(μs
) to whatever timeout in you want (or emit entirely if you don't want it).
-
Hi Sir! Sadly, I'm not using any commercially available ultrasonic sensor like HC-SR04. I have separate transmitter and receiver transducer Sir. Apr 11, 2018 at 9:48
-
@JeniferRicalde That is fine, can you provide a link to these? The code will still work assuming the transmitter and receiver are simply digital outputs (i.e. send HIGH to transmit sound on the transmitter and the receiver outputs HIGH when it receives). Apr 11, 2018 at 9:53
-
Sir, will it be ok if I ask for your email?I wish to send the code. I cannot attach it in here Apr 11, 2018 at 13:44
-
Why not? Just insert into the question like I have in my answer the
.ino
file. Or make a link with pastebin.com Apr 11, 2018 at 14:05 -
I'm sending 8 pulses of 40khz waves then the receiver will measure the voltage peak of the wave it received so that it may know the time interval.however, i'm not quite sure if my code is right Apr 11, 2018 at 22:38
I don't have 'a code', but what you can do is using a timer set to 40 kHz and send the pulses you need. .
If nothing else needs to be done (nor in the future) you can use a delay function.
Also check the pulseIn function from Arduino, you can use this convenience function for the checking the result.
HC-SR04
?