Meadow.Foundation.Audio.PiezoSpeaker
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
protected PiezoSpeaker piezoSpeaker;
public override Task Initialize()
{
Resolver.Log.Info("Initializing...");
piezoSpeaker = new PiezoSpeaker(Device.CreatePwmPort(Device.Pins.D05, new Frequency(100, Frequency.UnitType.Hertz)));
return Task.CompletedTask;
}
public override async Task Run()
{
for (int i = 0; i < 5; i++)
{
Resolver.Log.Info("Playing A major triad starting at A4");
await piezoSpeaker.PlayTone(new Frequency(440, Frequency.UnitType.Hertz), TimeSpan.FromMilliseconds(500)); //A
await piezoSpeaker.PlayTone(new Frequency(554.37f, Frequency.UnitType.Hertz), TimeSpan.FromMilliseconds(500)); //C#
await piezoSpeaker.PlayTone(new Frequency(659.25f, Frequency.UnitType.Hertz), TimeSpan.FromMilliseconds(500)); //E
await Task.Delay(2500);
}
}
Sample project(s) available on GitHub