Skip to content

Commit 36e9f6d

Browse files
raidancampbelltannewt
authored andcommitted
add bouncing ball example (#6)
Added example with bouncing ball animation
1 parent d6e50f4 commit 36e9f6d

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

examples/bouncing_ball.py

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
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+
# This is an implementation of the midpoint circle algorithm,
16+
# see https://en.wikipedia.org/wiki/Midpoint_circle_algorithm#C_example for details
17+
def draw_circle(xpos0, ypos0, rad, col=1):
18+
x = rad - 1
19+
y = 0
20+
dx = 1
21+
dy = 1
22+
err = dx - (rad << 1)
23+
while x >= y:
24+
oled.pixel(xpos0 + x, ypos0 + y, col)
25+
oled.pixel(xpos0 + y, ypos0 + x, col)
26+
oled.pixel(xpos0 - y, ypos0 + x, col)
27+
oled.pixel(xpos0 - x, ypos0 + y, col)
28+
oled.pixel(xpos0 - x, ypos0 - y, col)
29+
oled.pixel(xpos0 - y, ypos0 - x, col)
30+
oled.pixel(xpos0 + y, ypos0 - x, col)
31+
oled.pixel(xpos0 + x, ypos0 - y, col)
32+
if err <= 0:
33+
y += 1
34+
err += dy
35+
dy += 2
36+
if err > 0:
37+
x -= 1
38+
dx += 2
39+
err += dx - (rad << 1)
40+
41+
# initial center of the circle
42+
center_x = 63
43+
center_y = 15
44+
# how fast does it move in each direction
45+
x_inc = 1
46+
y_inc = 1
47+
# what is the starting radius of the circle
48+
radius = 8
49+
50+
# start with a blank screen
51+
oled.fill(0)
52+
# we just blanked the framebuffer. to push the framebuffer onto the display, we call show()
53+
oled.show()
54+
while True:
55+
# undraw the previous circle
56+
draw_circle(center_x, center_y, radius, col=0)
57+
58+
# if bouncing off right
59+
if center_x + radius >= oled.width:
60+
# start moving to the left
61+
x_inc = -1
62+
# if bouncing off left
63+
elif center_x - radius < 0:
64+
# start moving to the right
65+
x_inc = 1
66+
67+
# if bouncing off top
68+
if center_y + radius >= oled.height:
69+
# start moving down
70+
y_inc = -1
71+
# if bouncing off bottom
72+
elif center_y - radius < 0:
73+
# start moving up
74+
y_inc = 1
75+
76+
# go more in the current direction
77+
center_x += x_inc
78+
center_y += y_inc
79+
80+
# draw the new circle
81+
draw_circle(center_x, center_y, radius)
82+
# show all the changes we just made
83+
oled.show()

0 commit comments

Comments
 (0)