Skip to content

Commit 74ff27a

Browse files
Added example with bouncing ball animation
1 parent d6e50f4 commit 74ff27a

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

examples/bouncing_ball.py

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import board
2+
import busio
3+
import adafruit_ssd1306
4+
5+
# Create the I2C interface.
6+
i2c = busio.I2C(board.SCL, board.SDA)
7+
8+
# Create the SSD1306 OLED class.
9+
# The first two parameters are the pixel width and pixel height. Change these
10+
# to the right size for your display!
11+
oled = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c)
12+
13+
14+
# Helper function to draw a circle from a given position with a given radius
15+
def draw_circle(xpos0, ypos0, rad, col=1):
16+
x = rad - 1
17+
y = 0
18+
dx = 1
19+
dy = 1
20+
err = dx - (rad << 1)
21+
while x >= y:
22+
oled.pixel(xpos0 + x, ypos0 + y, col)
23+
oled.pixel(xpos0 + y, ypos0 + x, col)
24+
oled.pixel(xpos0 - y, ypos0 + x, col)
25+
oled.pixel(xpos0 - x, ypos0 + y, col)
26+
oled.pixel(xpos0 - x, ypos0 - y, col)
27+
oled.pixel(xpos0 - y, ypos0 - x, col)
28+
oled.pixel(xpos0 + y, ypos0 - x, col)
29+
oled.pixel(xpos0 + x, ypos0 - y, col)
30+
if err <= 0:
31+
y += 1
32+
err += dy
33+
dy += 2
34+
if err > 0:
35+
x -= 1
36+
dx += 2
37+
err += dx - (rad << 1)
38+
39+
center_x = 63
40+
center_y = 15
41+
x_inc = 1
42+
y_inc = 1
43+
radius = 5
44+
45+
# start with a blank screen
46+
oled.fill(0)
47+
# we just blanked the framebuffer. to push the framebuffer onto the display, we call show()
48+
oled.show()
49+
while True:
50+
# undraw the previous circle
51+
draw_circle(center_x, center_y, radius, col=0)
52+
53+
# if bouncing off right
54+
if center_x + radius >= oled.width:
55+
# start moving to the left
56+
x_inc = -1
57+
# if bouncing off left
58+
elif center_x - radius < 0:
59+
# start moving to the right
60+
x_inc = 1
61+
62+
# if bouncing off top
63+
if center_y + radius >= oled.height:
64+
# start moving down
65+
y_inc = -1
66+
# if bouncing off bottom
67+
elif center_y - radius < 0:
68+
# start moving up
69+
y_inc = 1
70+
71+
# go more in the current direction
72+
center_x += x_inc
73+
center_y += y_inc
74+
75+
# draw the new circle
76+
draw_circle(center_x, center_y, radius)
77+
# show all the changes we just made
78+
oled.show()

0 commit comments

Comments
 (0)