How to make an ultrasonic distance sensor on Arduino: DIY rangefinder. Ultrasonic distance sensor Do-it-yourself ultrasonic rangefinder on a microcontroller circuit diagram

Bruno Gavand

The project, which considers a simple and low-cost solution for an ultrasonic sensor for measuring distance, is based on the company's PIC16F877A microcontroller, but the source code can be adapted by users to other microcontrollers. The sensor can be built into custom designs and devices: presence detectors, robots, car parking systems, distance measuring devices, etc.

Distinctive features:

  • a small number of external components;
  • code size 200 Bytes;
  • working distance range: 30 cm - 200 cm;
  • measurement accuracy ±1 cm;
  • indication when measurement limits are exceeded.

As you know, the speed of sound in air is about 340 m/s. Thus, the principle of an ultrasonic sensor is to send an ultrasonic pulse with a frequency of 40 kHz and monitor the reflected signal (echo). Of course, you won't hear the sound, but the ultrasonic sensor is able to detect the reflected pulse. Therefore, knowing the travel time of the pulse and the reflected ultrasonic signal, we can obtain the distance. Dividing by two, we get the distance from the ultrasonic sensor to the first obstacle from which the signal was reflected.

The device uses a MA40B8S piezoceramic ultrasonic emitter and an open MA40B8R piezoceramic ultrasonic sensor. The main parameters are shown in the table below.

Device Purpose Frequency Direction,
hail
Capacity,
pF
Region
detection,
m
Input
voltage,
max, V
MA40B8S Emitter 40 kHz 50 (symmetrical) 2000 0.2 … 6 40
MA40B8R Sensor 40 kHz 50 (symmetrical) 2000 0.2 … 6

The company's debugging platform was used for testing.

However, the user can use any PIC microcontroller that has at least one ADC channel and one PWM channel.

Schematic diagram of an ultrasonic sensor

The emitter is controlled via transistor BD135. The 1N4007 diode is used to protect the transistor from reverse voltage. Thanks to the use of a transistor and a resonant circuit, which is formed by parallel connection of a 330 µH inductor L1 and a capacitor formed by the emitter itself, the supply voltage of the emitter will be about 20 V, which ensures a detection range of up to 200 cm. It is worth noting that the emitter can be controlled directly from the microcontroller output, however, in this case the distance range does not exceed 50 cm.

The sensor is connected directly to the ADC of the microcontroller (when using PIC16F877A - channel 1 of the ADC), a resistor connected in parallel with the sensor is necessary for impedance matching.

First you need to send an ultrasonic pulse. A 40 kHz signal is easily obtained using a hardware PWM microcontroller. The reflected signal from the sensor enters the ADC, the resolution of the ADC is 4 mV, which is quite sufficient for reading data from the sensor, and no additional components are needed.

External view of the ultrasonic sensor development board


This sensor is the simplest solution and therefore has several disadvantages: slight vibration of the ultrasonic receiver can lead to incorrect measurements. Since the pulse sent is not modulated or coded, extraneous sources of ultrasonic frequency can interfere with the measurement, all of which can lead to incorrect results (out-of-range measurements).

Captions on the image:

ultrasonic burst - ultrasonic pulse;
mechanical echo (removed by software) - mechanical echo (removed by software);
ultrasonic wave reflected by remote object - ultrasonic wave reflected from a distant object.

Oscilloscope division value: horizontally - 1 ms/div, vertically - 5 mV/div.

Mechanical echo is eliminated in software by introducing a delay. The reflected wave, having an amplitude of about 40 mV, was received 9.5 ms after the sent pulse. Considering that the speed of sound is 340 m/s, we get:

0.0095 / 2×340 = 1.615 m.

In reality, it was the ceiling of the room at a distance of 172 cm from the sensor; the value of 170 cm was displayed on the LCD display installed on the debugging board.

Downloads

Source code for the project on the PIC16F877A microcontroller (mikroC compiler) -

