In this tutorial, the robot will follow the black track by its IR light sensor which is located in its front end. Check the video:
|1~ 2 hours
|2 / 5
How to control the motor and robot behavior
In RK-micro:bit Car, the two motors are placed back-to-back, we call this a differential drive platform, which means the robot behaviors are decided by the direction/speed of these two motors.
Since we are using a L298n motor driver module to control the two motors, we acutually control four pins, two pins for one motor:
- P1, P2 – the left motor
- P14, P15 – the right motor
First we take a look at how to control one motor, if the motor rotate in the opposite direction, just switch the red/ black wire:
|P1 – H
|P1 – L
|P2 – H
|Brake (can NOT rotate the shaft)
|P2 – L
|Nothing (can rotate the shaft)
By combining two motors, we can make the robot move around, you can further adjust the motors’ speed to have more detailed control over the robot:
|Right motor – Forward
|Right motor – Backward
|Left motor – Forward
|Robot moves forward
|Robot turns right
|Left motor – Backward
|Robot turns left
|Robot moves backward
STEP1: In the
on start event, we declare a variable for the motor speed and use it to
STEP2: The code in
forever will run continuously, which means that it will keep looping until you unplug the microbit.
Since the IR light sensor is connected to
P12, and it will return
0 when it detects the black track and white ground. We can take advantage of this to make a zigzag line-following robot.
In the video, you can see we put the robot (IR light sensor) at the left-hand side of the black track, this means the robot will move toward the front right to seek for black track. If yes, then it will move toward the front left a little bit -> these two-conditional pattern will repeat forever.
So when the light sensor detects the black track (
digital read pin P12 = 1), the robot will move toward the front right, otherwise it will move toward the front left.
Note: please modify the motor parameters to make your robot move even better!
The complete code can be accessed at the following webpage or download the HEX file.
- makecode project: https://makecode.microbit.org/_KXjXMPJu7Rva
- hex file: https://drive.google.com/file/d/1GfYaJ-vlA3glWyfuw3tKW6C9wzicdAIU/view?usp=sharing