Page 1 of 1

Musical notes in Python

Posted: Mon Sep 24, 2018 7:08 pm
by toldcodger
I was recently playing around with micro python on a BBC microbit. Using some basic instructions I got it to show rows of LED’s and using the music library I got it to play the notes of the Close Encounters riff very simply by stating the note, octave and duration, i.e G4:4, A4:4 etc. I think that is similar to Sonic Pi

The coding may not be the prettiest thing you’ve ever seen, but it worked :)

I was going to try to do something similar using Python, a Blinkt stick or a Unicorn hat but I can’t find a way to create the notes using just Python on the Pi.

I’m not a programmer so I am expecting to be corrected on that last statement. But bearing in mind I am not a programmer, what’s the easiest way to do this. ?

Please try to keep it simple, I’m not as young as I used to be :)



Re: Musical notes in Python

Posted: Mon Sep 24, 2018 11:11 pm
by MrYsLab
I used the pigoio library "waves" (PWM) in conjunction with a piezo buzzer . Here is a snippet of code using pigpio waves to play a single tone. It was adapted from the s2-pi project, ... i/ lines 64-80

Code: Select all

import pigpio

pin = 18 # pin that buzzer is connected to

# frequency is in hz.
play_tone = 1000

# instantiate pigpio
pi = pigpio.pi()

# set pin to output mode
pi.set_mode(pin, pigpio.OUTPUT)

frequency = int((1000 / play_tone) * 1000)
tone = [pigpio.pulse(1 << pin, 0, frequency),
    pigpio.pulse(0, 1 << pin, frequency)]

wid = pi.wave_create()

if wid >= 0:


Re: Musical notes in Python

Posted: Tue Sep 25, 2018 12:58 am
by scruss
Something like asdwsda/rtttl will do the conversion from note & octave to frequency.

Re: Musical notes in Python

Posted: Tue Sep 25, 2018 6:42 pm
by toldcodger
Thanks guys,

On the micro bit I lit up a row of leds then played a note, then another row of leds and another note etc.

I think the rttl method may be the best fit.For this method.

If I get it working on the Pi i’ll Post it on here.

Thanks again


Re: Musical notes in Python

Posted: Fri Sep 28, 2018 7:12 pm
by toldcodger
I got it to work with the UnicornHat and SonicPi.

Unfortunately the movie won’t upload. It looks like I need to convert it to an avi file.

I was looking at SonicPi and saw the OSC option. You have to have SonicPi open and running an OSC listening script but it works.