This device, which is still considered unique, has been able to find application in almost all areas of human life. Today, laser rangefinders can be seen in the hands of geologists and surveyors. In other words, in those areas of human activity where it is necessary to measure distances with extreme accuracy. Therefore, laser tape measures have gained high popularity, characterized by high accuracy, increased reliability and a very affordable price. It’s quite natural to ask whether it’s possible to make a laser rangefinder with your own hands.

The group of devices that measure distance using electronics includes: laser rangefinder, ultrasonic rangefinder.

Measurements with a laser rangefinder are made on the basis of light fluxes; the signal carrier is electromagnetic radiation, colored in the appropriate shade. In most cases, red light is used as a basis.

According to the laws of physics, the speed of light is much higher than the speed of sound, so the time it takes to measure the same distance will differ.

The main reasons for installing a laser rangefinder

Using a mechanical tape measure is not always convenient. Sometimes it doesn't have a positive effect. Over the past 10 years, electronic rangefinders have become increasingly preferred. This group of devices that measure distance using electronics includes:

  • laser rangefinder;
  • ultrasonic range finder.

All these devices operate on the non-contact principle. Today, such a rangefinder is created by domestic craftsmen with their own hands. The devices work no worse than those that were produced in the factory.

A DIY laser rangefinder consists of several parts:

  • pay;
  • microcontroller;
  • laser signal amplifier;
  • laser;
  • photodetector;
  • filter.

Basically, laser radiation occurs using a sinusoidal signal.

It is quite difficult to obtain such a signal having a frequency of 10 MHz. A simple controller is not suitable here. To do this, it is better to use a meander that has the required frequency. When the signal coming from the photodetector is amplified, unnecessary harmonics are removed by a special bandpass filter that operates at a frequency of 10 MHz. A signal appears at the output that strongly resembles a sinusoidal one.

Return to contents

To make a rangefinder with your own hands, you can use a laser communication circuit as a basis. In this case, data transfer occurs very quickly, the speed is 10 Mbit. This value corresponds to the existing modulation frequency.

For such a laser device, the simplest power amplifier is used. It consists of one 74HC04 chip, which is assembled from six inverters. The current supply is limited by special resistors. However, craftsmen can replace resistors with more reliable parts.

The commissioning board becomes a source of 5-volt voltage. This is how the amplifier receives power. To remove signal interference to another part of the electrical circuit, the amplifier housing is made of steel, each wire is shielded.

The laser is the drive installed in DVD set-top boxes. Such a device has sufficient power to operate at frequencies reaching 10 MHz.

The receiver includes:

  • photodiode;
  • amplifier.

The amplifier includes a field-effect transistor, a special microcircuit. As the distance increases, the illuminance of the photodiode decreases. Therefore, it is necessary to have powerful amplification. The assembled circuit allows you to reach 4000 units.

As the frequency increases, the photodiode signals begin to decrease. An amplifier of this design is the main and highly vulnerable part. Its setting requires very high precision. It is advisable to adjust the gain in such a way as to obtain maximum values. The easiest way is to supply 3 V to the transistor. You can install an ordinary battery.

For the receiver to start working, you need to supply 12 V. For this, a special power supply is installed.

Such an amplifier has a high sensitivity to any interference, so it must be shielded. You can use the optical sensor housing for this. Photodiode shielding can be made from ordinary foil.

The system described above will allow you to create a homemade laser rangefinder at home.


Greetings to all. I recently came across an ultrasonic sensor that measures the distance to an object - US-100. A similar item can be purchased on online trading platforms. It was not possible to find such toys for sale in the markets of my city. It was decided to build a circuit based on such a sensor on the common AVR ATmega8 microcontroller. The purpose of the device is to measure the distance to an object, as well as measure temperature. Speaking of temperature. Model US-100 is an ultrasonic sensor with temperature compensation. The speed of propagation of a sound (ultrasonic) wave at different temperatures will be different. The sensor measurement is based on the travel time of the sound wave from the object to the sensor receiver. Temperature compensation will most likely not completely eliminate the error caused by ambient temperature.

