1 - Moveable Pixel
Code
from machine import Pin, PWM
import time
import _thread
class LED_Matrix():
def __init__(self):
# Create a list of pin numbers
self.row_pins = [6,4,7,5,3,8,2,9]
self.row_pins.reverse()
self.col_pins = [10,11,12,13,18,19,20,21]
# Create empty lists to contain the Pin objects
self.rows = []
self.cols = []
# Use the list of pin numbers to create
# Pin objects and add them to the lists
# created above.
for i in self.row_pins:
self.rows.append(Pin(i, Pin.OUT))
for i in self.col_pins:
self.cols.append(Pin(i, Pin.OUT))
# Create empty 8x8 array
self.matrix = [[0]*8]*8
# Create a counter for current row
#self.cur_row = 0
self.cur_col = 0 # !IMPORTANT! Interating over columns offers better brightness than iterating rows!
def clear(self):
self.matrix = [
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0]
]
def next_row(self):
# Deactivate current row
self.cols[self.cur_col].value(0)
# Increment current row
self.cur_col = (self.cur_col + 1) % 8
# Load next row's columns
for i in range(8):
self.rows[i].value(self.matrix[self.cur_col][i])
# Activate next row
self.cols[self.cur_col].value(1)
class Sprite():
def __init__(self):
self.x = 0
self.y = 0
def right(self):
self.y += 1
if self.y >= 8:
self.y = 7
def left(self):
self.y -= 1
if self.y <= -1:
self.y = 0
def down(self):
self.x += 1
if self.x >= 8:
self.x = 7
def up(self):
self.x -= 1
if self.x <= -1:
self.x = 0
def update_display():
while True:
global display
display.next_row()
time.sleep_ms(2)
def game_loop():
# Main Loop for game, runs at 30 Hz
global display
while True:
display.clear()
if not up.value():
s.up()
if not down.value():
s.down()
if not left.value():
s.left()
if not right.value():
s.right()
# Draw the sprite on the LED matrix
display.matrix[s.x][s.y] = 1
# Do nothing for 33ms, (30Hz Frame-Rate)
time.sleep_ms(33)
# Create LED Matrix object
display = LED_Matrix()
# Create Button Objects
up = Pin(14, Pin.IN, Pin.PULL_UP)
down = Pin(17, Pin.IN, Pin.PULL_UP)
left = Pin(16, Pin.IN, Pin.PULL_UP)
right = Pin(1, Pin.IN, Pin.PULL_UP)
# Create Sprite Object
s = Sprite()
# Use second core to constantly run the display
_thread.start_new_thread(update_display,())
# Use main core to run game loop at 30Hz
game_loop()
Last updated