Особенности применения ультразвукового дальномера hc-sr04 в качестве средства ориентации мобильного объекта

Step 3: Upload the Sketch

Copy the sketch to your Arduino and watch the blinky lights.

/*
HC-SR04 Ping distance sensor]
VCC to arduino 5v GND to arduino GND
Echo to Arduino pin 13 Trig to Arduino pin 12
Red POS to Arduino pin 11
Green POS to Arduino pin 10
560 ohm resistor to both LED NEG and GRD power rail
More info at: http://goo.gl/kJ8Gl
Original code improvements to the Ping sketch sourced from Trollmaker.com
Some code and wiring inspired by http://en.wikiversity.org/wiki/User:Dstaub/robotcar
*/
#define trigPin 13
#define echoPin 12
#define led 11
#define led2 10
void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
}
void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin, HIGH);
//  delayMicroseconds(1000); — Removed this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance < 4) {  // This is where the LED On/Off happens
    digitalWrite(led,HIGH); // When the Red condition is met, the Green LED should turn off
  digitalWrite(led2,LOW);
}
  else {
    digitalWrite(led,LOW);
    digitalWrite(led2,HIGH);
  }
  if (distance >= 200 || distance <= 0){
    Serial.println(«Out of range»);
  }
  else {
    Serial.print(distance);
    Serial.println(» cm»);
  }
  delay(500);
}

Пример работы

Рассмотрим как работает дальномер.

  • Для того чтобы инициализировать отправку сигнала дальномером, необходимо подать высокий сигнал длительностью 10 μs на пин .
  • После получения высокого сигнала длительностью 10 μs на пин , модуль генерирует пучок из восьми сигналов частотой 40 кГц и устанавливает высокий уровень на пине .
  • После получения отраженного сигнала модуль устанавливает на пине низкий уровень.

Зная продолжительность высокого сигнала на пине можем вычислить расстояние, умножив время, которое потратил звуковой импульс, прежде чем вернулся к модулю, на скорость распространения звука в воздухе (340 м/с).

Функция позволяет узнать длительность импульса в . Запишем результат работы этой функции в переменную
duration.

Теперь вычислим расстояние переведя скорость из м/с в см/мкс:

Преобразуем десятичную дробь в обыкновенную

Принимая во внимание то, что звук преодолел расстояние до объекта и обратно, поделим полученный результат на 2

Оформим в код всё вышесказанное и выведем результат в Serial Monitor

ultrasonic.ino
// Укажем, что к каким пинам подключено
int trigPin = 10; 
int echoPin = 11;  
 
void setup() { 
  Serial.begin (9600); 
  pinMode(trigPin, OUTPUT); 
  pinMode(echoPin, INPUT); 
} 
 
void loop() { 
  int duration, distance;
  // для большей точности установим значение LOW на пине Trig
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2); 
  // Теперь установим высокий уровень на пине Trig
  digitalWrite(trigPin, HIGH);
  // Подождем 10 μs 
  delayMicroseconds(10); 
  digitalWrite(trigPin, LOW); 
  // Узнаем длительность высокого сигнала на пине Echo
  duration = pulseIn(echoPin, HIGH); 
  // Рассчитаем расстояние
  distance = duration  58;
  // Выведем значение в Serial Monitor
  Serial.print(distance); 
  Serial.println(" cm"); 
  delay(100);
}

Работа с библиотекой

Количество строк кода можно существенно уменьшить, используя библиотеку для работы с дальномером.

ultrasonic_lib.ino
#include <NewPing.h>
 
#define TRIGGER_PIN  10
#define ECHO_PIN     11
#define MAX_DISTANCE 400
 
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
 
void setup() {
  Serial.begin(9600);
}
 
void loop() {
  delay(50);
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm());
  Serial.println("cm");
}

Работа с Iskra JS

var sonic = require('@amperka/ultrasonic')
  .connect({trigPin P10, echoPin P11});
 
