In this exercise, we are recreating an electronic musical instrument from the 1920s. We will play a musical note which changes based on how we move the microbit around in space. Wire a speaker or a pair of headphones between pin 0 and the GND pin on the edge of the microbit before running.
from microbit import *
import music
# where am i in space?
def calculate_movement():
scaling_factor = 20
x = accelerometer.get_x() / scaling_factor
y = accelerometer.get_y() / scaling_factor
z = accelerometer.get_z() / scaling_factor
movement = x + y + z
return int(movement)
frequency = 440 # concert 'A'
while True:
change = calculate_movement()
pitch = frequency + change
music.pitch(pitch)
sleep(100)