Our Goal


Material


Background Knowledge


What is ultrasonic wave?

Principle of Ultrasonic Distance Measurement

Hardware Connection


Connect sonar:bit to P10 on motor:bit. See picture below.

Software


Microsoft MakeCode

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

At the beginning of our program, we need to create a variable named away, which means the distance between our motor:bit car and the barrier detected. We set it to 0.

Set the speed of both motors to 100.

Step 3

create a forever loop to read the return value of sonar:bit in real time and assign its value to away.

Stop to Prevent Crash

When the distance detected (i.e. away) is under 8 cm, stop the car and delay time for 300 ms. After that, set the speed of both motors to a negative value(like -80) and delay time for 600 ms.

Steer to Avoid Barrier

When away is under 15 cm, then generate a random number among 0 to 99.

If the random number is under 50, assign a negative value to the right wheel. So the right wheel will reverse and the car will turn right.

If the random number is beyond 50, assign a negative value to the left wheel. So the left wheel will reverse and the car will turn left.

If away is beyond 15 cm, set the speed of both motors to 100 and the car will move forward.

Program

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

You can also download it from the page below.


Result


Think


FAQ


Relative Readings