# 11. Ultrasonic ranging

## 11.1 Overview
 
 In this section you will learn how to use the Ultrasonic Module. The ultrasonic sensor is used to measure distance and the
 value is displayed on the OLED screen in real time.
 
## 11.2 Working principle

### 11.2.1 Ultrasonic sensor

<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/11.lesson_ultrasonic.png" width="300" height="100"/>

 Sound waves are produced by vibrations and can travel at different speeds in different media. Ultrasonic waves have the
 advantages of strong directivity, slow energy loss, and long propagation distance in media, and are often used for distance
 measurement. For example, distance meters, liquid level measuring instruments, etc. can all be realized through ultrasonic
 waves.

|||
|----|----| 
|Electrical parameters|HC-SR04 Ultrasonic module|
|Working voltage|DC-5V|
|Working current|15mA|
|Working frequency|40KHz|
|Maximum range|4m|
|Minimum range|2cm|
|Measuring angle|15°|
|Input trigger signal|10 USTTLpulse|
|Output echo signal|Output TTL level signal, proportional to the range|
|||
 
 Ultrasonic ranging is a non-contact detection method , especially used in airborne ranging. Because the wave speed in the
 air is slow, the echo signal contained along the direction of structural information propagation is easy to detect and has very
 high resolution, so it The accuracy is higher than other methods; the ultrasonic sensor has the characteristics of simple
 structure, small size, and reliable signal processing. The use of ultrasonic detection is often faster, more convenient, simpler
 to calculate, easier to achieve real-time control, and can meet industrial practical requirements in terms of measurement
 accuracy.
 
 There are many methods of ultrasonic ranging. The principle of this system in ultrasonic measurement is: the trigger signal
 input terminal ( TRIG ) will input a high-level signal of more than 10 microseconds.After receiving the signal, the
 ultrasonic transmitter will automatically send 8 A 40Hz square wave.At the same time, the timer will start. When the sensor
 receives the echo, it stops timing and outputs the echo signal. Detect the ultrasonic wave from the ultrasonic transmitter, the
 transmission time through the gas medium to the receiver , multiply this time by the speed of sound in the gas, and get the
 distance of sound propagation. That is, the ultrasonic transmitter emits ultrasonic waves in a certain direction, and the MCU
 starts timing at the same time. The ultrasonic waves are launched in the air and return immediately when encountering
 obstacles on the way. The ultrasonic receiver stops timing immediately after receiving the reflected waves.
 Trecorded by the timer , the distance ( s ) from the launch point to the obstacle can be calculated .
 
 **Formula: S = VT/2**
 
 Four factors limit the maximum measurable distance of an ultrasound system: the amplitude of the ultrasound wave, the
 texture of the reflector, the angle between the reflected and incident sound waves, and the sensitivity of the receiving
 transducer. The ability of the receiving transducer to directly receive the acoustic pulse will determine the minimum
 measurable distance.
 
### 11.2.2 OLED

<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/11.lesson_oled.png" width="150" height="150"/>

 1. Resolution: 128*64
 2. Super wide viewing angle: greater than 160
 3. Communication method: IIC
 4. Working voltage: 3.3V~5V
 
## 11.3 Connection lines

<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/11.lession_connect_line.png" width="800" height="600"/>
 
## 11.4 Upload code program

### 11.4.1 Connect the main control board to the computer with a USB cable

<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/upload_code_program.png" width="600" height="200"/>

### 11.4.2 Open the program file ( path : 2_ESP32_S3_PLUS \ Lesson_11_Ultrasonic_ranging_OLED_display )
 Also select the board type as ESP32S3 Dev Module and select the COM number newly displayed when the USB is plugged
 in . Then click "Upload" to start compiling and uploading the program to the main control board, and wait for the program
 upload to be completed .
 After the program is uploaded, use an object to block the ultrasonic wave and see the measured distance value ( when the
 screen does not display correctly, you need to check the SCL/SDAwiring, or press the motherboard reset button to reset the
 program ).

<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/11.lesson_oled_output.png" width="200" height="200"/>
 
## 11.5 Code analysis

Declare the required libraries. If the corresponding libraries are not added, please go back to the installation libraryto see how to add the libraries.

```cpp
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
```

Define the pixel parameters of the OLED screen and instantiate a screen object display

```cpp
#define SCREEN_WIDTH 128  // Define the screen width to be 128 pixels
#define SCREEN_HEIGHT 64  // Define the screen height to be 64 pixels
#define OLED_RESET -1     // Define the OLED reset pin to -1 (or -1 if the reset function is not used)
// Create an Adafruit_SSD1306 object that controls the OLED screen, specifying the screen width, height, I2C bus object, and reset pin
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
```

Define ultrasonic sensor pins and distance variables

```cpp
#define Echo 18      // Define the ultrasonic Echo pin
#define Trig 17      // Define the ultrasonic Trig pin
int Udistance = 0;  // Define the ultrasonic distance variable
```

Set the ultrasonic pin Echo as input, Trig as output, initialize IIC bus and initialization screen, baud rate 9600

```cpp
void setup() {
  Serial.begin(9600);
  pinMode(Echo, INPUT);   // Define the pin operation mode as the input
  pinMode(Trig, OUTPUT);  // Define the pin operation mode as output
  Wire.begin(5,4);        // The initial I2C bus SDA pin is set to 5 and the SCL pin is set to 4

  // Initializing the screen
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 initialization failed"));
    for (;;)
      ;
  }
}
```

Ultrasonic acquisition distance function
```cpp
float GetDistance()  // Get ultrasonic sensor values
{
  float distance;
  digitalWrite(Trig, LOW);  // Sending a low level to the Trig triggers ranging
  delayMicroseconds(2);
  digitalWrite(Trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(Trig, LOW);
  distance = pulseIn(Echo, HIGH) / 58.00;  // Output distance conversion
  // delay(10);
  return distance;
}
```

The loop function first obtains the distance value of the ultrasonic detection module and saves it to the variable Udistance.
The value is output to the screen display through the display method of the screen object.

```cpp
void loop() {
  Udistance = GetDistance();  // Obtaining ultrasonic distance
  display.clearDisplay();     // Clear the screen buffer
  // Display ultrasonic distance
  display.setTextSize(2);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(16, 8);
  display.println("Distance");
  display.setCursor(32, 40);
  display.print(Udistance);
  display.print(" cm");
  display.display();
  //delay(200);  // Delay the next read for a while to adjust the update rate
  Serial.print("Distance = ");
  Serial.println(Udistance);
}
```