When examining a printed circuit board, we can make a conclusion about the source of temperature measurement: the thermometer is located in the microcircuit or the temperature is measured by a diode located on the edge of the board. When measuring temperature with a diode, its P-N junction is used and this is related to the temperature coefficient of conductivity. With great confidence, this is the second option, since when working with the circuit below, when you touch this diode with your fingers, the temperature changes. So when measuring, it is best to try not to touch the sensor with your hands in order to get more accurate distance data.

To measure, the sensor uses 2 heads that resemble a large microphone or a small speaker. Essentially it's both. One of the heads emits an ultrasonic wave, the second receives the reflected signal of the ultrasonic wave. The distance traveled is determined by the travel time. Apparently the limitation of the measured distance of 4.5 meters is due to the power of the emitter.

As for the communication between the sensor and the microcontroller, the US-100 model has two possible interfaces, selected by a jumper on the back of the sensor board. If the jumper is set, the UART interface is selected; if the jumper is removed, the interface or GPIO operating mode is used. In the first case, either the microcontroller hardware or software is used to communicate with the microcontroller. In the second case, you will have to receive and transmit data only manually. In the device circuit we use a simpler operating mode using the UART interface.

It is necessary to clarify the nuances of pinout and connection of the sensor to the microcontroller. Usually, when transmitting data via UART, the Rx and Tx lines are connected crosswise - Rx to Tx, and Tx to Rx. This ultrasonic sensor must be connected in accordance with the signed contacts on the printed circuit board Rx to Rx, and Tx to Tx. The Chinese burned it out, I agree. Before this was determined, I had to suffer for a long time and finally come to this. So, when working via UART, to initialize one distance measurement, the US-100 ultrasonic sensor needs to transfer the value 0x55 to the Trig/Tx pin, which corresponds to the symbol “U”. In response, the sensor will transmit two bytes of distance information to the Echo/Rx pin - the first byte is the high 8 bits, the second byte is the low 8 bits. The units of distance are millimeters. To convert two bytes into one distance value, you need to multiply the first byte by 256 and add the second byte. It is necessary to do this because when the low byte overflows, the high byte is increased by one. To display the current ambient temperature value, the value 0x50 must be passed, which corresponds to the character "P". In response, the sensor will transmit the temperature value. The actual temperature value will be equal to the value received from the sensor subtract 45.

US-100 ultrasonic sensor parameters:

  • supply voltage - 2.4 - 5.5 volts DC voltage
  • current consumption in standby mode - 2 mA
  • operating temperature - minus 20 - plus 70 C
  • viewing angle - 15 degrees
  • interface - GPIO or UART
  • measured distance - from 2 cm to 450 cm
  • error - plus minus 3 mm + 1%

UART configuration for the sensor: 9600 baud rate, 8 data bits, parity: none, 1 stop bit.

Let's move on to the device diagram.

