Skip to main content

PWM melody

This example is similar to the previous one. You will make the buzzer play a small piece of music.

What you need

  • SwiftIO Feather (or SwiftIO board)
  • Breadboard
  • Buzzer
  • Jumper wires

Circuit

  1. Plug the buzzer onto the breadboard.
  2. Connect any one leg to the pin GND and the other to the pin PWM5A.
circuit diagram

Example code

You can find the example code at the bottom left corner of IDE: example / SimpleIO / PWMMelody.

// Enable the speaker to play a simple melody by changing the frequency of PWM output.
// Import the library to enable the relevant classes and functions.
import SwiftIO

// Import the board library to use the Id of the specific board.
import MadBoard

// Initialize a PWM output pin the speaker connects.
let speaker = PWMOut(Id.PWM5A)

// Specify several frequencies corresponding to each note of the melody.
let fre = [
330,330,349,392,
392,349,330,294,
262,262,294,330,
330,294,294
]

// Allow the speaker to repeat the melody again and again.
while true {
for f in fre {
// Change the frequency and the duty cycle of output to produce each note.
speaker.set(frequency: f, dutycycle: 0.5)
sleep(ms: 250)
}
}

Code analysis

let fre = [
330,330,349,392,
392,349,330,294,
262,262,294,330,
330,294,294
]

The frequencies on the array correspond to the notes of the music. If you want to play other music, you can write down the frequencies according to the music score.

Reference

PWMOut - set the PWM signal.

MadBoard - find the corresponding pin id of your board.