Skip to content

Commit 1edfbf4

Browse files
authored
Merge pull request #187 from realpython/notexactlyawe/embedded-python
Complete code for embedded Python article
2 parents 8de42a2 + b267862 commit 1edfbf4

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

embedded-python/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Embedded Python Sample Code
2+
3+
This folder contains the complete program built in the Real Python tutorial on embedded Python.
4+
5+
You can run this code either on a BBC micro:bit or by pasting it into the [online simulator](https://www.cameronmacleod.com/createwithcode/).

embedded-python/simon_says.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from microbit import display, Image, accelerometer, sleep
2+
from random import randrange
3+
4+
# Define left, stay still and right
5+
directions = ["L", "O", "R"]
6+
points = 0
7+
8+
# While the micro:bit is on
9+
while True:
10+
# Pick a random direction
11+
direction = directions[randrange(3)]
12+
display.show(direction)
13+
# Sleep for a second (1000ms)
14+
sleep(1000)
15+
16+
# Get the X-axis (left-right) tilt
17+
acc_x = accelerometer.get_x()
18+
# Determine direction
19+
if acc_x < -200:
20+
player_in = "L"
21+
elif abs(acc_x) < 200:
22+
player_in = "O"
23+
elif acc_x > 200:
24+
player_in = "R"
25+
26+
# Check win condition
27+
if player_in == direction:
28+
# Player's input is correct
29+
points += 1
30+
else:
31+
display.scroll(points)
32+
display.show(Image.SAD)
33+
points = 0
34+
sleep(1000)

0 commit comments

Comments
 (0)