sonic.ping(function(err, value) {
  if (err) {
    console.log('An error occurred:', err);
  } else {
    console.log('The distance is:', value, 'millimeters');
  }
}, 'mm');

Example code for JSN-SR04T sensor with Arduino

Now that you have wired up the sensor it is time to connect the Arduino to the computer and upload some code. The sensor can be used without an Arduino library. Later I will show you an example with the NewPing library, which makes the code a lot shorter.

You can upload the following example code to your Arduino using the Arduino IDE. Next, I will explain to you how the code works. This code works for the JSN-SR04T-2.0 too.

You can copy the code by clicking the button in the top right corner of the code field.

/* Arduino example sketch to control a JSN-SR04T ultrasonic distance sensor with Arduino. No library needed. More info: https://www.makerguides.com */

// Define Trig and Echo pin:
#define trigPin 2
#define echoPin 3

// Define variables:
long duration;
int distance;

void setup() {
  // Define inputs and outputs
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  
  // Begin Serial communication at a baudrate of 9600:
  Serial.begin(9600);
}

void loop() {
  // Clear the trigPin by setting it LOW:
  digitalWrite(trigPin, LOW);
  
  delayMicroseconds(5);

 // Trigger the sensor by setting the trigPin high for 10 microseconds:
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  // Read the echoPin. pulseIn() returns the duration (length of the pulse) in microseconds:
  duration = pulseIn(echoPin, HIGH);
  
  // Calculate the distance:
  distance = duration*0.034/2;
  
  // Print the distance on the Serial Monitor (Ctrl+Shift+M):
  Serial.print("Distance = ");
  Serial.print(distance);
  Serial.println(" cm");
  
  delay(100);
}

You should see the following output in the serial monitor:

How the code works

First, the trigger pin and the echo pin are defined. I call them  and . The trigger pin is connected to digital pin 2 and the echo pin to digital pin 3 on the Arduino.

The statement  is used to give a name to a constant value. The compiler will replace any references to this constant with the defined value when the program is compiled. So everywhere you mention , the compiler will replace it with the value 2 when the program is compiled.

// Define Trig and Echo pin:
#define trigPin 2
#define echoPin 3

Next, I defined two variables:  and . Duration stores the time between sending and receiving the sound waves. The distance variable is used to store the calculated distance.

//Define variables
long duration;
int distance;

In the , you start by setting the trigPin as an output and the echoPin as an input. Next, you initialize serial communication at a baud rate of 9600. Later you will display the measured distance in the serial monitor, which can be accessed with Ctrl+Shift+M or Tools > Serial Monitor. Make sure the baud rate is also set to 9600 in the serial monitor.

void setup() {
  // Define inputs and outputs
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  
  // Begin Serial communication at a baudrate of 9600:
  Serial.begin(9600);
}

In the , you trigger the sensor by setting the trigPin HIGH for 20 µs. Note that to get a clean signal you start by clearing the trigPin by setting it LOW for 5 microseconds.

void loop() {
  // Clear the trigPin by setting it LOW:
  digitalWrite(trigPin, LOW);
  
  delayMicroseconds(5);

 // Trigger the sensor by setting the trigPin high for 10 microseconds:
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

Next, you need to read the length of the pulse sent by the echoPin. I use the function  for this. This function waits for the pin to go from LOW to HIGH, starts timing, then waits for the pin to go LOW and stops timing.

After that, you can calculate the distance by using the formula mentioned in the introduction of this tutorial.

  // Read the echoPin. pulseIn() returns the duration (length of the pulse) in microseconds:
  duration = pulseIn(echoPin, HIGH);
  
  // Calculate the distance:
  distance = duration*0.034/2;

Finally, print the calculated distance in the serial monitor.

  // Print the distance on the Serial Monitor (Ctrl+Shift+M):
  Serial.print("Distance = ");
  Serial.print(distance);
  Serial.println(" cm");
  
  delay(100);
}

Пьезоэффект и магнитострикция

