How to Program the Mouse Bot

This lesson will go over how to program the Mouse Bot

What it does?

The Mouse Bot senses the objects on its left, front, and right side, and it tries to avoid them by making turns.


Check the top left, front, and right IR sensors:

  1. If see something to the left, turn right.
  2. If see something to the right, turn left.
  3. If see something in front, turn left
  4. Otherwise go forward.

We are going to start with the setup code. We will need to include the SmartInventor library at the top of the code. Then since we will be needing the motors to move us around, we will need to set them up.
Next inside of void loop we will need to read the values of the sensors and save them so that we can use them later in our code.
Now it is time to write the main section of the code. In order to do so, an “if statement” may be used to check whether any of the top sensors have detected an object. (Reminder! Click here to learn how “if statements” work). We will add the statement to check whether the left sensor has detected an object, and if it has we will try to move away.
Similarly, the case when the right sensor detects an object should be considered. To do so, it is more efficient to use an “else if statement”. This statement will be executed only if the previous if statement is false.
Also another “else if statement” is needed in the case when the center sensor detects an object:
And finally, an “else statement” should be used to direct the robot to go forward in case no objects were detected by the sensors.
Optional: In order to customize the robot’s actions, the speed or the delay time may be changed.

Final Code