forked from nanoframework/nanoFramework.IoT.Device
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Buzzer.cs
83 lines (74 loc) · 2.59 KB
/
Buzzer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Device.Model;
using System.Device.Pwm;
using System.Threading;
namespace Iot.Device.Buzzer
{
/// <summary>
/// Simple buzzer.
/// </summary>
[Interface("Simple buzzer")]
public class Buzzer : IDisposable
{
private PwmChannel _pwmChannel;
/// <summary>
/// Initializes a new instance of the <see cref="Buzzer" /> class.
/// </summary>
/// <param name="pinNumber">Pin connected to buzzer.</param>
public Buzzer(int pinNumber)
: this(PwmChannel.CreateFromPin(pinNumber))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Buzzer" /> class.
/// </summary>
/// <param name="chip">The GPIO pin number in case of a software PWM. The chip in case of a hardware PWM.</param>
/// <param name="channel">The channel to use in case of a hardware PWM.</param>
public Buzzer(int chip, int channel)
: this(PwmChannel.Create(chip, channel))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Buzzer" /> class.
/// </summary>
/// <param name="pwmChannel">The PWM controller to use during work.</param>
public Buzzer(PwmChannel pwmChannel) => _pwmChannel = pwmChannel;
/// <summary>
/// Set new or overwrite previously set frequency and start playing the sound.
/// </summary>
/// <param name="frequency">Tone frequency in Hertz.</param>
[Command]
public void StartPlaying(double frequency)
{
_pwmChannel.Frequency = (int)frequency;
_pwmChannel.Start();
}
/// <summary>
/// Stop playing tone.
/// </summary>
[Command]
public void StopPlaying() => _pwmChannel.Stop();
/// <summary>
/// Play tone of specific frequency for specified duration.
/// </summary>
/// <param name="frequency">Tone frequency in Hertz.</param>
/// <param name="duration">Playing duration in millisecons.</param>
[Command]
public void PlayTone(double frequency, int duration)
{
StartPlaying(frequency);
Thread.Sleep(duration);
StopPlaying();
}
/// <summary>
/// Dispose Buzzer.
/// </summary>
public void Dispose()
{
_pwmChannel?.Dispose();
_pwmChannel = null;
}
}
}