Maker Advent Calendar Day #5: Hear my Code!

Maker Advent Calendar Day #5: Hear my Code!

Welcome to day five of your 12 Projects of Codemas Advent Calendar. Today we’ll be making sounds with our code using the custom buzzer you've just discovered in your box!

The buzzer is nice and easy to wire into our circuit, using just two pins with no other components required, yet can add SO much to a project! Adding audible feedback for errors, button presses and other actions gives your project a whole new dimension.

Let's make some noise!

Box #5 Contents

In this box you will find:

  • 1x Custom pre-wired buzzer with male jumper wire ends

Day 5 parts

Today’s Project

Today we'll be using our buzzer in a few different ways, first for simple beeps and tones, then combining with our potentiometer to control the volume, then finally something a little more advanced where we use different frequencies to generate festive tones!

This particular buzzer works with PWM signals to allow you to generate different tones, so we'll be tapping back into everything we learned about PWM in yesterday's box. It's almost like we planned this...

Construct the Circuit

Remember to unplug your Pico from your USB port before amending the circuit!

We'll be using the potentiometer from yesterday's box to control our buzzer in a few moments, so leave your circuit in place as it is. We just need to add our buzzer and we're good to go.

This is one of the easier components to work with as we've included a custom pre-wired buzzer with male jumper wire ends.

Simply push the red wire into GPIO 13 (physical pin 17) and the black wire into the GND pin next to it (physical pin 18). The Pico pin map is always on hand if you need to check it.

Pico buzzer

Activity 1: Let's buzz!

Our buzzer can generate different tones based on the PWM frequency and duty cycle we use in our code - this should sound familiar as we covered PWM yesterday.

PWM Frequency and Duty Cycle with Buzzers

The frequency here changes the tone of the buzzer - we find that our ears can detect changes in the tone when using values between 10 and 10000.

The Duty Cycle sets the volume of the buzzer. The range is technically 0 to 65535 in MicroPython, however we find that values below 5000 are very difficult for our ears to hear. A duty of 10000 appears to be the sweet spot for our buzzer.

If you want to silence the buzzer in your code, just set the duty to 0 - easy!

The Code

Now we know what the PWM values do here, let's try a quick example where we sound the buzzer for a few seconds.

The example below includes the same ingredients you're now becoming familiar with - imports, pin setup (with PWM), PWM duty cycle and frequency - so there's nothing new or scary here, and our usual slightly-excessive code commentary tells you what each line is doing!

We set up the pin for the buzzer, then assign a frequency (1000) and finally set the PWM duty (volume) to 10000 to for a second, and then back down to 0 to mute it. Nice and easy!

Copy the example over to Thonny and give it a go:

# Imports
from machine import Pin, PWM
import time

# Set up the Buzzer pin as PWM
buzzer = PWM(Pin(13)) # Set the buzzer to PWM mode

# Set PWM frequency to 1000
buzzer.freq(1000)

# Set PWM duty
buzzer.duty_u16(10000)

time.sleep(1) # Wait 1 second

# Duty to 0 to turn the buzzer off
buzzer.duty_u16(0)

Now try changing that frequency number to 300 and see what happens. Did the tone go lower? You can try higher values too, but eventually you’ll go too high (around 10000) and it won’t work/your human ears won’t hear it.

Activity 2: Changing tones

Here's another simple example just to show you how easy it is to change the tone on your buzzer from one to another.

Here we start with a frequency of 1000 for one second and then drop it down to 500 for one second.

Give it a try and hear it for yourself:

# Imports
from machine import Pin, PWM
import time

# Set up the Buzzer pin as PWM
buzzer = PWM(Pin(13)) # Set the buzzer to PWM mode

# Set PWM duty
buzzer.duty_u16(10000)

# Set PWM frequency to 1000 for one second
buzzer.freq(1000)
time.sleep(1)

# Set PWM frequency to 500 for one second
buzzer.freq(500)
time.sleep(1)

# Buzzer off
buzzer.duty_u16(0)

Activity 3: Potentiometer Volume Control

Let’s use one of the previous components to control the volume of the buzzer. This one's a bit noisy and not perfect (the sound can distort or cut out at high levels) but it's a fun project to try out! If you find the buzzer a bit loud or harsh, you can always place some sticky tape or a blob of Blu-tack over the hole to calm it down.

The readings from the potentiometer are between 0 and 65535, and our buzzer duty (volume) uses the same range, so we can use the potentiometer readings to directly control the duty - handy!

In the example below, in each while loop we take a reading from the potentiometer and store it in a variable called 'reading' (just like we did yesterday in activity 3) and then we use this variable as the buzzer duty value (instead of adding a number there ourselves).

A little warning - this example will never turn the buzzer off even if you stop the program as it's just a quick, basic example for us to get familiar with buzzer control. You can unplug the USB cable to stop the noise or just move on to the next activity.

# Imports
from machine import Pin, PWM, ADC
import time

# Set up the Buzzer and Potentiometer
potentiometer = ADC(Pin(27))
buzzer = PWM(Pin(13)) # Set the buzzer to PWM mode

reading = 0 # Create a variable called 'reading' and set it to 0

while True: # Run forever
    
    time.sleep(0.01) # Delay
    
    reading = potentiometer.read_u16() # Read the potentiometer value and store it in our 'reading' variable
    
    buzzer.freq(500) # Frequency to 500
    buzzer.duty_u16(reading) # Use the reading variable as the duty
    
    print(reading) # Print our reading variable

Activity 4: Festive Jingle!

How about a little festive tune with our buzzer? By changing the frequency between each pause we can create a tune that resembles a popular festive jingle!

A nice way of doing this is to define each musical note frequency as a variable using the note name, which will make our code easier to write, read and review. We've covered variables before so this should be familiar. We've also used a variable for the volume (duty cycle) as, again, it makes our code a little more human. Don't worry, we've included the tone values for the jingle below for you.

The example below is purposely inefficient and uses a LOT of lines, mostly because each section of the jingle includes lines to turn the volume on then off as well as delays. Try this first, then we'll move on to a nicer way of doing things in the next activity.

We've included commentary on the first jingle block of code to show you what we're doing here.

Tip: This is a simple buzzer, so it doesn't quite have the smooth sound that a normal speaker will create. The buzzer can sound a little more 'Nightmare Before Christmas' than 'Elf'!

# Imports
from machine import Pin, PWM
import time

# Set up the Buzzer pin as PWM
buzzer = PWM(Pin(13)) # Set the buzzer to PWM mode

# Create our library of tone variables for "Jingle Bells"
C = 523
D = 587
E = 659
G = 784

# Create volume variable (Duty cycle)
volume = 10000

# Play the tune

# "Jin..."
buzzer.duty_u16(volume) # Volume up
buzzer.freq(E) # Set frequency to the E note
time.sleep(0.1) # Delay
buzzer.duty_u16(0) # Volume off
time.sleep(0.2) # Delay

# "...gle"
buzzer.duty_u16(volume)
buzzer.freq(E)
time.sleep(0.1)
buzzer.duty_u16(0)
time.sleep(0.2)

# "Bells"
buzzer.duty_u16(volume)
buzzer.freq(E)
time.sleep(0.1)
buzzer.duty_u16(0)
time.sleep(0.5) # longer delay

# "Jin..."
buzzer.duty_u16(volume)
buzzer.freq(E)
time.sleep(0.1)
buzzer.duty_u16(0)
time.sleep(0.2)

# "...gle"
buzzer.duty_u16(volume)
buzzer.freq(E)
time.sleep(0.1)
buzzer.duty_u16(0)
time.sleep(0.2)

# "Bells"
buzzer.duty_u16(volume)
buzzer.freq(E)
time.sleep(0.1)
buzzer.duty_u16(0)
time.sleep(0.5) # longer delay

# "Jin..."
buzzer.duty_u16(volume)
buzzer.freq(E)
time.sleep(0.1)
buzzer.duty_u16(0)
time.sleep(0.2)

# "...gle"
buzzer.duty_u16(volume)
buzzer.freq(G)
time.sleep(0.1)
buzzer.duty_u16(0)
time.sleep(0.2)

# "All"
buzzer.duty_u16(volume)
buzzer.freq(C)
time.sleep(0.1)
buzzer.duty_u16(0)
time.sleep(0.2)

# "The"
buzzer.duty_u16(volume)
buzzer.freq(D)
time.sleep(0.1)
buzzer.duty_u16(0)
time.sleep(0.2)

# "Way"
buzzer.duty_u16(volume)
buzzer.freq(E)
time.sleep(0.1)
buzzer.duty_u16(0)
time.sleep(0.2)

# Duty to 0 to turn the buzzer off
buzzer.duty_u16(0)

Activity 5: Festive Jingle using Functions

Let's improve the very long code above by introducing something new - functions!

Functions

Functions are blocks of code that you can create and then call (use) at any time in your program. They're great for repetitive blocks of code as it keeps your program short and efficient (which can be important if your microcontroller has limited storage).

Let's explain how functions work before we move on...

Writing a function

Below is an example of a simple function that prints 3 lines. We create a function by writing 'def' followed by a space and then the name we want to give our function (no spaces in the function name) .

We've called ours 'myfunction'. You then add brackets (parentheses) at the end which can include any arguments if required (we're not using any in this example but we cover them in a moment) followed by a colon (:).

Indentation is important again here - everything under the 'def' line must be indented to indicate that it's part of the function:

def myfunction():
    print("This")
    print("is a")
    print("function")

Using Functions

So now that we have a function, how do we use it, and why is it better than just writing the code?

We can call (use) the function by simply using the function name followed by the brackets, like this:

myfunction()

So why is this better? Let's look at two examples below where we want to print a set of strings three times. Both of the following examples have the exact same outcome (try them yourself) however the code using functions is shorter.

It might not look like much in this example, however in large projects this can save a LOT of lines in your code. It also makes it a lot easier to update your code as you only have to amend the one function - not every part of your program.

Example without a function

print("This")
print("is a")
print("function")

print("This")
print("is a")
print("function")

print("This")
print("is a")
print("function")

Example with a function

def myfunction():
    print("This")
    print("is a")
    print("function")
    
myfunction()
myfunction()
myfunction()

Function Arguments

We mentioned arguments earlier so let's talk about them quickly before we get into our jingle example.

Arguments are optional in functions. They allow you to pass information into your function, if needed. We pass the information to the function when we call it - that might be a bit confusing so let's jump to an example so you can see it working.

In the example below our function prints three lines again, but this time we include arguments asking for the first name, middle name and surname - as we might want to change the names each time we call this function. Those arguments are used in the print lines as you can see below:

def myfunction(first,middle,last):
    print(first)
    print(middle)
    print(last)

Now, to call the function AND pass the names on to it, we add the names in the same places inside the brackets (making sure we enter them inside inverted commas as we're dealing with strings here):

myfunction("Joe","David","Bloggs")

Try this yourself, then try adding a fourth argument and printing a fourth line to go with it.

The Code

Now we know how functions work, let's apply them to our jingle example to see if we can reduce the length of the code.

The example below uses a function called playtone to handle all of the volume changes, delays and notes. All you have to do is add the arguments for each.

Our arguments are:

  • note - the note to use
  • vol - the volume
  • delay1 - the first time.sleep period
  • delay2 - the second time.sleep period

The code is roughly half the number of lines and does the same thing - much better!

# Imports
from machine import Pin, PWM
import time

# Set up the Buzzer pin as PWM
buzzer = PWM(Pin(13)) # Set the buzzer to PWM mode

# Create our library of tone variables for "Jingle Bells"
C = 523
D = 587
E = 659
G = 784

# Create volume variable (Duty cycle)
volume = 32768

# Create our function with arguments
def playtone(note,vol,delay1,delay2):
    buzzer.duty_u16(vol)
    buzzer.freq(note)
    time.sleep(delay1)
    buzzer.duty_u16(0)
    time.sleep(delay2)
    
# Play the tune
playtone(E,volume,0.1,0.2)
playtone(E,volume,0.1,0.2)
playtone(E,volume,0.1,0.5) #Longer second delay

playtone(E,volume,0.1,0.2)
playtone(E,volume,0.1,0.2)
playtone(E,volume,0.1,0.5) #Longer second delay

playtone(E,volume,0.1,0.2)
playtone(G,volume,0.1,0.2)
playtone(C,volume,0.1,0.2)
playtone(D,volume,0.1,0.2)
playtone(E,volume,0.1,0.2)

# Duty to 0 to turn the buzzer off
buzzer.duty_u16(0)

Bonus - More notes!

Chris E kindly added a comment below providing a nice full list of notes (including sharps). Look up your favourite songs, use these notes and get creative. Thanks Chris!

  • A = 440
  • As = 466
  • B = 494
  • C = 523
  • Cs = 554
  • D = 587
  • Ds = 622
  • E = 659
  • F = 698
  • Fs = 740
  • G = 784
  • Gs = 830

Day #5 Complete!

We've covered lots today fellow makers, pat yourselves on the back!

As we cover more advanced topics such as functions, you may find that you need to refer back to these days to refresh your memory later on - and that's absolutely normal! Even the most seasoned professional programmers have to use search engines regularly (some even admit it!).

So what did we cover on day #5? Today you have:

  • Built a circuit with a buzzer, your first audio component
  • Learnt how to use the buzzer with MicroPython and the Pico
  • Learnt about PWM frequencies and duty cycle with buzzers
  • Used analogue inputs to control audio volume using PWM
  • Created a festive jingle with MicroPython
  • Learnt how to use functions to make your code easier to manage and more efficient

Keep your circuit safe somewhere until tomorrow (don't take anything apart just yet).


We used Fritzing to create the breadboard wiring diagram images for this page.

32 comments

LMD

LMD

Hello PiHut! If somebody — that person being me! — wanted to add another buzzer (or two) to make polyphonic tunes, which buzzer component would they need to purchase to match the one that came with the calendar (preferably breadboard ready)?

Hello PiHut! If somebody — that person being me! — wanted to add another buzzer (or two) to make polyphonic tunes, which buzzer component would they need to purchase to match the one that came with the calendar (preferably breadboard ready)?

The Pi Hut

The Pi Hut

@Darya – Oh no :( sorry about that. Please get in touch via support.thepihut.com and we’ll get the right packs out to you ASAP.

@Darya – Oh no :( sorry about that. Please get in touch via support.thepihut.com and we’ll get the right packs out to you ASAP.

Darya

Darya

Unfortunately, my advent calendar contains Day 8 in Day 5 and a second Day 8 in Day 8

Unfortunately, my advent calendar contains Day 8 in Day 5 and a second Day 8 in Day 8

Igor

Igor

We tried to implement the song that my son learned at school. Note timing and tone are tough for a person without any kind of understanding of the music, so it sounds weird, but it is what it is :)

Also, I tried to combine melody with blinking lights. The whole gist is here: https://gist.github.com/v1r7u/d67c77b84a440cb130a210ab8effdcfe; maybe you will get some ideas on what can be done.

We tried to implement the song that my son learned at school. Note timing and tone are tough for a person without any kind of understanding of the music, so it sounds weird, but it is what it is :)

Also, I tried to combine melody with blinking lights. The whole gist is here: https://gist.github.com/v1r7u/d67c77b84a440cb130a210ab8effdcfe; maybe you will get some ideas on what can be done.

Marcus Burke

Marcus Burke

Getting the note timing was a bit difficult for me. I converted note length to use semi-standard values (16 = 16th notes, 8 = 8th notes, etc. ) 12 is a dotted 8th, you get the idea.

A demo in the form of a Rick Roll (by request):
-———————————————————————————
import time
from machine import Pin, PWM

############################

global variables #
############################ Set the buzzer to PWM mode
buzzer = PWM) Set the buzzer to PWM mode
notes = [[“rest”,100],[“A0”,220],[“C1”,261],[“C#1”,277],[“D1”,294],[“D#1”,211],[“E1”,329],[“F1”,349],[“F#1”,370],[“G1”,391],[“G#1”,415],[“A1”,440],[“A#1”,466],[“B1”,494],[“C2”,523],[“C#2”,554],[“D2”,587],[“D#2”,622],[“E2”,659],[“F2”,698],[“F#2”,740],[“G2”,784],[“G#2”,830],[“A2”,880],[“A#2”,932]] give your song a tempo
tempo = 114

############################

main code #
############################ Create our play tone function with arguments length defaults to a quarter note, volume defaults to 8000
def playtone(pitch, length=4, vol=8000,):
freq = 440
for i in notes:
if i0 == pitch:
freq = i1
continue
print("pitch: " + pitch + " | freq: " + str(freq) + " | vol: " + str(vol) + " | note length: " + str(length))
buzzer.freq(freq)
buzzer.duty_u16(vol)
time.sleep((60/tempo)(1/length)3.5)

playtone(“C1”,16)
playtone(“D1”,16)
playtone(“F1”,16)
playtone(“D1”,16)
playtone(“A1”,8)
playtone(“rest”,16,0)
playtone(“A1”,8)
playtone(“rest”,16,0)
playtone(“G1”,8)
playtone(“rest”,4,0)

playtone(“C1”,16)
playtone(“D1”,16)
playtone(“F1”,16)
playtone(“D1”,16)
playtone(“G1”,8)
playtone(“rest”,16,0)
playtone(“G1”,8)
playtone(“rest”,16,0)
playtone(“F1”,8)
playtone(“rest”,4,0)

playtone(“C1”,16)
playtone(“D1”,16)
playtone(“F1”,16)
playtone(“D1”,16)
playtone(“F1”,4)
playtone(“G1”,8)
playtone(“E1”,12)
playtone(“D1”,16)
playtone(“C1”,8)
playtone(“rest”,8,0)
playtone(“C1”,8)
playtone(“G1”,4)
playtone(“F1”,4)
playtone(“rest”,2,0)

playtone(“C1”,16)
playtone(“D1”,16)
playtone(“F1”,16)
playtone(“D1”,16)
playtone(“A1”,8)
playtone(“rest”,16,0)
playtone(“A1”,8)
playtone(“rest”,16,0)
playtone(“G1”,8)
playtone(“rest”,4,0)

playtone(“C1”,16)
playtone(“D1”,16)
playtone(“F1”,16)
playtone(“D1”,16)
playtone(“C2”,8)
playtone(“rest”,16,0)
playtone(“E1”,8)
playtone(“rest”,16,0)
playtone(“F1”,8)
playtone(“rest”,4,0)

playtone(“C1”,16)
playtone(“D1”,16)
playtone(“F1”,16)
playtone(“D1”,16)
playtone(“F1”,4)
playtone(“G1”,8)
playtone(“E1”,12)
playtone(“D1”,16)
playtone(“C1”,8)
playtone(“rest”,8,0)
playtone(“C1”,8)
playtone(“G1”,4)
playtone(“F1”,4)

buzzer.duty_u16(0)

Getting the note timing was a bit difficult for me. I converted note length to use semi-standard values (16 = 16th notes, 8 = 8th notes, etc. ) 12 is a dotted 8th, you get the idea.

A demo in the form of a Rick Roll (by request):
-———————————————————————————
import time
from machine import Pin, PWM

############################

global variables #
############################ Set the buzzer to PWM mode
buzzer = PWM) Set the buzzer to PWM mode
notes = [[“rest”,100],[“A0”,220],[“C1”,261],[“C#1”,277],[“D1”,294],[“D#1”,211],[“E1”,329],[“F1”,349],[“F#1”,370],[“G1”,391],[“G#1”,415],[“A1”,440],[“A#1”,466],[“B1”,494],[“C2”,523],[“C#2”,554],[“D2”,587],[“D#2”,622],[“E2”,659],[“F2”,698],[“F#2”,740],[“G2”,784],[“G#2”,830],[“A2”,880],[“A#2”,932]] give your song a tempo
tempo = 114

############################

main code #
############################ Create our play tone function with arguments length defaults to a quarter note, volume defaults to 8000
def playtone(pitch, length=4, vol=8000,):
freq = 440
for i in notes:
if i0 == pitch:
freq = i1
continue
print("pitch: " + pitch + " | freq: " + str(freq) + " | vol: " + str(vol) + " | note length: " + str(length))
buzzer.freq(freq)
buzzer.duty_u16(vol)
time.sleep((60/tempo)(1/length)3.5)

playtone(“C1”,16)
playtone(“D1”,16)
playtone(“F1”,16)
playtone(“D1”,16)
playtone(“A1”,8)
playtone(“rest”,16,0)
playtone(“A1”,8)
playtone(“rest”,16,0)
playtone(“G1”,8)
playtone(“rest”,4,0)

playtone(“C1”,16)
playtone(“D1”,16)
playtone(“F1”,16)
playtone(“D1”,16)
playtone(“G1”,8)
playtone(“rest”,16,0)
playtone(“G1”,8)
playtone(“rest”,16,0)
playtone(“F1”,8)
playtone(“rest”,4,0)

playtone(“C1”,16)
playtone(“D1”,16)
playtone(“F1”,16)
playtone(“D1”,16)
playtone(“F1”,4)
playtone(“G1”,8)
playtone(“E1”,12)
playtone(“D1”,16)
playtone(“C1”,8)
playtone(“rest”,8,0)
playtone(“C1”,8)
playtone(“G1”,4)
playtone(“F1”,4)
playtone(“rest”,2,0)

playtone(“C1”,16)
playtone(“D1”,16)
playtone(“F1”,16)
playtone(“D1”,16)
playtone(“A1”,8)
playtone(“rest”,16,0)
playtone(“A1”,8)
playtone(“rest”,16,0)
playtone(“G1”,8)
playtone(“rest”,4,0)

playtone(“C1”,16)
playtone(“D1”,16)
playtone(“F1”,16)
playtone(“D1”,16)
playtone(“C2”,8)
playtone(“rest”,16,0)
playtone(“E1”,8)
playtone(“rest”,16,0)
playtone(“F1”,8)
playtone(“rest”,4,0)

playtone(“C1”,16)
playtone(“D1”,16)
playtone(“F1”,16)
playtone(“D1”,16)
playtone(“F1”,4)
playtone(“G1”,8)
playtone(“E1”,12)
playtone(“D1”,16)
playtone(“C1”,8)
playtone(“rest”,8,0)
playtone(“C1”,8)
playtone(“G1”,4)
playtone(“F1”,4)

buzzer.duty_u16(0)

The Pi Hut

The Pi Hut

@Martin – Our blog comment system (powered by Shopify) isn’t the most powerful and lacks a lot of nice features. It’s something we want to look at improving/replacing. For now, we’d recommend using something like PasteBin to share code examples: https://pastebin.com/

@Martin – Our blog comment system (powered by Shopify) isn’t the most powerful and lacks a lot of nice features. It’s something we want to look at improving/replacing. For now, we’d recommend using something like PasteBin to share code examples: https://pastebin.com/

Martin

Martin

@bob shock. I think The comments tool may have sripped some code out. Some comment # marks were missing and the [] around the note array refs and some important whitespace chars were missing.

Hopefully this post doesn’t strip out from your code, nice work btw. All credit to Bob for this:

#Imports
from machine import Pin, PWM
import time

#Set up the Buzzer pin as PWM
buzzer = PWM) # Set the buzzer to PWM mode Create our library of tone variables for “Jingle Bells”

C = 523
D = 587
E = 659
F = 698
G = 784

#Create volume variable (Duty cycle)
volume = 10000
notes = [[E,0.2],[E,0.2],[E,0.5],[E,0.2],[E,0.2],[E,0.5],[E,0.2],[G,0.2],[C,0.2],[D,0.2],[E,0.4],
[F,0.2],[F,0.2],[F,0.2],[F,0.2],[F,0.2],[E,0.2],[E,0.2],[E,0.2],[E,0.2],[D,0.2],[D,0.2],
[E,0.2],[D,0.4],[G,0.4]]

for note in notes:
buzzer.duty_u16(volume)
buzzer.freq(note0)
time.sleep(note1)
buzzer.duty_u16(0)
time.sleep(0.1)

#Duty to 0 to turn the buzzer off
buzzer.duty_u16(0)

Note to Mods, if this is stripping out syntax, how do we stop that. We can’t preview posts.

@bob shock. I think The comments tool may have sripped some code out. Some comment # marks were missing and the [] around the note array refs and some important whitespace chars were missing.

Hopefully this post doesn’t strip out from your code, nice work btw. All credit to Bob for this:

#Imports
from machine import Pin, PWM
import time

#Set up the Buzzer pin as PWM
buzzer = PWM) # Set the buzzer to PWM mode Create our library of tone variables for “Jingle Bells”

C = 523
D = 587
E = 659
F = 698
G = 784

#Create volume variable (Duty cycle)
volume = 10000
notes = [[E,0.2],[E,0.2],[E,0.5],[E,0.2],[E,0.2],[E,0.5],[E,0.2],[G,0.2],[C,0.2],[D,0.2],[E,0.4],
[F,0.2],[F,0.2],[F,0.2],[F,0.2],[F,0.2],[E,0.2],[E,0.2],[E,0.2],[E,0.2],[D,0.2],[D,0.2],
[E,0.2],[D,0.4],[G,0.4]]

for note in notes:
buzzer.duty_u16(volume)
buzzer.freq(note0)
time.sleep(note1)
buzzer.duty_u16(0)
time.sleep(0.1)

#Duty to 0 to turn the buzzer off
buzzer.duty_u16(0)

Note to Mods, if this is stripping out syntax, how do we stop that. We can’t preview posts.

Bob Shock

Bob Shock

Added a loop to make the code more compact.

Imports
from machine import Pin, PWM
import time Set up the Buzzer pin as PWM
buzzer = PWM) # Set the buzzer to PWM mode Create our library of tone variables for “Jingle Bells”
C = 523
D = 587
E = 659
F = 698
G = 784 Create volume variable (Duty cycle)
volume = 10000

notes = [[E,0.2],[E,0.2],[E,0.5],[E,0.2],[E,0.2],[E,0.5],[E,0.2],[G,0.2],[C,0.2],[D,0.2],[E,0.4],
[F,0.2],[F,0.2],[F,0.2],[F,0.2],[F,0.2],[E,0.2],[E,0.2],[E,0.2],[E,0.2],[D,0.2],[D,0.2],
[E,0.2],[D,0.4],[G,0.4]]

for note in notes:
buzzer.duty_u16(volume)
buzzer.freq(note0)
time.sleep(note1)
buzzer.duty_u16(0)
time.sleep(0.1)

Duty to 0 to turn the buzzer off
buzzer.duty_u16(0)

Added a loop to make the code more compact.

Imports
from machine import Pin, PWM
import time Set up the Buzzer pin as PWM
buzzer = PWM) # Set the buzzer to PWM mode Create our library of tone variables for “Jingle Bells”
C = 523
D = 587
E = 659
F = 698
G = 784 Create volume variable (Duty cycle)
volume = 10000

