# 5. case 02 Keep Distance#

## 5.1. Our Goal#

Make motor:bit smart car keeps distance with another car.

## 5.3. Background Knowledge#

### What is ultrasonic wave?#

Ultrasonic Wave is a kind of sound wave with frequency higher than 20,000 Hz. It has good direction sense and strong penetration. It is easy to obtain comparatively concentrated sound energy and travel long distance underwater. It can be used to measure distance or speed, rinse, weld, break stones, or sterilize, etc.. Ultrasonic wave is named for its lower frequency limit is higher than the upper limit of human audible sound.

### Principle of Ultrasonic Distance Measurement#

The transmitter emits ultrasonic wave to a certain direction. At the same time, it starts timing when emitting. Once encountered with a barrier, the ultrasonic wave spread in the air will be reflected back immediately. When the receiver has received the reflected wave, it will stop timing immediately. We can calculate the distance according to the time since the receiver has received the reflected wave, which is similar to radar ranging principle.

## 5.4. Hardware Connection#

Connect sonar:bit to P5 on motor:bit.

## 5.5. Software#

Microsoft MakeCode

## 5.6. Programming#

### Step 1#

Click Advanced in the code drawer of MakeCode to see more options.

To program for motor:bit, we have to add a package. Find Add Package in the bottom of code drawer and click it. This will pop up a dialogue box. Search for “motorbit” and then click to download this package.

Note: If you get a hint that some packages will be deleted due to the problem of incompatibility, you can either follow the prompts, or create a new project in the project menu.

### Step 2#

Insert a `move forward with speed` block below `on start`, and set its parameter to 80, which means the car moves forward at the speed of 80 once powered on. The unit of ultrasonic wave is centimeter(cm). Read the value of P5 and assign its return value to variable `item`. If the return value is above 10 but under 20, set the speed of motors to 0 and stop the car. If the return value is under 20, set the motor speed to 80 and make the car reverse. If none of these values meet, set the motor speed to 80 and make the car move forward.

### Program#

Link of the whole program: https://makecode.microbit.org/_5uq9T8d0p6hP