🎨
MadMachine-Examples
  • Introduction
  • About our project
  • Getting Started
  • Tutorial
    • What is SwiftIO
    • How to use IDE
    • Libraries
    • MM SDK
  • Built-In Examples
    • GettingStarted
      • Blink
      • ReadDigitalInput
      • ReadAnalogInput
      • PWMBrightnessControl
    • SimpleIO
      • ButtoncontrolLED
      • BlinkAnalogIn
      • BlinkTimer
      • BrightnessAnalogIn
      • Debounce
      • LEDsBrightnessControl
      • PWMSoundOutput
      • PWMMelody
    • AdvancedIO
      • ILI9341
      • LCD1602
      • MidiPlayer
      • PCA9685
      • SHT3x
      • SSD1315
    • Challenge
      • LCDFamily
      • RobotArm
      • Tetris
    • MakerKit
      • Mission 01 Blink
      • Mission 02 RGB LED
      • Mission 03 Push Button
      • Mission 04 Potentiometer RGB
      • Mission 05 Buzzer
      • Mission 06 Seven Segment Display
      • Mission 07 DC Motor
      • Mission 08 Servo Motor
      • Mission 09 LCD
      • Mission 10 Humiture Sensor
  • Library Reference
  • FAQ
Powered by GitBook
On this page
  • What you need
  • Circuit
  • Code
  • Instruction
  • See Also
  • References

Was this helpful?

  1. Built-In Examples
  2. SimpleIO

PWMMelody

PreviousPWMSoundOutputNextAdvancedIO

Last updated 4 years ago

Was this helpful?

This example shows how to use the PWMOut to generate notes. It plays a little melody which you may have heard before.

What you need

  • SwiftIO board

  • Jumper wires

  • Piezo buzzer or a speaker

  • SwiftIO shield (optional)

Circuit

Code

// 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

// Initialize a PWM output pin the speaker is connected to.
let speaker = PWMOut(Id.PWM2B)

// Specify several frequencies corresponding to each note of the melody. 
let fre = [
    350,350,393,441,
    441,393,350,330,
    294,294,330,350,
    350,330,330
]

/// 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)
    }
}

Instruction

The code above uses a Frequency as musical pitches. For example, NOTE_C4 is middle C, whose frequency is 262 Hz. Latter example MidiPlayer we will markdown all this musical note in a file. This file contains all the pitch values for typical notes. You may find it useful whenever you want to make musical notes.

See Also

References

- The PWMOut class is used to change the time of high voltage during one period to simulate different output.

PWMOut
Frequency and Pitch
Online Tone Generator
wiki: Pitch (music)