microbit music

Questions and discussion about running MicroPython on a micro:bit board.
Target audience: MicroPython users with a micro:bit.
Post Reply
kvarneb
Posts: 2
Joined: Mon Mar 13, 2017 2:16 pm

microbit music

Post by kvarneb » Mon Mar 13, 2017 2:46 pm

Im trying to use this code in order to create sound by moving the microbit for a project but it wont seem to work...can anyone please help?

from micro bit import *
import music
on = False
initial = 1000
while True:
if button_a.is_pressed():
on = True
while on:
if accelerometer.get_y() >10:
initial +=100
music.pitch(initial,100)
elif accelerometer.get_y() <10:
initial -=100
music.pitch(initial,100)
else:
music.pitch(initial,100)

if initial >4000:
initial = 4000
if initial < 100:
initial = 100

if button_b.is_pressed():
on = False
sleep(100)

fizban
Posts: 24
Joined: Mon Oct 24, 2016 2:32 pm

Re: microbit music

Post by fizban » Mon Mar 27, 2017 8:43 pm

It works fine on my micro:bit. It is unfortunate that you cannot yet format the code in your post, but I guess it looks like this:

Code: Select all

from microbit import *
import music
on = False
initial = 1000
while True:
    if button_a.is_pressed():
        on = True
    while on:
        if accelerometer.get_y() > 10:
            initial += 100
            music.pitch(initial, 100)
        elif accelerometer.get_y() < 10:
            initial -= 100
            music.pitch(initial, 100)
        else:
            music.pitch(initial, 100)

        if initial > 4000:
            initial = 4000
        if initial < 100:
            initial = 100

        if button_b.is_pressed():
            on = False
        sleep(100)
Pressing button A starts the music. Button B stops it. You might have to connect a real speaker to hear some of the pitch values, since piezo buzzers have the bad habit of being silent at some frequencies...

loganMulvey
Posts: 1
Joined: Tue Dec 31, 2019 8:11 pm

Re: microbit music

Post by loganMulvey » Tue Dec 31, 2019 8:16 pm

I know this is years later, but I figured I'd just add this here in case someone found this thread by way of Google Search - as i myself did.

First off, it would be helpful to know what you mean by "doesn't work." I tried running this code and it didn't work because whenever it went as high as possible, the program bugged out and game me an invalid value error.

I don't know why, but the highest possible pitch available with my setup is 3906 - kind of a random number I know. So I changed the value 4000 on lines 18/19 to 3806 - and the program seems to work fine after that.

Cheers,

MicroBitEnthusiast

Post Reply