/ Motion_Gift_Box / code.py
code.py
 1  # SPDX-FileCopyrightText: 2018 Anne Barela for Adafruit Industries
 2  #
 3  # SPDX-License-Identifier: MIT
 4  
 5  import time
 6  import random
 7  import audioio
 8  import audiocore
 9  import board
10  import neopixel
11  from adafruit_crickit import crickit
12  
13  # NeoPixels on the Circuit Playground Express
14  pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=0.3)
15  pixels.fill(0)                # Off to start
16  
17  # PIR sensor on signal #1
18  PIR_SENSOR = crickit.SIGNAL1
19  crickit.seesaw.pin_mode(PIR_SENSOR, crickit.seesaw.INPUT)
20  
21  # Set audio out on speaker
22  speaker = audioio.AudioOut(board.A0)
23  audio_files = ["evillaugh3.wav", "laugh.wav"]
24  
25  # One motor
26  motor_1 = crickit.dc_motor_1
27  motor_1.throttle = 0             # off to start
28  
29  while True:
30      pixels.fill(0)
31      print("Waiting for trigger")
32      while not crickit.seesaw.digital_read(PIR_SENSOR):
33          pass
34      print("PIR triggered")
35      pixels.fill((100, 0, 0))    # NeoPixels red
36  
37      # Start playing the file (in the background)
38      audio_file = open(random.choice(audio_files), "rb")   # muahaha
39      wav = audiocore.WaveFile(audio_file)
40      speaker.play(wav)
41  
42      # move motor back and forth for 3 seconds total
43      timestamp = time.monotonic()
44      while time.monotonic() - timestamp < 3:
45          motor_1.throttle = 1        # full speed forward
46          time.sleep(0.25 + random.random())  # random delay from 0.25 to 1.25 seconds
47          motor_1.throttle = -1        # full speed backward
48          time.sleep(0.25 + random.random())  # random delay from 0.25 to 1.25 seconds
49      motor_1.throttle = 0        # stop!
50  
51      # wait for audio to stop
52      while speaker.playing:
53          pass
54      # clean up and close file
55      audio_file.close()