The ultrasonic rangefinder circuit is based on the Atmega8 microcontroller and the US-100 ultrasonic sensor. The power supply for the circuit is taken from the linear voltage stabilizer L7805, it can be replaced with a domestic analogue KR142EN5A, capacitors in the stabilizer harness are required, although it can work without them. Some stabilizers simply do not start without capacitors. The linear stabilizer can be replaced with a pulse regulator, for example MC34063 or LM2576, but you will have to slightly change the circuit according to the connection of the switching regulators in the circuit. Capacitors C5-C7 are necessary to ensure stability of the microcontroller and sensor. The ratings of all capacitors can be varied within reasonable limits. Resistor R2 is necessary to prevent spontaneous restarting of the microcontroller and serves as a pull-up of positive power to the reset pin. Resistor R1 regulates the contrast of the LCD display. The information panel was a liquid crystal display (LCD or otherwise LCD) SC1602 screen, 2 lines of 16 characters each, based on the HD44780 controller. You can replace the LCD display with any other model based on the HD44780 controller with the same number of lines and characters per line or more. On the printed circuit board of an LCD display, it is possible to activate the screen backlight in two ways - either by soldering a resistor and a jumper on the screen board itself, or by using special pins, usually designated “A” and “K”. Anode and cathode respectively. The circuit supply voltage of 5 volts is connected to them through a current-limiting resistor. This diagram uses the first method, so it is not indicated on the diagram. Instead of clock buttons S1 - S5, you can use any other buttons. LED1 can be used in any suitable color or replaced with a transistor and controlled by some other circuit depending on the distance from the sensor. Depending on the type of transistors used (P-N-P or N-P-N), when the distance or distance limit is exceeded, the output will have a positive or negative voltage, that is, when the logic signal of the microcontroller is high, the N-P-N transistor will be open and the P-N-P transistor will be closed. The microcontroller firmware contains a parameter in which, if the specified distance limit is exceeded, a high logical voltage level will be supplied to the PB0 pin. In this circuit, the LED simply signals an excess. This signal is duplicated on the LCD display by underlining the distance limit information. This parameter can be adjusted using buttons S1, S2. When pressed, it increases or decreases by 10 mm. Information about the distance is also displayed on the display in millimeters. Information about the ambient temperature is displayed on the display in degrees Celsius. Two firmware options are attached to the article: 1) continuous measurement of distance and temperature parameters (interval of approximately 0.2 seconds), while the S4, S5 buttons are not used, 2) when pressing the S4, S5 buttons, a single request is made to the sensor to measure the temperature and distances. The video for the article was made with firmware number 1. To program the microcontroller, you need to flash the fuse bits:

For beginners, I recommend using hexadecimal values ​​for the fuse bits HIGH and LOW, so as not to mess up the checkboxes. Screenshot from AVRstudio (there are differences from pipe, sina prog and other programs for flashing microcontrollers). If you use programs for flashing AVR microcontrollers that do not allow you to enter fuse parameters, you can use fuse calculators to convert checkboxes into hexadecimal form and vice versa.

The circuit was assembled and tested on a development board for Atmega8:

Structurally, the scheme can be designed, for example, in the form of a pistol with a laser indicator of the direction of the ultrasonic sensor. The only limit is the measured distance, beyond which the error increases sharply. The limitation also concerns the position and size of the object to which the distance is measured - the distance to objects that are too small or at a large angle will be distorted. The ideal combination is large enough objects that are perpendicular to the direction of the sensor. The measurement error approximately corresponds to that stated by the manufacturer. With further development, this device can be used as an obstacle detector, like a parking sensor in indoor conditions, since on the street the ultrasonic heads of this sensor will become clogged with dirt.

Offer your ideas and application options; the most interesting ideas can be implemented in the future.

I am attaching to the article 2 versions of HEX firmware for the MK, a project in (version 7.7, the US-100 ultrasonic sensor is not in the proteus database, but a UART debugger is used), as well as a short video demonstrating the operation of the circuit.

List of radioelements

Designation Type Denomination Quantity NoteShopMy notepad
IC1 MK AVR 8-bit

ATmega8

1 To notepad
VR1 Linear regulator

L7805AB

1 To notepad
HG1 LCD displaySC16021 Based on HD44780 To notepad
U1 Ultrasound sensorUS-1001 To notepad
R1 Trimmer resistor10 kOhm1 3296W-1-103LF To notepad
R2 Resistor

10 kOhm

1 0.25 W To notepad
R3 Resistor

390 Ohm

