Time
Use the Time blocks to pause code or get a timestamp from when the program was started.
Example 1: Using sleep blocks
Sleep blocks pause the code for a designated amount of time. In this example, the code turns on the red LED on for one second, then turns on the blue LED for a half second, and finally turns on the green LED for two seconds. Note that, when a program is sleeping, it's not performing any other task.
Example 2: Sleep block causing an error
Say you want to change the //code.Node RGB LED color every two seconds and also turn the //code.Node speaker on or off by using the //code.Node buttons. In this example, if you press Button 1, the speaker may or may not turn on. This is because the code only checks the button state after every two seconds. If the button isn't pressed down during that check, then the code doesn't turn on the speaker. To get the speaker to turn on, you must press and hold Button 1 so that, when the LED changes, the state of Button 1 is true
. To turn the speaker off, press and hold Button 2 so that it's held down the same time the LED changes.
Tip
See Example 4 for a method to fix this problem.
Example 3: Getting the instantaneous time
Use the get time in ms block to get a timestamp of when an event happens. In this example, the code uses this block to determine how long it takes for the temperature to reach 25 °C. Use the number output block from the Code Output group to display the time.
Example 4: Perform synchronous functions
Use the get time in ms block if you want tasks to happen every x amount of seconds. In this example, set a variable timeCheck
to the time stamp at the start of the program. Then use an if statement with a condition that sets timeCheck
to the current time stamp every two seconds and runs the setRandomLED
function. At the same time, use a separate conditional statement to make the //code.Node speaker turn on by pressing Button 1 or turn off by pressing Button 2. The loop doesn't have to stop before turning the speaker on or off. This doesn't work with the sleep blocks as see in Example 2.