How to Program the Crab Bot

This lesson will go over how to program the Crab Bot

What it does?

The Crab Robot is designed to avoid light, similar to a real crab!

Objective

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

  1. If the light is shining from the left, move to the right.
  2. If the light is shining from the right, move to the left.
  3. If the light is shining from the center, move back and forth.
  4. Otherwise stop.

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 we need to find a base level for what the top IR sensors are reading. This way we can know if we are seeing an abnormal value. We will create some variables that will save the normal values for the sensors. However, we do not want to create these variables inside of void setup though. If we did they would only exist inside of setup and we could not use them in the loop. To allow us to use them in both we will create them as global variables and set the normal value to them in setup. For the normal value we will read the sensor and subtract 50 from it, this way we give a little extra room for normal.

Next we need to read the values of the sensor in loop and save them for later use.

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 increase in the brightness level.

The following statement checks whether the left sensor (leftSensorValue) has detected an increase in the brightness level with respect to the primary light level (leftBaseLevel); a smaller value means brighter. If it is triggered we will run to the right and light up the left LEDs.

Similarly, the case when the right sensor detects an increase in the brightness 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. When the center one detects something it will run back and forth trying to get away.

And finally, an “else statement” should be used to direct the robot to take no action in case no brightness change was detected by the sensors.

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

Final Code