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.
[crayon-66052cf576890108691232/]
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.
[crayon-66052cf576896781905056/]
Next we need to read the values of the sensor in loop and save them for later use.
[crayon-66052cf576898209400672/]
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.
[crayon-66052cf576899262635508/]
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.
[crayon-66052cf57689b602302147/]
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.
[crayon-66052cf57689c351753872/]
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.
[crayon-66052cf57689d881730676/]
Optional: In order to customize the robot’s actions, the speed or the delay time may be changed accordingly.

Final Code

[crayon-66052cf57689f418247420/]