Skip to content

Instantly share code, notes, and snippets.

@abachman
Created November 7, 2018 01:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abachman/f191457b174c268ff9e2a15ac2e24204 to your computer and use it in GitHub Desktop.
Save abachman/f191457b174c268ff9e2a15ac2e24204 to your computer and use it in GitHub Desktop.
CircuitPython Trellis M4 pixel tilt drawing demo
# Tiny slow gravitational etch-a-sketch. Press a button to reset.
# using https://github.com/adafruit/Adafruit_CircuitPython_TrellisM4
# and https://www.adafruit.com/product/4020
import time
import board
import busio
import adafruit_adxl34x
import adafruit_trellism4
trellis = adafruit_trellism4.TrellisM4Express()
color = (0, 0, 0)
# Our accelerometer
i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA)
accelerometer = adafruit_adxl34x.ADXL345(i2c)
# map value from one range to another
def linmap(x, inx, iny, ox, oy):
return ((x - inx) * (oy - ox) + ox * (iny - inx)) / (iny - inx)
class Dot:
def __init__(self):
self.lx = 4
self.ly = 1
self.x = 4.0
self.y = 1.0
self.drawn = False
def update(self, tx, ty):
self.vx = 0
if abs(tx) > 2:
self.vx = -1 if tx > 0 else 1
self.vy = 0
if abs(ty) > 2:
self.vy = -1 if ty < 0 else 1
self.x = self.x + self.vx
self.y = self.y + self.vy
# don't fall outside the boundaries
if self.x < 0:
self.x = 0
if self.x > 7:
self.x = 7
if self.y < 0:
self.y = 0
if self.y > 3:
self.y = 3
def draw(self):
x = int(self.x)
y = int(self.y)
# only redraw if the dot has moved
if not self.drawn or self.lx != x or self.ly != y:
trellis.pixels[self.lx, self.ly] = (0, 0, 10)
trellis.pixels[x, y] = (100, 0, 0)
self.lx = x
self.ly = y
self.drawn = True
c = Dot()
last_accel = 0
accel_gap = 0.25 # time between updates
while True:
tx = accelerometer.acceleration[1]
ty = accelerometer.acceleration[0]
tick = time.monotonic()
if trellis.pressed_keys:
trellis.pixels.fill(0)
if tick > last_accel + accel_gap:
c.update(tx, ty)
c.draw()
print("%0.3f %0.1f %0.1f" % (tick, tx, ty))
last_accel = tick
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment