> For the complete documentation index, see [llms.txt](https://royals6234.gitbook.io/madmachine-examples/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://royals6234.gitbook.io/madmachine-examples/examples/simpleio/pwmsoundoutput.md).

# PWMSoundOutput

![](https://845437858-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MGOJWkptBbZ3bq0TpEw%2Fsync%2Ff7e2e1f92f1adcd02176d07c8516d839562c1e42.gif?generation=1599890771525995\&alt=media)

This example shows how to use the `PWMOut` to generate notes. It plays three tones repeatedly.

## What you need

* SwiftIO board
* Jumper wires
* Buzzer
* SwiftIO shield (optional)

## Circuit

![](https://845437858-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MGOJWkptBbZ3bq0TpEw%2Fsync%2F84051b605409d927c2a1513fa88685c9d99ac256.png?generation=1600173595333763\&alt=media)

## Code

```swift
// Produce different notes by changing the frequency of PWM signal.

// 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 to produce different sound.
let fre = [262, 294, 330]

/// Play recurrently these notes.
while true {
    for f in fre {
        // Set the frequency and the duty cycle of output to produce each note.
        speaker.set(frequency: f, dutycycle: 0.5)
        // Play each note for one second.
        sleep(ms: 1000)
    }

}
```

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

* [PWMOut](https://swiftioapi.madmachine.io/Classes/PWMOut.html) - The PWMOut class is used to change the time of high voltage during one period to simulate different output.&#x20;

## References

* [Frequency and Pitch](http://www.vias.org/crowhurstba/crowhurst_basic_audio_vol1_006.html)
* [Online Tone Generator](https://www.szynalski.com/tone-generator/)
* [wiki: Pitch (music)](https://en.wikipedia.org/wiki/Pitch_%28music%29)
