/ Magic_Nine_Ball / code.py
code.py
1 # SPDX-FileCopyrightText: 2018 John Edgar Park for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 # Magic 9 Ball 6 # Turn HalloWing face down and then face up to change images at random 7 # place 128 x 128 pixel 24-bit .bmp images at root level of HalloWing 8 9 import time 10 import os 11 import random 12 import board 13 import displayio 14 import adafruit_lis3dh 15 16 splash = displayio.Group() 17 board.DISPLAY.show(splash) 18 19 SENSITIVITY = 5 # reading in Z direction to trigger, adjustable 20 21 images = list(filter(lambda x: x.endswith("bmp"), os.listdir("/"))) 22 23 i = random.randint(0, (len(images)-1)) # initial image is randomly selected 24 25 # Set up accelerometer on I2C bus, 4G range: 26 ACCEL = adafruit_lis3dh.LIS3DH_I2C(board.I2C(), address=0x18) 27 28 ACCEL.range = adafruit_lis3dh.RANGE_4_G 29 30 while True: 31 shaken = False 32 33 print("Image load {}".format(images[i])) 34 # CircuitPython 6 & 7 compatible 35 try: 36 f = open(images[i], "rb") 37 odb = displayio.OnDiskBitmap(f) 38 except ValueError: 39 print("Image unsupported {}".format(images[i])) 40 del images[i] 41 continue 42 face = displayio.TileGrid(odb, pixel_shader=getattr(odb, 'pixel_shader', displayio.ColorConverter())) 43 44 # # CircuitPython 7+ compatible 45 # try: 46 # odb = displayio.OnDiskBitmap(images[i]) 47 # except ValueError: 48 # print("Image unsupported {}".format(images[i])) 49 # del images[i] 50 # continue 51 # face = displayio.TileGrid(odb, pixel_shader=odb.pixel_shader) 52 53 splash.append(face) 54 # Wait for the image to load. 55 try: 56 board.DISPLAY.refresh(target_frames_per_second=60) 57 except AttributeError: 58 board.DISPLAY.wait_for_frame() 59 60 # Fade up the backlight 61 for b in range(101): 62 board.DISPLAY.brightness = b / 100 63 time.sleep(0.01) # default (0.01) 64 65 # Wait until the board gets shaken 66 while not shaken: 67 try: 68 ACCEL_Z = ACCEL.acceleration[2] # Read Z axis acceleration 69 except OSError: 70 pass 71 # print(ACCEL_Z) # uncomment to see the accelerometer z reading 72 if ACCEL_Z > SENSITIVITY: 73 shaken = True 74 75 # Fade down the backlight 76 for b in range(100, 0, -1): 77 board.DISPLAY.brightness = b 78 time.sleep(0.005) # default (0.005) 79 80 splash.pop() 81 82 i = random.randint(0, (len(images)-1)) # pick a new random image 83 # print("shaken") 84 faceup = False 85 i %= len(images) - 1