notes = [[E,0.2],[E,0.2],[E,0.5],[E,0.2],[E,0.2],[E,0.5],[E,0.2],[G,0.2],[C,0.2],[D,0.2],[E,0.4],
[F,0.2],[F,0.2],[F,0.2],[F,0.2],[F,0.2],[E,0.2],[E,0.2],[E,0.2],[E,0.2],[D,0.2],[D,0.2],
[E,0.2],[D,0.4],[G,0.4]]

for note in notes:
buzzer.duty_u16(volume)
buzzer.freq(note0)
time.sleep(note1)
buzzer.duty_u16(0)
time.sleep(0.1)

Duty to 0 to turn the buzzer off
buzzer.duty_u16(0)
Ian F

Ian F

Here’s my attempt at the opening 2 lines of Last Christmas..

Imports
from machine import Pin, PWM
import time Set up the Buzzer pin as PWM
buzzer = PWM) # Set the buzzer to PWM mode Create our library of tone variables for “Jingle Bells”
A = 440
As = 466
B = 494
C = 523
Cs = 554
D = 587
Ds = 622
E = 659
F = 698
Fs = 740
G = 784
Gs = 830 Create volume variable (Duty cycle)
volume = 32768 Create our function with arguments
def playtone(note,vol,delay1,delay2):
buzzer.duty_u16(vol)
buzzer.freq(note)
time.sleep(delay1)
buzzer.duty_u16(0)
time.sleep(delay2) Play the tune
playtone(G,volume,0.1,0.5)
playtone(G,volume,0.1,0.1)
playtone(F,volume,0.1,0.2)
playtone(C,volume,0.1,0.2)
playtone(G,volume,0.1,0.2)
playtone(G,volume,0.1,0.2)
playtone(A,volume,0.1,0.2)
playtone(F,volume,0.1,0.2)

playtone(D,volume,0.1,0.4)
playtone(D,volume,0.1,0.2)
playtone(G,volume,0.1,0.1)
playtone(G,volume,0.1,0.2)
playtone(A,volume,0.1,0.2)
playtone(F,volume,0.1,0.2)
playtone(D,volume,0.1,0.2)
playtone(E,volume,0.1,0.2)
playtone(F,volume,0.1,0.2)
playtone(E,volume,0.1,0.1)
playtone(D,volume,0.1,0.2)

Duty to 0 to turn the buzzer off
buzzer.duty_u16(0)

Here’s my attempt at the opening 2 lines of Last Christmas..

Imports
from machine import Pin, PWM
import time Set up the Buzzer pin as PWM
buzzer = PWM) # Set the buzzer to PWM mode Create our library of tone variables for “Jingle Bells”
A = 440
As = 466
B = 494
C = 523
Cs = 554
D = 587
Ds = 622
E = 659
F = 698
Fs = 740
G = 784
Gs = 830 Create volume variable (Duty cycle)
volume = 32768 Create our function with arguments
def playtone(note,vol,delay1,delay2):
buzzer.duty_u16(vol)
buzzer.freq(note)
time.sleep(delay1)
buzzer.duty_u16(0)
time.sleep(delay2) Play the tune
playtone(G,volume,0.1,0.5)
playtone(G,volume,0.1,0.1)
playtone(F,volume,0.1,0.2)
playtone(C,volume,0.1,0.2)
playtone(G,volume,0.1,0.2)
playtone(G,volume,0.1,0.2)
playtone(A,volume,0.1,0.2)
playtone(F,volume,0.1,0.2)

playtone(D,volume,0.1,0.4)
playtone(D,volume,0.1,0.2)
playtone(G,volume,0.1,0.1)
playtone(G,volume,0.1,0.2)
playtone(A,volume,0.1,0.2)
playtone(F,volume,0.1,0.2)
playtone(D,volume,0.1,0.2)
playtone(E,volume,0.1,0.2)
playtone(F,volume,0.1,0.2)
playtone(E,volume,0.1,0.1)
playtone(D,volume,0.1,0.2)

Duty to 0 to turn the buzzer off
buzzer.duty_u16(0)
The Pi Hut

The Pi Hut

@Patrick – Really sorry about that, looks like a packing error at the factory. Please get in touch via support.thepihut.com and we’ll get the right parts sent out to you.

@Patrick – Really sorry about that, looks like a packing error at the factory. Please get in touch via support.thepihut.com and we’ll get the right parts sent out to you.

Patrick

Patrick

Turns out my Day 5 box has Day 8 contents (as does my Day 8 box). Can you please send me a replacement for Day 5 ASAP? I really want to do this in order.

Turns out my Day 5 box has Day 8 contents (as does my Day 8 box). Can you please send me a replacement for Day 5 ASAP? I really want to do this in order.

Patrick

Patrick

