How to Program the Pirate Ship Bot

This lesson will go over how to program the Pirate Ship Bot

What it Does

The Pirate Ship Robot is designed in such a way that it will sense an object on its right or left side, and it will swing towards it. If the robot has swung back and forth for a hundred times, it will play a melody.


Program the controller in such a way that:

  1. If the left sensor senses an object, swing to the left.
  2. If the right sensor senses an object, swing to the right.
  3. If the hundredth swing occurs, play a melody.

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 also need to set them up.

Then we will need to find the base level for our top IR sensors. We will use these base levels to know what normal is, which will allow us to know if something is covering one of them.

Then inside of void loop we need to read the sensors and save them so that w can check their values later.

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 the right or left sensor have detected an object. (Reminder! Click here to review how “if statements” work).

In order for the robot to swing in the left direction when an object its placed in front of the left sensor, it must check and make sure that it is going the opposite direction. To do so we will keep track of the last direction with variables. To make it move to the left it must update the variable lastDirection to left, and proceed with moving the motor CW at a 100 speed for 75 ms. “SuccessCount += 1” increments the value of SuccessCount by one, and helps keep track of the times it has been swung back and forth.

In case a hundred back and forth swings occurred, a melody may be played using the SmartInventor.Buzz command, which plays a specific note for a certain amount of time. In this example the number “6” is the indicator if this time, and it refers to 1/6th of a second. Also, the counter used to store the success count, must be reset to zero after the 100th success.

Optional: In order to customize the robot’s actions, the motor speed or the delay time may be changed accordingly.

Final Code