1 0.25 W
Some notes:
All the parts needed to create an ultrasonic rangefinder according to this scheme are sold in chipidip, it costs about 500-900 rubles for everything (I don’t remember exactly - there was a lot of money, I didn’t count it :-). (housing, tweeters, connectors, etc.)
Some comments on the ultrasonic rangefinder circuit:
1. You can use any tweeters, different ones are better for different tasks... for my task - the larger the dimensions, the better, the angle is 50.
2. You can try to use only one relatively expensive AD822 and in place of the comparator something cheaper (I simply didn’t have anything else on hand at all)
3. In the mega, you can use a timer to generate 40 kilohertz; for this you need to select another resonator. (I only had 16 and 12.. they don't fit)
4. The speed of sound in air actually depends on temperature - if accuracy is very important (I don’t care about it), then take this into account
5. Please note that in the picture of the rangefinder in the case - the tweeters do not touch the plastic - one person said that with mega-precise settings (this circuit is capable of this) the sound from the tweeter to the microphone will be transmitted through the body, so it’s better to play it safe
6. An example of the simplest mega firmware in C (under this diagram) can be seen
7. It is better to use the programmer STK200/300, also known as avreal - the software and circuit can be pulled
8. According to the mind, in the firmware it is necessary to track both the beginning and the end of the “pack”, in the example only the beginning (the accuracy will increase specifically)... maybe I’ll add it and post it.
9. The tweeter really likes 40 kHz - a little to the side is not at all the same... it’s probably true what they say in the manual, that it’s resonant :-)
10. It’s not without reason that transistors are crammed into the emitter in the diagram - for those who want to give more volts than 12 - welcome - one person said that it would squeak louder (count further). I didn’t do this for three reasons: firstly, 24 volts still need to be found somewhere, and secondly, the current version, with the resistor configured accordingly, sees a wall 4 meters away, i.e. I have no place to test it, and I don’t need it. Well, the third reason this same person said is that tweeters tend to die at this voltage
11. General advice: you can find all the resistors and capacitors in a non-working power supply from an ATX computer (they are all about 1/8 watt) - you will save money!
12. There is a misconception that the ultrasound emitted by a squeaker can somehow be heard by dogs and other creatures, it has a bad effect on them: my dog ​​came one night and fell asleep in front of the squeaker that was on.
13. Also - just for your information - megas and other 8-bit controllers from Atmel work great... in some tasks, instead of the required 16, they work at 24 and are fine.
14. When setting R5 above a kilo-ohm (10, 50, 100), you will get a very large gain, and most likely you will need horns, but the measurement range will greatly increase.
15. Instead of removing the horns (with a large R5), see above, you can upgrade the firmware so that it does not wait for a useful signal at the initial moment of time. But then it will be impossible to measure distances of about 10 cm or less.

Commentary to tip 8 - yellow indicates the moment the ultrasonic rangefinder MK interruption is triggered at reception; in fact, you can limit yourself to just this first moment, wait a little and make the next measurement, generating the next burst of pulses - and the flight time of the sound is considered the time from the first sent pulse (or the last one is not important) until the FIRST one accepted.
The second option - indicated in red - is more accurate - since the packet of pulses, as a rule, does not arrive in perfect form and not completely (there may not be a couple of the first or last pulses), in fact, even in the picture you can see that it is “flattened” at the edges, although an ideal rectangle of pulses was sent - so: the point is that the middle of the packet should remain in place despite the fact that its edges may no longer be felt by the comparator. So the accuracy is several.. (one has to think about millimeters) depends on whether the middle or only the beginning of the pack was taken into account in the firmware of the ultrasonic rangefinder when receiving it back.

The HC-SR04 Ultrasonic Proximity Sensor (and similar modules) use ultrasonic waves to determine the distance to an object.

Generally speaking, we will need to figure out the distance to the object, because the sensor itself simply takes into account the time it takes to catch the echo of the sound waves it sends. It goes like this:

  1. The module sends out sound waves while at the same time applying voltage to a special echo pin.
  2. The module catches the reflected signal and removes voltage from the pin.

That's all an ultrasonic rangefinder does. We can determine the distance ourselves, because we know how long it took the sound to travel from the module and back (by how long the echo pin was energized), and we also know the speed of sound in air. But we won't go into too much detail and let the Arduino do all the calculations.

By the way, despite the fact that the principle of operation of all ultrasonic sensors is the same, NOT ALL OF THEM produce the same voltage output on the echo pin. So, if you have a module other than HC-S04, then pay attention to the fourth step, which describes possible problems, and check if your module is on the list. If it is not there, then you will have to figure it out on your own.

Step 1: DIY hardware assembly