The contents of my Day 5 box look nothing like this. I have a resistor, 3 male-to-male jumper cables, and something which might be a sensor of some kind (I’m new to this stuff) with 3 wires. I’m looking through later boxes (I’d really wanted to enjoy the surprise) to see if the speaker is in there and found something very similar to the ‘sensor’ (if that’s what it is) in Day 8. No buzzer to be found anywhere. So now what?

The contents of my Day 5 box look nothing like this. I have a resistor, 3 male-to-male jumper cables, and something which might be a sensor of some kind (I’m new to this stuff) with 3 wires. I’m looking through later boxes (I’d really wanted to enjoy the surprise) to see if the speaker is in there and found something very similar to the ‘sensor’ (if that’s what it is) in Day 8. No buzzer to be found anywhere. So now what?

Philip

Philip

How about combining days 3, 4, and 5 and create a mini piano:

```
from machine import ADC, Pin, PWM

button1 = Pin(12, Pin.IN, Pin.PULL_DOWN)
button2 = Pin(8, Pin.IN, Pin.PULL_DOWN)
button3 = Pin(3, Pin.IN, Pin.PULL_DOWN)
buzzer = PWM)
red = Pin(18, Pin.OUT)
amber = Pin(19, Pin.OUT)
green = Pin(20, Pin.OUT)
potentiometer = ADC (Pin(27))

#Notes:
A = 440
B = 494
C = 523
D = 587
E = 659
F = 740
G = 784

def playNote(note):
buzzer.duty_u16(potentiometer.read_u16())
buzzer.freq(note)

while True:
if(button1.value() == 1 and button2.value() == 1 and button3.value() == 1):
red.on()
amber.on()
green.on()
playNote(A)
elif(button1.value() == 1 and button2.value() == 1):
red.on()
amber.on()
playNote(B)
elif(button1.value() == 1 and button3.value() == 1):
red.on()
green.on()
playNote©
elif(button2.value() == 1 and button3.value() == 1):
amber.on()
green.on()
playNote(D)
elif(button1.value() == 1):
red.on()
playNote(E)
elif(button2.value() == 1):
amber.on()
playNote(F)
elif(button3.value() == 1):
green.on()
playNote(G)
else :
red.off()
amber.off()
green.off()
buzzer.duty_u16(0)
```

How about combining days 3, 4, and 5 and create a mini piano:

```
from machine import ADC, Pin, PWM

button1 = Pin(12, Pin.IN, Pin.PULL_DOWN)
button2 = Pin(8, Pin.IN, Pin.PULL_DOWN)
button3 = Pin(3, Pin.IN, Pin.PULL_DOWN)
buzzer = PWM)
red = Pin(18, Pin.OUT)
amber = Pin(19, Pin.OUT)
green = Pin(20, Pin.OUT)
potentiometer = ADC (Pin(27))

#Notes:
A = 440
B = 494
C = 523
D = 587
E = 659
F = 740
G = 784

def playNote(note):
buzzer.duty_u16(potentiometer.read_u16())
buzzer.freq(note)

while True:
if(button1.value() == 1 and button2.value() == 1 and button3.value() == 1):
red.on()
amber.on()
green.on()
playNote(A)
elif(button1.value() == 1 and button2.value() == 1):
red.on()
amber.on()
playNote(B)
elif(button1.value() == 1 and button3.value() == 1):
red.on()
green.on()
playNote©
elif(button2.value() == 1 and button3.value() == 1):
amber.on()
green.on()
playNote(D)
elif(button1.value() == 1):
red.on()
playNote(E)
elif(button2.value() == 1):
amber.on()
playNote(F)
elif(button3.value() == 1):
green.on()
playNote(G)
else :
red.off()
amber.off()
green.off()
buzzer.duty_u16(0)
```

Martin Packer

Martin Packer

It was also at this point I decided to PHYSICALLY tidy up the circuit: I cut the resistors down by about 1.5cm each side. I also moved the positive leads away from the resistor bare wires by 1 hole. Tested with Day 4 code and all worked fine. My motivation was to avoid shorts and to make it a bit tidier. (I fully accept the resistors should be shipped “full length” – as they indeed were.) I also have plenty of spare 330Ω resistors – if later days require them.

It was also at this point I decided to PHYSICALLY tidy up the circuit: I cut the resistors down by about 1.5cm each side. I also moved the positive leads away from the resistor bare wires by 1 hole. Tested with Day 4 code and all worked fine. My motivation was to avoid shorts and to make it a bit tidier. (I fully accept the resistors should be shipped “full length” – as they indeed were.) I also have plenty of spare 330Ω resistors – if later days require them.

Martin Packer

Martin Packer

A tune could be encoded as an array/list of triples – to be iterated over. Anyone?

A tune could be encoded as an array/list of triples – to be iterated over. Anyone?

The Pi Hut

The Pi Hut

@Tom It’s something we’re going to look at. It might be tricky to implement (and/or will rely on users to format/tag code properly in comments) but it’s on the list of things to look at next year.

@Tom It’s something we’re going to look at. It might be tricky to implement (and/or will rely on users to format/tag code properly in comments) but it’s on the list of things to look at next year.

Tom

Tom

These comments need code formatting, seems to strip random things from each code that’s been pasted. Making trying them out impossible!

These comments need code formatting, seems to strip random things from each code that’s been pasted. Making trying them out impossible!

PJ

PJ

Loved this day messing with the buzzer and potentiometer.
Here’s how it ended up, with some silly retro sound effects

from machine import PWM, Pin, ADC
import time

potentiometer = ADC)
buzzer = PWM)

def playtone(note, delay1, delay2): #as per the day 5 buzzer demo (thank you PiHut) with volume replaced by potentiometer
buzzer.duty_u16(potentiometer.read_u16())
buzzer.freq(note)
time.sleep(delay1)
buzzer.duty_u16(0)
time.sleep(delay2)

def play_effect(starting_note,finishing_note,note_decrement,note_length,note_separation,blast_length):
note = starting_note #set the initial note

while note > finishing_note: playtone(note,note_length,note_separation) #play the note note -= note_decrement #reduce the note by the specified value for i in range(blast_length): #play a blast effect, repeating for specified length/occurrences playtone(800,0.001,0.001) playtone(750,0.001,0.001) playtone(850,0.001,0.001) playtone(700,0.001,0.001) buzzer.duty_u16(0) #silence the buzzer

def laser_shot(starting_note,finishing_note):
starting_note = starting_note #starting note for the run down
finishing_note = finishing_note #finishing note for the run down
note_decrement = 100 #size of step for the run down
note_length = 0.009 #the length of the note
note_separation = 0.001 #the separation between notes
blast_length = 0 #the length of the blast – 0 = no blast

play_effect(starting_note,finishing_note,note_decrement,note_length,note_separation,blast_length) #play the effect

def missile_strike():
starting_note = 1200 #starting note for the run down
finishing_note = 700 #finishing note for the run down
note_decrement = 20 #size of step for the run down
note_length = 0.05 #the length of the note
note_separation = 0.001 #the separation between notes
blast_length = 100 #the length of the blast

play_effect(starting_note,finishing_note,note_decrement,note_length,note_separation,blast_length) #play the effect

def lasers():
for a in range(6): #play the effects [a] times
laser_shot(2000,1000)
laser_shot(1200,700)
laser_shot(800,400)
time.sleep(0.01)

missile_strike() #play missile strike effect

time.sleep(0.05)

lasers() #play laser effect

Loved this day messing with the buzzer and potentiometer.
Here’s how it ended up, with some silly retro sound effects

from machine import PWM, Pin, ADC
import time

potentiometer = ADC)
buzzer = PWM)

def playtone(note, delay1, delay2): #as per the day 5 buzzer demo (thank you PiHut) with volume replaced by potentiometer
buzzer.duty_u16(potentiometer.read_u16())
buzzer.freq(note)
time.sleep(delay1)
buzzer.duty_u16(0)
time.sleep(delay2)

def play_effect(starting_note,finishing_note,note_decrement,note_length,note_separation,blast_length):
note = starting_note #set the initial note

