Remarks

PiezoSpeaker
Status
Source code GitHub
NuGet package

The PiezoSpeaker class represents a piezoelectric speaker that can be used to generate tones across a range of frequencies. They typically perform well between 1-5kHz but may go as high as 100kHz. PiezoSpeaker Implements IToneGenerator.

The positive pin of the piezo speaker connects to a pulse width modulation (PWM) capable pin on the Meadow and the negative pin connects to common/ground. A resistor can be placed in-line to reduce volume.

Code Example

The following example shows how to initialize a PiezoSpeaker and play an A4 note for one second:

public class MeadowApp : App<F7Micro, MeadowApp>
{        
    protected PiezoSpeaker piezoSpeaker;

    public MeadowApp()
    {
        Console.WriteLine("Initializing...");

        piezoSpeaker = new PiezoSpeaker(Device.CreatePwmPort(Device.Pins.D05));

        TestPiezoSpeaker();
    }

    protected void TestPiezoSpeaker()
    {
        Console.WriteLine("TestPiezoSpeaker...");

        while (true)
        {
            Console.WriteLine("Playing A4 note!");
            piezoSpeaker.PlayTone(440, 1000);
            piezoSpeaker.StopTone();
            Thread.Sleep(500);
        }
    }
}

Sample projects available on GitHub

Wiring Example

Characteristic Locus
Inheritance System.Object > PiezoSpeaker
Namespace Meadow.Foundation.Audio
Assembly Meadow.Foundation.dll

Syntax

public class PiezoSpeaker : IToneGenerator

Constructors

View Source

PiezoSpeaker(IIODevice, IPin, Single, Single)

Create a new PiezoSpeaker instance

Declaration
public PiezoSpeaker(IIODevice device, IPin pin, float frequency = 100F, float dutyCycle = 0F)

Parameters

Type Name Description
IIODevice device
IPin pin

PWM Pin connected to the PiezoSpeaker

System.Single frequency
System.Single dutyCycle
View Source

PiezoSpeaker(IPwmPort)

Create a new PiezoSpeaker instance

Declaration
public PiezoSpeaker(IPwmPort port)

Parameters

Type Name Description
IPwmPort port

Properties

View Source

Port

Gets the port that is driving the Piezo Speaker

Declaration
public IPwmPort Port { get; protected set; }

Property Value

Type Description
IPwmPort

Methods

View Source

PlayTone(Single, Int32)

Play a frequency for a specified duration

Declaration
public void PlayTone(float frequency, int duration = 0)

Parameters

Type Name Description
System.Single frequency

The frequency in hertz of the tone to be played

System.Int32 duration

How long the note is played in milliseconds, if durration is 0, tone plays indefinitely

View Source

StopTone()

Stops a tone playing

Declaration
public void StopTone()