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:
- If the light is shining from the left, move to the right.
- If the light is shining from the right, move to the left.
- If the light is shining from the center, move back and forth.
- 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-6758b10776341998467581/]
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-6758b10776349787713799/]
Next we need to read the values of the sensor in loop and save them for later use.
[crayon-6758b1077634a341489573/]
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-6758b1077634c174149726/]
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-6758b1077634e503598911/]
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-6758b1077634f522840124/]
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-6758b10776351066721674/]
Optional: In order to customize the robot’s actions, the speed or the delay time may be changed accordingly.
Final Code
[crayon-6758b10776352629663977/]