First, we'll think up some random numbers and use the set_pixel
function to place a random colour on a random location on the Sense HAT display.
-
Open Python 3 and create a new file.
-
In the new file, start by importing the Sense HAT module:
from sense_hat import SenseHat
-
Next, create a connection to your Sense HAT by adding:
sense = SenseHat()
-
Now think of a random number between 0 and 7 and assign it to the variable
x
, for example:x = 4
-
Think of another random number between 0 and 7, then assign it to
y
:y = 5
-
Think of three random numbers between 0 and 255, then assign them to
r
,g
, andb
:r = 19 g = 180 b = 230
-
Now use the
set_pixel
function to place your random colour at your random location on the display:sense.set_pixel(x, y, r, g, b)
-
Check over your code. It should look like this, with your own random numbers assigned to the variables:
from sense_hat import SenseHat sense = SenseHat() x = 4 y = 5 r = 19 g = 180 b = 230 sense.set_pixel(x, y, r, g, b)
-
Now run your code by pressing
F5
. You should see a single pixel light up. -
Now pick some new random numbers - change them all - and run the program again. A second pixel should appear on the display!
So far you've picked your own random numbers, but you can let the computer choose them instead.
-
Add another
import
line at the top of your program, belowfrom sense_hat import SenseHat
:from random import randint
-
Now change your
x =
andy =
lines to automatically select a random position:x = randint(0, 7) y = randint(0, 7)
-
Run your program again, and you should see another random pixel being placed on the display. It will be the same colour you chose previously.
-
Now change your colour value lines to:
r = randint(0, 255) g = randint(0, 255) b = randint(0, 255)
Now your program will automatically select a random colour.
-
Run it again, and you should see another pixel appear in a random location with a random colour.
-
Run it a few more times, and you should see more of the grid fill up with random pixels.
Rather than have to keep running your program, you can add a loop so that it will keep going.
-
First, add an
import
to the top of your file:from time import sleep
You'll use this to pause the program between pixels.
-
Add a
while True:
to your code so that the random lines,set_pixel
andsleep
are all within the loop:while True: x = randint(0, 7) y = randint(0, 7) r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) sense.set_pixel(x, y, r, g, b) sleep(0.1)
-
Run the code and you should see random sparkles in action!