/ ufo / code.py
code.py
 1  # SPDX-FileCopyrightText: 2017 John Park for Adafruit Industries
 2  #
 3  # SPDX-License-Identifier: MIT
 4  
 5  """
 6  UFO Flying Saucer with Circuit Playground Express
 7  https://learn.adafruit.com/ufo-circuit-playground-express/
 8  Plays UFO lights and sounds if the board is upside down only,
 9  Tilt to change light color, cycle speed, tone pitch
10  """
11  
12  import time
13  
14  from adafruit_circuitplayground.express import cpx
15  
16  def simple_circle(wait, red, green, blue):
17      """timing, color values per channel"""
18      baseFreq = int(20 + (green * 0.3))  # tone value derived from rotation
19  
20      for i in range(10):
21          cpx.pixels[i] = ((0, 0, 0))
22          cpx.start_tone(baseFreq + i)  # increasing pitch sweep
23          time.sleep(wait)
24  
25      for i in range(10):
26          cpx.pixels[i] = ((red, green, blue))
27          time.sleep(wait)
28  
29  
30  # Main loop gets x, y and z axis acceleration, prints the values, and turns on
31  # lights if the UFO is upside down, plays tones
32  while True:
33      R = 0
34      G = 0
35      B = 0
36      x, y, z = cpx.acceleration  # read the accelerometer values
37  
38      R = 10 * (R + abs(int(x)))  # scale up the accel values into color values
39      G = 10 * (G + abs(int(y)))
40      B = 10 * (B + abs(int(z)))
41  
42      # check for upside down state on z axis
43      if z < 0:  # any negative number on z axis means it's upside down enough
44          speed = (0.01 * (B * 0.025))
45          simple_circle(speed, R, G, B)  # speed based on tilt, .01 is good start
46  
47      else:  # right side up means no colors or sound!
48          cpx.pixels.fill((0, 0, 0))
49          cpx.stop_tone()