Back to: Multiplier Event Luxembourg
import math import time from adafruit_circuitplayground import cp # NeoPixel #9 is set to red to indicate no (good) reading. cp.pixels[9] = (255, 0, 0) # Loop forever while True: # If button A or B is pressed if cp.button_a or cp.button_b: # Initialise a_x, a_y, and a_z. a_x = 0 a_y = 0 a_z = 0 # Take 10 measurements for a_x, a_y, and a_z. for count in range(10): x, y, z = cp.acceleration a_x = a_x + x a_y = a_y + y a_z = a_z + z time.sleep(0.01) # Calculate the average of the 10 measurements. a_x = a_x / 10 a_y = a_y / 10 a_z = a_z / 10 # Assume the reading is good. reading = True # Check for levelness: # Ideally, a_z = 0 if the Circuit Playground is hold vertically. # However, a small amount of acceleration is permitted. if abs(a_z) > 1: reading = False # Compute acceleration using norm. acceleration = math.sqrt(a_x*a_x + a_y*a_y + a_z*a_z) # Check for motion: # Ideally, accelaration = 9.81 (gravity = 9.81 m/s^2). # However, a small amount of acceleration is permitted. if acceleration > 10: reading = False # NeoPixel #9 is set to indicate the quality of the reading. if reading: cp.pixels[9] = (0, 255, 0) # Green light for good reading. else: cp.pixels[9] = (255, 0, 0) # Red light for try again. continue # Compute tan(𝛼). # Use |a_x| to avoid trouble when flipping the board. tan_alpha = abs(a_x) / a_y # Compute 𝛼 (atan returns radians), convert it to degrees, # then take the absolute value, and finally convert it to an # integer. alpha = int(abs(math.degrees(math.atan(tan_alpha)))) # NeoPixel #8 is set to indicate the sign of the angle. if tan_alpha < 0: cp.pixels[8] = (0, 0, 255) # Blue light for negative. else: cp.pixels[8] = (255, 255, 255) # White light for positive. # Display angle magnitude on NeoPixels #0 to #7 as 8-bit value. for p in range(8): # Check if right bit (0x1 = 00000001) is set. if alpha & 0x1 == 1: cp.pixels[p] = (255, 255, 255) # Turn on the NeoPixel else: cp.pixels[p] = (0, 0, 0) # Turn off the NeoPixel # Shift 𝛼 right by 1 bit. # Dropping the right bit equals dividing the number by 2. alpha = alpha >> 1 # Depending on the switch, write to # * the serial console (if True, i.e. left), or to # * the CircuitPython storage (if False, i.e. right). if cp.switch: # Read d and e as float. d = float(input("What is the distance to the object in meters? ")) e = float(input("What is the eye level in meters? ")) # Substract e if tan_alpha is negative. e = math.copysign(e, tan_alpha) # Print the height of the object. print("The height of the object is", "{:.2f}".format(d * tan_alpha + e), "meters.\n") else: f = open("tan_alpha.csv", "a") f.write(repr(tan_alpha) + "\n") f.close()
import storage from adafruit_circuitplayground import cp storage.remount("/", readonly=cp.switch)