while note > finishing_note: playtone(note,note_length,note_separation) #play the note note -= note_decrement #reduce the note by the specified value for i in range(blast_length): #play a blast effect, repeating for specified length/occurrences playtone(800,0.001,0.001) playtone(750,0.001,0.001) playtone(850,0.001,0.001) playtone(700,0.001,0.001) buzzer.duty_u16(0) #silence the buzzer

def laser_shot(starting_note,finishing_note):
starting_note = starting_note #starting note for the run down
finishing_note = finishing_note #finishing note for the run down
note_decrement = 100 #size of step for the run down
note_length = 0.009 #the length of the note
note_separation = 0.001 #the separation between notes
blast_length = 0 #the length of the blast – 0 = no blast

play_effect(starting_note,finishing_note,note_decrement,note_length,note_separation,blast_length) #play the effect

def missile_strike():
starting_note = 1200 #starting note for the run down
finishing_note = 700 #finishing note for the run down
note_decrement = 20 #size of step for the run down
note_length = 0.05 #the length of the note
note_separation = 0.001 #the separation between notes
blast_length = 100 #the length of the blast

play_effect(starting_note,finishing_note,note_decrement,note_length,note_separation,blast_length) #play the effect

def lasers():
for a in range(6): #play the effects [a] times
laser_shot(2000,1000)
laser_shot(1200,700)
laser_shot(800,400)
time.sleep(0.01)

missile_strike() #play missile strike effect

time.sleep(0.05)

lasers() #play laser effect

Severin

Severin

We love this Christmas calendar!
This is what we made so far:
You need lights, potentiometer and buzzer :-)

from machine import Pin, PWM, ADC
import time

buzzer = PWM)
red = Pin(18, Pin.OUT)
green = Pin(20, Pin.OUT)
potentiometer = ADC)

count = 0
volume = 0

c = 261;
d = 294;
e = 329;
f = 349;
g = 391;
gS = 415;
a = 440;
aS = 455;
b = 466;
cH = 523;
cSH = 554;
dH = 587;
dSH = 622;
eH = 659;
fH = 698;
fSH = 740;
gH = 784;
gSH = 830;
aH = 880;

def playBeep(note, duration):
global count
volume = potentiometer.read_u16()
buzzer.duty_u16(volume)
buzzer.freq(note)

if count % 2 == 0 : red.value(1) time.sleep(duration) red.value(0) else: green.value(1) time.sleep(duration) green.value(0) buzzer.duty_u16(0) time.sleep(0.050) count += 1

def playPart1():
playBeep(a, 0.5);
playBeep(a, 0.5);
playBeep(a, 0.5);
playBeep(f, 0.35);
playBeep(cH, 0.15);
playBeep(a, 0.5);
playBeep(f, 0.35);
playBeep(cH, 0.15);
playBeep(a, 0.65);
time.sleep(0.5);
playBeep(eH, 0.5);
playBeep(eH, 0.5);
playBeep(eH, 0.5);
playBeep(fH, 0.35);
playBeep(cH, 0.15);
playBeep(gS, 0.5);
playBeep(f, 0.35);
playBeep(cH, 0.15);
playBeep(a, 0.65);
time.sleep(0.5);

def playPart2():
playBeep(aH, 0.5);
playBeep(a, 0.3);
playBeep(a, 0.15);
playBeep(aH, 0.5);
playBeep(gSH, 0.325);
playBeep(gH, 0.175);
playBeep(fSH, 0.125);
playBeep(fH, 0.125);
playBeep(fSH, 0.25);
time.sleep(0.325);
playBeep(aS, 0.25);
playBeep(dSH, 0.5);
playBeep(dH, 0.325);
playBeep(cSH, 0.175);
playBeep(cH, 0.125);
playBeep(b, 0.125);
playBeep(cH, 0.25);
time.sleep(0.35);

def playPart3():
playBeep(f, 0.25);
playBeep(gS, 0.5);
playBeep(f, 0.35);
playBeep(a, 0.125);
playBeep(cH, 0.5);
playBeep(a, 0.375);
playBeep(cH, 0.125);
playBeep(eH, 0.65);
time.sleep(0.5);

def playPart4():
playBeep(f, 0.25);
playBeep(gS, 0.5);
playBeep(f, 0.375);
playBeep(cH, 0.125);
playBeep(a, 0.5);
playBeep(f, 0.375);
playBeep(cH, 0.125);
playBeep(a, 0.65);
time.sleep(0.65);

playPart1()
playPart2()
playPart3()
playPart2()
playPart4()

buzzer.duty_u16(0)

We love this Christmas calendar!
This is what we made so far:
You need lights, potentiometer and buzzer :-)

from machine import Pin, PWM, ADC
import time

buzzer = PWM)
red = Pin(18, Pin.OUT)
green = Pin(20, Pin.OUT)
potentiometer = ADC)

count = 0
volume = 0

c = 261;
d = 294;
e = 329;
f = 349;
g = 391;
gS = 415;
a = 440;
aS = 455;
b = 466;
cH = 523;
cSH = 554;
dH = 587;
dSH = 622;
eH = 659;
fH = 698;
fSH = 740;
gH = 784;
gSH = 830;
aH = 880;

def playBeep(note, duration):
global count
volume = potentiometer.read_u16()
buzzer.duty_u16(volume)
buzzer.freq(note)

if count % 2 == 0 : red.value(1) time.sleep(duration) red.value(0) else: green.value(1) time.sleep(duration) green.value(0) buzzer.duty_u16(0) time.sleep(0.050) count += 1

def playPart1():
playBeep(a, 0.5);
playBeep(a, 0.5);
playBeep(a, 0.5);
playBeep(f, 0.35);
playBeep(cH, 0.15);
playBeep(a, 0.5);
playBeep(f, 0.35);
playBeep(cH, 0.15);
playBeep(a, 0.65);
time.sleep(0.5);
playBeep(eH, 0.5);
playBeep(eH, 0.5);
playBeep(eH, 0.5);
playBeep(fH, 0.35);
playBeep(cH, 0.15);
playBeep(gS, 0.5);
playBeep(f, 0.35);
playBeep(cH, 0.15);
playBeep(a, 0.65);
time.sleep(0.5);

def playPart2():
playBeep(aH, 0.5);
playBeep(a, 0.3);
playBeep(a, 0.15);
playBeep(aH, 0.5);
playBeep(gSH, 0.325);
playBeep(gH, 0.175);
playBeep(fSH, 0.125);
playBeep(fH, 0.125);
playBeep(fSH, 0.25);
time.sleep(0.325);
playBeep(aS, 0.25);
playBeep(dSH, 0.5);
playBeep(dH, 0.325);
playBeep(cSH, 0.175);
playBeep(cH, 0.125);
playBeep(b, 0.125);
playBeep(cH, 0.25);
time.sleep(0.35);

def playPart3():
playBeep(f, 0.25);
playBeep(gS, 0.5);
playBeep(f, 0.35);
playBeep(a, 0.125);
playBeep(cH, 0.5);
playBeep(a, 0.375);
playBeep(cH, 0.125);
playBeep(eH, 0.65);
time.sleep(0.5);

def playPart4():
playBeep(f, 0.25);
playBeep(gS, 0.5);
playBeep(f, 0.375);
playBeep(cH, 0.125);
playBeep(a, 0.5);
playBeep(f, 0.375);
playBeep(cH, 0.125);
playBeep(a, 0.65);
time.sleep(0.65);

playPart1()
playPart2()
playPart3()
playPart2()
playPart4()

buzzer.duty_u16(0)

LED

LED

Made this drip music check it out

Imports
from machine import Pin, PWM
import time Set up the Buzzer pin as PWM
buzzer = PWM) # Set the buzzer to PWM mode Create our library of tone variables for “Among us drip”
A = 440
As = 466
B = 494
C = 523
Cs = 554
D = 587
Ds = 622
E = 659
F = 698
Fs = 740
G = 784
Gs = 830 Create volume variable (Duty cycle)
volume = 10000 Create our function with arguments
def playtone(note,vol,delay1,delay2):
buzzer.duty_u16(vol)
buzzer.freq(note)
time.sleep(delay1)
buzzer.duty_u16(0)
time.sleep(delay2) Play the tune
playtone(D,volume,0.1,0.2)
playtone(F,volume,0.1,0.2)
playtone(G,volume,0.1,0.2)
playtone(Gs,volume,0.1,0.2)
playtone(G,volume,0.1,0.2)
playtone(F,volume,0.1,0.2)
playtone(D,volume,0.1,0.5)

