Lesson: Exercise: Timing Considerations
Understand the speed of program execution on a robot and what that means for your program. Understand how to write code that does not fail due to timing issues.
When programming robots (or any other real-time system), it is very important to understand how the speed realm of the robot differs from your own. When we look at our robot program, we see the while loop that we use to perform the read-environment/make-decision/act repeating pattern. We tend to think of this loop as happening slowly or at least as we might think of going through these operations.
The reality is that the robot will execute the while loop in our program thousands of times per second. The robot operates much faster than you think. This can lead to bugs in your programs in some situations.
Consider the example code below. The purpose of the program is to perform two actions controlled by the gamepad buttons. The program will count each time your press button A and on each press of button B, toggle a boolean variable from true to false. Download the program in Android Studio and test it on your robot.
So what happened? When you pressed the A button the immediate result is the program counted hundreds or thousands of button presses. Why? Because while the A button press seemed to you to be quick, on the program's time scale the button was down for many repeats of the while loop, and it counted each loop. Same for the B button. The setting of the boolean value bButton seems erratic and definately not a toggle each time the button is pressed. Again, due to the fact that your idea of a button press and the program's idea of a button press are quite different.
What do we do about this? We have to write code to handle this situation and convert the many button presses seen by the while loop into one logical press and act only when the one logical press happends. Here is the example program modified to handle the timing problems:
Download this program into Android studio and try it out. You should see the button presses now handled correctly.
The use of the variables aButtonPressed and bButtonPressed to track the state of the button is called latching.
In the earlier lesson Using Servos, we observed that the code that moved the arm up and down was susceptible to the timing issue discussed in this lesson. Even though you momentarily pushed the button to make the robot arm move up or down, the arm would keep moving after button release and it was hard to move the arm with any precision. Here is an example of how the code that handles moving the arm in response to button presses could be rewritten to move the arm a constant fixed amount for each quick button press and move the arm a longer distance for a long button press. Try it out: