It is often important to know what time it is in the match. The API doesn’t tell us this, so we have to keep track ourselves. This can be done very simply with three lines of code. It is also a good example of creating and using variables. In this section we will create a variable “time,” then we’ll initialize it and finally increment it once every second. Since we want “time” to be available anywhere in our code, we will define this variable at the top of our program. Add the three lines below to your Hello Space program. Add the first line before the init() function, the second line inside the init() function and the third line after the DEBUG statement in the loop() function.
- int time; //Add before the init() function
- time = 0; //Add inside the init() function
- time++; //Add after DEBUG inside the loop() function
The resulting code should look like this.
//Declare any variables shared between functions here
//This function is called once when your code is first loaded.
//IMPORTANT: make sure to set any variables that need an initial value.
//Do not assume variables will be set to 0 automatically!
time = 0;
This should work, but won’t be very impressive, so let’s make one more change. Change the DEBUG statement to be:
DEBUG(("\nHello Space! Time: %d",time))
Okay this will not be all that impressive either, but at least we’ll see that something is happening. Run and view the simulation as you did in the last section paying attention to the Debug window. Leave the Load Settings as “Last simulated settings” or select the settings you created in the last section. When your program ran, several things happened. First when the C++ class that is your program was instantiated (created,) an integer variable “time” was created with an unknown value. Second, before the match started, the init() function was called which set the time variable to 0. Last, every time the loop() function was called, the last thing it did was increment the time variable. Consider the DEBUG statement to be the first line of loop() and time++ as the last and everything else will go between these lines.
What time does the match start?
The first time loop() is called you are in the first second, but the time is actually 0 – the beginning of the first second. I will use this convention. Some people prefer to treat the first call to loop() as time 1. There are two extremely simple ways to make this change – think about what they are, but leave this program the way it is for the purpose of the tutorial. Now that we’re clear on what goes where, let’s remove the comments and omit them for the rest of the tutorial for simplicity.