How to Program the Turret Bot

This lesson will go over how to program the Turret Bot

What it Does

This robot is designed to be controlled with the on board sensors such that if you cover the left one it will turn to the left and the right one will turn it to the right. Then the center sensor will be use to fire the rubber band.


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 middle sensor senses an object, shoot the rubber band.

For this program we need to be able to control the direction of the turret and be able to shoot it. We will use the top three IR sensors to control it.

We will start by getting all of the code setup. We need to include the SmartInventor library to get all of the needed background files and setup the motors.
Then what we will do is check to see what the base level that our sensors are reading, this way we can tell if there is something closer to it. Inside of void setup() we will read the values of the sensors and then save that value into some variables. To make sure that we have a little room for error we will subtract 50 from each of the sensors to make a threshold for it that is less than the normal reading. Note that since our board is upside down the left sensor (the one on our left) is technically the right sensor on the board (pin 21).

Next in void loop() we will read the sensors and check to see if any of them are being pressed.
With this code it will check to see if the right sensor is less than normal. Then if it is not it will check if the left sensor is less than normal. And then if it is not it will check if the center sensor is less than normal. This way it will check them one at a time, and it will only ever do one of them to prevent it from just wiggling back and forth if both the left and right ones are covered.

Now we can have the motors spins added in to this code. We we have the motors turn for a short amount of time and then stop for a small amount of time. This way it will move in small increments to allow for better control of it.
Next we will add in LEDs to give us some feedback as to what the robot is doing. We will have the left two LEDs on when the left sensor is covered, the right two on when the right sensors is covered, and the middle two on when the center one is covered. We need to setup the LEDs as outputs first so that we can control them (we will use pinMode() for that). Then we will have the appropriate LEDs turn on when it enters the if statement and turn them back off just before it exits the if statement.

Final Code