playtone(C,volume,0.1,0.2)
playtone(E,volume,0.1,0.2)
playtone(D,volume,0.1,0.5)

playtone(A,volume,0.1,0.2)
playtone(D,volume,0.1,0.5)

playtone(D,volume,0.1,0.2)
playtone(F,volume,0.1,0.2)
playtone(G,volume,0.1,0.2)
playtone(Gs,volume,0.1,0.2)

playtone(G,volume,0.1,0.2)
playtone(F,volume,0.1,0.2)
playtone(Gs,volume,0.1,0.5)

playtone(Gs,volume,0.1,0.1)
playtone(G,volume,0.1,0.1)
playtone(F,volume,0.1,0.1)
playtone(Gs,volume,0.1,0.1)
playtone(G,volume,0.1,0.1)
playtone(F,volume,0.1,0.1)

playtone(D,volume,0.5,0.5)

Duty to 0 to turn the buzzer off
buzzer.duty_u16(0)

Made this drip music check it out

Imports
from machine import Pin, PWM
import time Set up the Buzzer pin as PWM
buzzer = PWM) # Set the buzzer to PWM mode Create our library of tone variables for “Among us drip”
A = 440
As = 466
B = 494
C = 523
Cs = 554
D = 587
Ds = 622
E = 659
F = 698
Fs = 740
G = 784
Gs = 830 Create volume variable (Duty cycle)
volume = 10000 Create our function with arguments
def playtone(note,vol,delay1,delay2):
buzzer.duty_u16(vol)
buzzer.freq(note)
time.sleep(delay1)
buzzer.duty_u16(0)
time.sleep(delay2) Play the tune
playtone(D,volume,0.1,0.2)
playtone(F,volume,0.1,0.2)
playtone(G,volume,0.1,0.2)
playtone(Gs,volume,0.1,0.2)
playtone(G,volume,0.1,0.2)
playtone(F,volume,0.1,0.2)
playtone(D,volume,0.1,0.5)

playtone(C,volume,0.1,0.2)
playtone(E,volume,0.1,0.2)
playtone(D,volume,0.1,0.5)

playtone(A,volume,0.1,0.2)
playtone(D,volume,0.1,0.5)

playtone(D,volume,0.1,0.2)
playtone(F,volume,0.1,0.2)
playtone(G,volume,0.1,0.2)
playtone(Gs,volume,0.1,0.2)

playtone(G,volume,0.1,0.2)
playtone(F,volume,0.1,0.2)
playtone(Gs,volume,0.1,0.5)

playtone(Gs,volume,0.1,0.1)
playtone(G,volume,0.1,0.1)
playtone(F,volume,0.1,0.1)
playtone(Gs,volume,0.1,0.1)
playtone(G,volume,0.1,0.1)
playtone(F,volume,0.1,0.1)

playtone(D,volume,0.5,0.5)

Duty to 0 to turn the buzzer off
buzzer.duty_u16(0)
Victoria

Victoria

You can save your songs in functions, that way your program can play more than one song!

More musically inclined people. PLEASE POST YOUR SONGS!! Emma posted a very good one!
I am trying and failing to make something sound like carol of the bells. This is as close as I could get.
def carol_of_bells():
pt(A,volume,0.3,0.2)
pt(C,volume,0.1,0.2)
pt(E,volume,0.1,0.2)
pt(D,volume,0.1,0.5)
pt(A,volume,0.3,0.2)
pt(C,volume,0.1,0.2)
pt(E,volume,0.1,0.2)
pt(D,volume,0.1,0.2)

You can save your songs in functions, that way your program can play more than one song!

More musically inclined people. PLEASE POST YOUR SONGS!! Emma posted a very good one!
I am trying and failing to make something sound like carol of the bells. This is as close as I could get.
def carol_of_bells():
pt(A,volume,0.3,0.2)
pt(C,volume,0.1,0.2)
pt(E,volume,0.1,0.2)
pt(D,volume,0.1,0.5)
pt(A,volume,0.3,0.2)
pt(C,volume,0.1,0.2)
pt(E,volume,0.1,0.2)
pt(D,volume,0.1,0.2)

Emma

Emma

Really cool! I enjoyed trying different tunes. Found my favorite one by far.
I added a higher A to the list and called it A2, frequency is 880Hz.
Feel free to try out :)

Tones that I used:
C = 523
D = 587
E = 659
F = 698
G = 784
A2 = 880

Song:
playtone(C,volume,0.1,0.1)
playtone(D,volume,0.1,0.1)
playtone(F,volume,0.1,0.1)
playtone(D,volume,0.1,0.2)
playtone(A2,volume,0.1,0.2)
playtone(A2,volume,0.1,0.2)
playtone(G,volume,0.1,0.5)

playtone(C,volume,0.1,0.1)
playtone(D,volume,0.1,0.1)
playtone(F,volume,0.1,0.1)
playtone(D,volume,0.1,0.2)
playtone(G,volume,0.1,0.2)
playtone(G,volume,0.1,0.2)
playtone(F,volume,0.1,0.05)
playtone(E,volume,0.1,0.05)
playtone(D,volume,0.1,0.5)

playtone(C,volume,0.1,0.1)
playtone(D,volume,0.1,0.1)
playtone(F,volume,0.1,0.1)
playtone(D,volume,0.1,0.1)
playtone(F,volume,0.1,0.3)
playtone(G,volume,0.1,0.07)
playtone(E,volume,0.1,0.07)
playtone(D,volume,0.1,0.1)
playtone(C,volume,0.1,0.4)
playtone(C,volume,0.1,0.1)
playtone(G,volume,0.1,0.2)
playtone(F,volume,0.1,0.2)

Really cool! I enjoyed trying different tunes. Found my favorite one by far.
I added a higher A to the list and called it A2, frequency is 880Hz.
Feel free to try out :)

Tones that I used:
C = 523
D = 587
E = 659
F = 698
G = 784
A2 = 880

Song:
playtone(C,volume,0.1,0.1)
playtone(D,volume,0.1,0.1)
playtone(F,volume,0.1,0.1)
playtone(D,volume,0.1,0.2)
playtone(A2,volume,0.1,0.2)
playtone(A2,volume,0.1,0.2)
playtone(G,volume,0.1,0.5)

playtone(C,volume,0.1,0.1)
playtone(D,volume,0.1,0.1)
playtone(F,volume,0.1,0.1)
playtone(D,volume,0.1,0.2)
playtone(G,volume,0.1,0.2)
playtone(G,volume,0.1,0.2)
playtone(F,volume,0.1,0.05)
playtone(E,volume,0.1,0.05)
playtone(D,volume,0.1,0.5)

playtone(C,volume,0.1,0.1)
playtone(D,volume,0.1,0.1)
playtone(F,volume,0.1,0.1)
playtone(D,volume,0.1,0.1)
playtone(F,volume,0.1,0.3)
playtone(G,volume,0.1,0.07)
playtone(E,volume,0.1,0.07)
playtone(D,volume,0.1,0.1)
playtone(C,volume,0.1,0.4)
playtone(C,volume,0.1,0.1)
playtone(G,volume,0.1,0.2)
playtone(F,volume,0.1,0.2)

John

John

Angelo – If you want to control the volume as you go, I altered the playtone function to update the volume as it plays each note (no need for a while loop)

def playtone(note,vol,delay1,delay2):
reading = potentiometer.read_u16()
vol = int(reading / 6)
buzzer.duty_u16(vol)
buzzer.freq(note)
time.sleep(delay1)
buzzer.duty_u16(0)
time.sleep(delay2)

Note this makes the global volume variable and the vol input into the playtone function redundant.

