Your code can only run for 30 seconds or it will be rejected during our code review and will not be sent to Wonder. To add this functionality, we are going to create a counter variable that increases as our program runs. Then we will modify the while
loop to only run while this counter variable is less than 30. Finally, we will add a command telling the LED screen to clear and the program to quit once the while
loop is terminated.
Let’s first create a timer
variable and add it to the beginning of our program. You can also create a variable called team_name
that we will use in the next lesson for recording the data of your program.
We are setting timer = 1
because we use sleep(1)
at the beginning of our program and we need to account for this one second before we start the while
loop. Since the loop currently runs as fast as the Raspberry Pi processor, we will also need to slow our loop down to an increment that we can track. But we don’t want to slow it down so much that we don’t sense the motion of the ship. Imagine if we only grabbed data from our sensors every five seconds: we would miss all of the color and motion data during that five seconds! We have found that 0.1 works really well. This causes our sensors to get data ten times every second. We strongly suggest using this value.
When you create your team name, do not use spaces or any special characters. Just letters, numbers, and _.
#### Housekeeping
# Libraries
from sense_hat import SenseHat
sense = SenseHat()
from time import sleep
# Timer and team name
team_name = "Whale_Demo"
timer = 1
increment = 0.1
Now that we have a timer variable, let’s head down to our while
loop and modify it. We need to change two things: 1) we need to make the loop contingent on the value of timer
and 2) we need to increase timer
on every lap by our increment
. Here is the opening of the while
loop with the edits:
#### Create the GIF animation
while timer < 30:
### Timer
timer = timer + increment
sleep(increment)
### Color
# Arrange colors with updated color variable values on 8x8 matrix
image = [
f, f, f, g, g, g, g, g,
f, f, g, g, f, g, g, f,
f, f, f, f, f, f, g, g,
f, g, g, g, g, g, g, g,
g, g, g, g, g, g, d, d,
g, b, g, g, g, d, d, f,
g, g, g, g, d, d, f, f,
f, g, g, d, d, f, f, f]
Notice how we increase timer
by the exact amount that we sleep our program. If we don’t keep these values the same then our timer is not actually tracking the runtime of our program.
Finally, we need to have our program clear the LED screen and quit once the while
loop is over. Add the following code after your while
loop, ensuring that this code is not indented so that it is not part of the loop.
# Rotate our creature
if relative_heel > 4:
sense.set_rotation(270)
rotation = 270
if relative_heel < -4:
sense.set_rotation(90)
rotation = 90
if -4 <= relative_heel <= 4:
sense.set_rotation(0)
rotation = 0
# Store this lap's movement value for comparison on the next iteration of the loop
movement = new_movement
sense.clear()
quit()