Activity

# Sound compass

Intermediate | MakeCode, Python | Buttons, Compass, LED display, Sound | Relational operators, Selection, Using a compass, Variables

## Step 1: Make it

### What is it?

Make a compass that makes a sound when you're pointing North to make it more accessible and useful.

### What you'll learn

• How to use compass readings from the micro:bit's magnetometer sensor
• How to use variables, selection, comparisons and logic to trigger events when sensor readings fall in a range of numbers

### How it works

• A loop keeps the micro:bit checking which direction you're facing in. It stores this in a variable called direction.
• If the direction is between 355 and 5 degrees, you are facing North so it shows an N on the LED display and makes a beeping sound.
• If you have a new micro:bit you can hear the sound on the built-in speaker, otherwise you can connect headphones to pin 0 and GND.
• If you're not facing North it clears the display and stops the sound.
• You can also press button A to see a compass reading on the LED display if you're not facing North.
• The first time you use a compass project on your micro:bit, you’ll probably be asked to play a little game. Tilt the screen to light every LED on the display. This calibrates the compass and makes sure it’s working correctly.

### What you need

• A micro:bit
• MakeCode or Python editor
• battery pack (optional)

## Step 2: Code it

1from microbit import *
2import music
3
4while True:
6    if direction < 5 or direction > 355:
7        display.show('N')
8        music.play("C4:1")
9    elif button_a.is_pressed():
10        display.scroll(direction)
11    else:
12        display.clear()
13        music.stop()
14

## Step 3: Improve it

• Play different notes depending on which way you're facing: South, East or West.
• Add another button press to calibrate the compass again if you think it's not accurate. In MakeCode you'll find the 'calibrate compass' block under Input... more. In Python use compass.calibrate()