Angelo – If you want to control the volume as you go, I altered the playtone function to update the volume as it plays each note (no need for a while loop)

def playtone(note,vol,delay1,delay2):
reading = potentiometer.read_u16()
vol = int(reading / 6)
buzzer.duty_u16(vol)
buzzer.freq(note)
time.sleep(delay1)
buzzer.duty_u16(0)
time.sleep(delay2)

Note this makes the global volume variable and the vol input into the playtone function redundant.

Jonothan Hunt

Jonothan Hunt

This calendar is so much fun!

If anyone wants a sc-fi lights and sound effect, I’ve made this script. When you turn the potentiometer, the speaker plays a random sound with pitch from the reading and each light lights randomly too!

Imports
from machine import Pin, PWM, ADC
import time
import random Set up the Buzzer pin as PWM
buzzer = PWM) # Set the buzzer to PWM mode
led = Pin(18, Pin.OUT) # LED 1
led2 = Pin(19, Pin.OUT) # LED 2
led3 = Pin(20, Pin.OUT) # LED 3
potentiometer = ADC) # Potentiometer

reading = 0
newReading = 0
delay= 0.05
played = 0
delay = 0.03

while played < 100:
newReading = potentiometer.read_u16() # new reading from potentiometer
note = random.randint(100, 500) + int(newReading / 40) # noise chosen randomly + added pitch from the new reading

Print old reading and new reading
print("old: “, reading)
print(”new: ", newReading) If new reading is > 500 > last reading Or new reading is > 500 < last reading Then play the random sound and activate the lights randomly
if newReading > (reading + 500) or newReading < (reading – 500): buzzer.duty_u16(200) buzzer.freq(note) time.sleep(delay) buzzer.duty_u16(0) led.value(1 if random.random() > 0.5 else 0) led2.value(1 if random.random() > 0.5 else 0) led3.value(1 if random.random() > 0.5 else 0) reading = newReading played += 1 Sleep for 0.05 before checking a new reading
time.sleep(0.05) Turn lights and buzzer off
led.value(0)
led2.value(0)
led3.value(0)

buzzer.duty_u16(0)

This calendar is so much fun!

If anyone wants a sc-fi lights and sound effect, I’ve made this script. When you turn the potentiometer, the speaker plays a random sound with pitch from the reading and each light lights randomly too!

Imports
from machine import Pin, PWM, ADC
import time
import random Set up the Buzzer pin as PWM
buzzer = PWM) # Set the buzzer to PWM mode
led = Pin(18, Pin.OUT) # LED 1
led2 = Pin(19, Pin.OUT) # LED 2
led3 = Pin(20, Pin.OUT) # LED 3
potentiometer = ADC) # Potentiometer

reading = 0
newReading = 0
delay= 0.05
played = 0
delay = 0.03

while played < 100:
newReading = potentiometer.read_u16() # new reading from potentiometer
note = random.randint(100, 500) + int(newReading / 40) # noise chosen randomly + added pitch from the new reading

Print old reading and new reading
print("old: “, reading)
print(”new: ", newReading) If new reading is > 500 > last reading Or new reading is > 500 < last reading Then play the random sound and activate the lights randomly
if newReading > (reading + 500) or newReading < (reading – 500): buzzer.duty_u16(200) buzzer.freq(note) time.sleep(delay) buzzer.duty_u16(0) led.value(1 if random.random() > 0.5 else 0) led2.value(1 if random.random() > 0.5 else 0) led3.value(1 if random.random() > 0.5 else 0) reading = newReading played += 1 Sleep for 0.05 before checking a new reading
time.sleep(0.05) Turn lights and buzzer off
led.value(0)
led2.value(0)
led3.value(0)

buzzer.duty_u16(0)

HEATH

HEATH

so so good very cool

so so good very cool

Rob Box

Rob Box

“Jin…”
play_note(volume, E, 0.15, 0.15) “…gle”
play_note(volume, E, 0.15, 0.15) “Bells”
play_note(volume, E, 0.3, 0.3) “Jin…”
play_note(volume, E, 0.15, 0.15) “…gle”
play_note(volume, E, 0.15, 0.15) “Bells”
play_note(volume, E, 0.3, 0.3) “Jin…”
play_note(volume, E, 0.3, 0) “…gle”
play_note(volume, G, 0.3, 0) “All”
play_note(volume, C, 0.3, 0.15)
Try the following timings; it should make things sounds a bit less like an electronic card! ;) “The”
play_note(volume, D, 0.15, 0) “Way”
play_note(volume, E, 0.3, 0.15)
“Jin…”
play_note(volume, E, 0.15, 0.15) “…gle”
play_note(volume, E, 0.15, 0.15) “Bells”
play_note(volume, E, 0.3, 0.3) “Jin…”
play_note(volume, E, 0.15, 0.15) “…gle”
play_note(volume, E, 0.15, 0.15) “Bells”
play_note(volume, E, 0.3, 0.3) “Jin…”
play_note(volume, E, 0.3, 0) “…gle”
play_note(volume, G, 0.3, 0) “All”
play_note(volume, C, 0.3, 0.15)
Try the following timings; it should make things sounds a bit less like an electronic card! ;) “The”
play_note(volume, D, 0.15, 0) “Way”
play_note(volume, E, 0.3, 0.15)
giles

giles

Thanks for the remaining notes including sharps @Chris Ellis.

I was rather surprised to discover that Github copilot understood that we are writing music code (it is an AI code auto-completer from Microsoft that controversially learns how to code from all the open source software on Github)

I found it was able to fill in the extra note’s frequencies (but not sharps!) for me and write a tune with correct frequencies and delays. However, it seemed fixated on star wars music and I’ve not yet convinced it to auto-complete jingle bells for me!

I’ll post a demo soon.

Thanks for the remaining notes including sharps @Chris Ellis.

I was rather surprised to discover that Github copilot understood that we are writing music code (it is an AI code auto-completer from Microsoft that controversially learns how to code from all the open source software on Github)

I found it was able to fill in the extra note’s frequencies (but not sharps!) for me and write a tune with correct frequencies and delays. However, it seemed fixated on star wars music and I’ve not yet convinced it to auto-complete jingle bells for me!

I’ll post a demo soon.

Angelo

Angelo

How could you set the volume of the final tune using the PWM value of the potentiometer? I have tried and keep getting stuck in a while loop or end up having it only set the volume at the beginning of each play through.

How could you set the volume of the final tune using the PWM value of the potentiometer? I have tried and keep getting stuck in a while loop or end up having it only set the volume at the beginning of each play through.

Alex

Alex

Nice project! Any idea if you can combine multiple PWM outputs to create more complex sounds / chords?

Nice project! Any idea if you can combine multiple PWM outputs to create more complex sounds / chords?

Chris Ellis

Chris Ellis

Really enjoying this, if anyone else is interested here’s a scale of notes to play with if you want to make more tunes:

A = 440
As = 466
B = 494
C = 523
Cs = 554
D = 587
Ds = 622
E = 659
F = 698
Fs = 740
G = 784
Gs = 830

Really enjoying this, if anyone else is interested here’s a scale of notes to play with if you want to make more tunes:

A = 440
As = 466
B = 494
C = 523
Cs = 554
D = 587
Ds = 622
E = 659
F = 698
Fs = 740
G = 784
Gs = 830

The Pi Hut

The Pi Hut

@Phil C – You’re absolutely right – good spot! One of those moments where you don’t realise the code is technically wrong because the error still allows it to work as expected. Thanks for letting us know.

@Phil C – You’re absolutely right – good spot! One of those moments where you don’t realise the code is technically wrong because the error still allows it to work as expected. Thanks for letting us know.

Phil C

Phil C

Enjoying this so far. Just a quick note on the last piece of code:
the variable volume is fed into the function as vol, but then inside the function it is still using the global volume variable

Enjoying this so far. Just a quick note on the last piece of code:
the variable volume is fed into the function as vol, but then inside the function it is still using the global volume variable

Leave a comment

All comments are moderated before being published.

This site is protected by hCaptcha and the hCaptcha Privacy Policy and Terms of Service apply.