/ CPX_Marble_Maze / code.py
code.py
 1  # SPDX-FileCopyrightText: 2019 Anne Barela for Adafruit Industries
 2  #
 3  # SPDX-License-Identifier: MIT
 4  
 5  # CircuitPython code for the Gyroscopic Marble Maze
 6  # Adafruit Industries, 2019. MIT License
 7  import time
 8  import board
 9  import pwmio
10  from adafruit_motor import servo
11  import simpleio
12  from adafruit_circuitplayground.express import cpx
13  
14  # create a PWMOut object on Pin A2.
15  pwm1 = pwmio.PWMOut(board.A1, duty_cycle=2 ** 15, frequency=50)
16  pwm2 = pwmio.PWMOut(board.A2, duty_cycle=2 ** 15, frequency=50)
17  
18  # Create a servo object, my_servo.
19  my_servo1 = servo.Servo(pwm1)
20  my_servo2 = servo.Servo(pwm2)
21  
22  NUM_READINGS = 8
23  roll_readings = [90] * NUM_READINGS
24  pitch_readings = [90] * NUM_READINGS
25  
26  def Average(lst):
27      return sum(lst) / len(lst)
28  
29  while True:
30      x, y, z = cpx.acceleration  # x = green
31      print((x, y, z))
32  
33      roll = simpleio.map_range(x, -9.8, 9.8, 0, 180)
34      roll_readings = roll_readings[1:]
35      roll_readings.append(roll)
36      roll = Average(roll_readings)
37  
38      print(roll)
39  
40      my_servo1.angle = roll
41  
42      pitch = simpleio.map_range(y, -9.8, 9.8, 0, 180)
43      pitch_readings = pitch_readings[1:]
44      pitch_readings.append(pitch)
45      pitch = Average(pitch_readings)
46  
47      print(pitch)
48  
49      my_servo2.angle = pitch
50  
51      time.sleep(0.05)