Building Smart LEGO MINDSTORMS EV3 Robots
上QQ阅读APP看书,第一时间看更新

Program the return-to-center (right side)

If the turret has strayed too far to the right (motor D has > | 250 degrees), the tank will need to make a sharp right turn to center the beacon within its line of sight again and center the turret. We will add some programming in the true case of our new switch that will do just that.

First, add a medium motor block and set it to turn motor D off. This case executes when the turret starts to rotate too far, so we need to stop it to make sure it does not over-rotate.

Next, the tank will make its sharp right turn. We will use the move tank block, which allows us to individually control the power of both drive motors (port B + C). Set its mode to On for Seconds. Set the power of motor B, the left drive motor, to 75 percent. Set the power of motor C, the right drive motor, to -75 percent. Powering the motors in opposite directions allows the tank to make a quick spin turn. We want the tank to turn for 1.2 seconds, so enter that as the target time value. 

Directly after that, we can place another move tank block, this time with the mode set to Off. This will halt the drive motors after the tank has made its turn.

The last part of this segment is some code that returns the turret to center. Add a loop block. We will set a special exit case for this loop. Change the mode on the loop to Motor Rotation | Compare | Degrees. This will work in a similar manner to the compare switches we programmed earlier. We will set a target degree value and the motor will rotate until it reaches this target. Change the compare type to < (type 4) and make the threshold value 3 degrees. Make sure the motor in port D is selected. Inside the loop, place a medium motor block. Set the block to simply turn the motor On at -50 percent power. This loop will power motor D in the negative direction until its degree value is less than three (which is very close to the center):

It is good practice to set the target degree value to  < 3  as opposed to  = 0 . This is because the EV3 motor encoders (also known as degree counters) have an error of about one degree; also, there are only so many times the EV3 can check the degree value on motor D in one second. As a result of these two factors, there is a very small possibility that the EV3 will miss when the degree value is  exactly  equal to zero and the motor will never stop.  | 0 is too specific of a case, so we program in  < | 3  instead as a safety net; it will never fail, and will still get the turret into the center position.
You can try experimenting with the target degree value to see how it affects the accuracy of the centering. If you set it to a smaller number (1 or 2 degrees), will the turret return to center more accurately, or does this make the turret rotate past center? Setting a larger target degree value (for example, 5 degrees) will make the turret stop just before reaching the center position. Give it a try!