Как же получить колебания в ультразвуковом диапазоне?

Кристаллы некоторых материалов (таких как кварц) способны совершать очень быстрые колебания, при прохождении через них электричества. Это, так называемый, обратный пьезоэффект. Во время вибрации, они толкают и тянут воздух вокруг себя, производя, тем самым, ультразвуковые волны. Устройства, которые производят ультразвуковые волны с помощью пьезоэлектричества известны как пьезоэлектрические преобразователи. Пьезоэлектрические кристаллы также работать в обратном порядке: если ультразвуковые волны, распространяясь по воздуху,  сталкиваются с пьезоэлектрическим кристаллом, слегка деформируют его поверхность, в результате чего в кристалле возникает электрическое поле. Итак, если подключить пьезоэлектрический кристалл к измерителю электрического напряжения, мы получим детектор ультразвука.

Пьезоэлектрический эффект

Ультразвуковые волны могут быть получены с использованием магнетизма вместо электричества. Так же, как пьезоэлектрические кристаллы производят ультразвуковые волны в ответ на электричество, существуют и другие кристаллы, которые излучают ультразвук в ответ на магнетизм. Это эффект магнистрикции. Такие кристаллы называются магнитострикционными кристаллами. Датчики, использующие их, называются магнитострикционными преобразователями.

В англоязычной литературе ультразвуковые датчики называются ultrasound sensor.

About the sensor

The sensor comes with a 2.5 m long cable that connects to a breakout board which controls the sensor and does all the processing of the signal. Note that only the sensor and the cable itself are waterproof, if you get water onto the breakout board, the sensor might stop working.

An ultrasonic distance sensor works by sending out ultrasound waves. These ultrasound waves get reflected back by an object and the ultrasonic sensor detects them. By timing how much time passed between sending and receiving the sound waves, you can calculate the distance between the sensor and an object.

Distance (cm) = Speed of sound (cm/µs) × Time (µs) / 2

Where Time is the time between sending and receiving the sound waves in microseconds.

So what are the differences between this sensor and the HC-SR04? The main difference, besides it being waterproof, is that this sensor uses only one ultrasonic transducer instead of two. This transducer serves as both the transmitter and the receiver of the ultrasound waves.

For more info on how ultrasonic sensors work, you can check out my article on the HC-SR04. In this article the working principles of an ultrasonic distance sensor are explained in much greater detail.

JSN-SR04T Specifications

Operating voltage 5 V
Operating current 30 mA
Quiescent current 5 mA
Frequency 40 kHz
Measuring range 25-450 cm
Resolution 2 mm
Measuring angle 45-75 degrees
Sensor dimensions 23.5 x 20 mm, 2.5 m long cable
PCB dimensions 41 x 28.5 mm
Mounting hole 18 mm
Cost Check price

For more information you can check out the datasheet here.

JSN-SR04T Datasheet

Использование ультразвукового дальномера

Пьезоэлектродвигатели

Пьезоэлектрический преобразователь как альтернативный источник энергии

Пьезоэлектрические преобразователи в ультразвуковой диагностике

Импульсные ультразвуковые сонары открытого типа

Пьезо-сенсор стука на Arduino UNO

Справочник ультразвуковых излучателей и приемников

400EP250 Pulse Transit Enclose Type Ultrasonic TransduceСеть магазинов «Кварц»

https://www.stroykat.by/tipyi-datchikov-rashoda-zhidkostey.html

3Скетч Arduino для ультразвукового дальномера

Напишем скетч для нашего дальномера:

const int trigPin = 6; // вывод триггера датчика HC-SR04
const int echoPin = 5; // вывод приёмника датчика HC-SR04

#include <LiquidCrystal.h> // подключаем стандартную библиотеку
LiquidCrystal lcd(12, 11, 10, 9, 8, 7); //инициализация ЖКИ 