Assembly is very simple (assemble everything disconnected from the voltage):

  1. Connect 5V from Arduino to VCC pin on module
  2. Connect GND from Arduino to GND on the module
  3. Connect digital pin 7 on the Arduino to the Trig pin on the module
  4. Connect digital module 8 on the Arduino to the Echo pin on the module

Step 2: Programming the HC-SR04 Module

In order to see the results of the program, you need to run serial monitor on Arduino. If you're not familiar with this feature, now is the time to open it up and learn more about it - it's a great tool for helping you debug your code. In the Arduino interface, look in the right corner, there you will find a button that launches the serial monitor, it looks like a magnifying glass, click on it and the monitor will open (or select TOOLS/Serial Monitor, or press Ctrl+Shift+M).

Here is a draft of the working program:

// Start of Sketch for Aruino -
// Define constants (constants do not change and if you try to redefine them you will get a compile-time error)
const int triggerPin = 7; // creates a constant called "triggerPin" and assigns digital pin 7 to it
const int echoPin = 8; // creates a constant called "echoPin" and assigns digital pin 8 to it
// Define variables (variables can and usually change during the program, they may contain any calculated values)
int duration = 0; // creates a variable called "duration" to hold the value returned by pulseIn, initially set to "0"
int distance = 0; // creates a variable to store a value calculated as the distance to the object in front of the sensor, initially the value is set to “0”
void setup() // In this section you can configure your board and other parameters necessary for your program to run.
{
Serial.begin(9600); // initializes serial communication via USB between the Arduino and the computer, we will need this
//define pin modes
pinMode(triggerPin, OUTPUT); // “triggerPin” will be used for OUTPUT, the pin number is declared above in the “Defining Variables” section
pinMode(echoPin, INPUT); // “echoPin” will be used for INPUT, the pin number is declared above in the “Defining Variables” section
) // end of setup
// everything that was written above is read by the program only once - at Startup or Reset
void loop() // the program code in the looped part is read continuously and repeated until the power is turned off or a reset is made
{
digitalWrite(triggerPin, HIGH); //starts sending ultrasonic waves from the HC-SR04 module
delay(5); // a short pause, it is needed for the module to function correctly (you can reduce this value, my other programs work with a value of 1)
digitalWrite(triggerPin, LOW); //stops ultrasonic waves coming from the HC-SR04 module
duration = pulseIn(echoPin, HIGH); //special function that allows you to determine the length of time at which voltage was applied to the echo pin in the last completed ultrasound cycle
delay(10); // again a short pause. It is needed for stability; a pause that is too short may not produce results.
distance = (duration/2) / 58; //convert duration to distance (the value stored in “duration” is divided by 2, then this value is divided by 58**) ** for centimeters
delay(500); // another pause for stability - you can play with the value, but this may ruin the program, so use 500 by default
Serial.print(distance); //sends the calculated distance value to the serial monitor
Serial.println("cm"); //adds the word “cm” after the distance value and moves the caret on the serial monitor to a new line
Serial.println(); //adds a blank line on the serial monitor (for readability)
) // End of loop

_________________________________________________

So, after reading my instructions, I realized that the program outline did not correspond to my understanding of simplicity. Therefore, I am posting the same sketch with light comments.

// HC-SC04 ultrasonic distance sensor module program
const int triggerPin = 7; //trigger for 7
const int echoPin = 8; // ECHO at 8
int duration = 0; // stores the value from pulseIn
int distance = 0; // stores the value of the calculated distance
void setup()
{
Serial.begin(9600);
pinMode(triggerPin, OUTPUT); //defines pin modes
pinMode(echoPin, INPUT);
}
void loop()
{
digitalWrite(triggerPin, HIGH); // starts sending ultrasound
delay(5); //required command, configurable (but not lower than 10 microseconds)
digitalWrite(triggerPin, LOW); // module stops sending ultrasound
duration = pulseIn(echoPin, HIGH); // determines how long the ECHO pin has been energized
delay(10); //necessary command, configurable, but carefully
distance = (duration/2) / 58; // calculate the distance in cm to the object
delay(500); // pause for stability, decreasing may break the flow of the program, it is better to leave it as is
Serial.print(distance); //sends the current value stored in distance to the serial monitor
Serial.println("cm"); // displays the word "cm" immediately after the distance
Serial.println(); // creates one empty line in the serial monitor (for readability)
}