void setup() {
  pinMode(trigPin, OUTPUT); // триггер - выходной пин
  pinMode(echoPin, INPUT); // эхо - входной
  digitalWrite(trigPin, LOW); 
  lcd.begin(16, 2); //задаём кол-во строк и символов в строке
  lcd.setCursor(10, 0); // выравниваем надпись по правому краю
  lcd.print("Dist:");
  lcd.setCursor(14, 1); 
  lcd.print("cm");
}

void loop() {
  long distance = getDistance(); // получаем дистанцию с датчика   
  lcd.setCursor(10, 1);
  lcd.print("    "); // очищаем ЖКИ от предыдущего значения
  lcd.setCursor(10, 1);
  lcd.print((String)distance); // выводим новую дистанцию
  delay(100);
}

// Определение дистанции до объекта в см
long getDistance() {
  long distacne_cm = getEchoTiming() * 1.7 * 0.01;
  return distacne_cm;
}

// Определение времени задержки
long getEchoTiming() {
  digitalWrite(trigPin, HIGH); // генерируем импульс запуска
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // определение на пине echoPin длительности уровня HIGH, мкс:
  long duration = pulseIn(echoPin, HIGH);
  return duration;
}

Тут всё просто. Сначала инициализируем ЖКИ на выводах 12, 11, 10, 9, 8 и 7 с помощью библиотеки LiquidCrystal из состава Arduino IDE. Далее привяжем выводы «триггер» и «эхо» дальномера к выводам 6 и 5 платы Arduino. Каждые 100 мс будем запрашивать с детектора расстояние с помощью функции getDistance() и выводить на ЖК-дисплей.

У меня на LCD дисплее имеется дефект, и его левая половина почти не работает. Поэтому я вывожу надписи выровненными по правому краю.

После того как записали скетч в память Arduino, можем собирать прибор. Предлагаемая мной компоновка внутренностей показана на рисунке. Дисплей и датчик я закрепил с помощью термоклея. Он держит достаточно прочно, но при этом даёт возможность снять соединённые детали, если понадобится. Желательно всё разместить так, чтобы можно было подключиться к USB порту Arduino и поправить «прошивку» при необходимости. Например, изменить выводимый текст или поправить коэффициенты для расчёта дистанции. Может понадобиться менять контрастность ЖК дисплея, так что также желательно иметь в доступности регулятор потенциометра.

Вариант готового прибора показан на фотографии. Он достаточно компактен и удобен в использовании.

Вариант компоновки ультразвукового дальномера Внешний вид готового ультразвукового дальномера

Но следует иметь в виду несколько важных замечаний при его использовании:

  • Ультразвук лучше отражается от гладких поверхностей, чем от поглощающих (например, мягкого ковра). Поэтому следует выбирать место расположения дальномера при измерении так, чтобы напротив дальномера располагалась гладкая отражающая поверхность (например, стена).
  • Показания прибора могут существенно отличаться в зависимости от угла направления на цель. Поэтому лучше всего провести несколько измерений, немного изменяя угол направления на цель, и взять среднее значение от всех измерений.

Краткие выводы

Ультразвуковые датчики расстояния достаточно универсальны и точны, что позволяет их использовать для большинства любительских проектов. В статье рассмотрен крайне популярный датчик HC SR04, который легко подключается к плате ардуино (для этого следует сразу предусмотреть два свободных пина, но есть вариант подключения и с одним пином). Для работы с датчиком существуют несколько бесплатных библиотек (в статье рассмотрена лишь одна из них, NewPing), но можно обойтись и без них – алгоритм взаимодействия с внутренним контроллером датчика достаточно прост, мы показали его в этой статье.

Исходя из собственного опыта, можно утверждать, что датчик HC-SR04 показывает точность в пределах одного сантиметра на расстояниях от 10 см до 2 м. На более коротких и дальних дистанциях возможно появление сильных помех, что сильно зависит от окружающих предметов и способа использования. Но в большинстве случаев HC-SR04 отлично справлялся со своей работой.

Оцените статью:
Оставить комментарий