I will also attach .ino files to the instructions

Files

  1. HCSR04BareBones.ino - this file is heavily commented and contains some information on the HC-SR04 module, as well as assembly information.
  2. BareBonesLight.ino - a module with a small number of comments

Here's my advice. I know that the code works, but before attaching the files to the instructions, I double-checked everything and the serial monitor consistently showed “0 cm”. The problem turned out to be a burnt-out module, and replacing it corrected the situation.

Look at how the program responds if you decide to play with the values ​​of the delay commands. Through experience, I discovered that decreasing the delay values ​​or setting them to 0 can lead the program to an inoperative state.

Once you've set up your device, the only limit is your imagination. You can check that stationary objects are at the same distance and remain stationary. You can use the monitor to receive notifications when an object has moved past the sensor, etc.

I used the diagram above to determine that all objects are further than 60 cm from the sensor. Three diodes and a tweeter were used in the project. When all objects were further than 60 cm, the green LED was on. When something approached less than 60 cm, the green diode went out and the red light came on. If the object remained at a close distance for some time, the second red diode would light up and the beeper would start beeping. When the object moved 60 cm away, the beeper went silent, the red diodes went out, and the green light came on again. This didn't prevent all false alarms, but it worked for most cases where a bird flew past the sensor or a curious squirrel ran by.

Step 4: Known Issues

If you see the model of your ultrasonic module in this paragraph, then scroll below. I hope you find your problem and solve it.

  1. US-105
  2. DYP-ME007TX

Module US-105

The US-105 ultrasonic module uses a GPIO pin on the ECHO pin, which means different calculations to determine the distance. By pinning the GPIO to the ECHO pin, the pin is not held energized while sending a wave. Instead, when reflected ultrasound is received, a specific voltage is applied to the ECHO pin that is proportional to the time it takes for the ultrasound wave to travel and return back to the sensor. The following code will work with this module:

// Code for the ultrasonic module US-105 unsigned int EchoPin = 2; unsigned int TrigPin = 3; unsigned long Time_Echo_us = 0; //Len_mm_X100 = length*100 unsigned long Len_mm_X100 = 0; unsigned long Len_Integer = 0; // unsigned int Len_Fraction = 0; void setup() ( Serial.begin(9600); pinMode(EchoPin, INPUT); pinMode(TrigPin, OUTPUT); ) void loop() ( digitalWrite(TrigPin, HIGH); delayMicroseconds(50); digitalWrite(TrigPin, LOW) ; Time_Echo_us = pulseIn(EchoPin, HIGH); if((Time_Echo_us 1)) ( Len_mm_X100 = (Time_Echo_us*34)/2; Len_Integer = Len_mm_X100/100; Len_Fraction = Len_mm_X100%100; Serial.print("Distance: "); Serial.print(Len_Integer, DEC); Serial.print(".");< 10) Serial.print("0"); Serial.print(Len_Fraction, DEC); Serial.println("mm"); delay(1000); } // Конец программы

Module DYP-ME007TX

// Code for ultrasonic module DYP-ME007TX /* Connection Instructions * 5V from Arduino to VCC on module * GNG from Arduino to GND on module * OUT from module to digital pin 7 on Arduino */ #include #define RXpin 7 #define TXpin 7 SoftwareSerial mySerial(RXpin, TXpin); long mili = 0; byte mybuffer = (0); byte bitpos = 0; void setup() ( Serial.begin(9600); mySerial.begin(9600); ) void loop() ( bitpos = 0; while (mySerial.available()) ( if (bitpos< 4) { mybuffer = mySerial.read(); } else break; } mySerial.flush(); mili = mybuffer << 8 | mybuffer; Serial.print("Distance: "); Serial.print(mili / 25.4); Serial.print (" inches"); Serial.println(); delay(500); }