using System; using Microsoft.SPOT; using Microsoft.SPOT.Hardware; using SecretLabs.NETMF.Hardware; using System.Threading; namespace HelloNetduino { class PiezoSpeaker { PWM pwm; Timer timer; public PiezoSpeaker(Cpu.Pin pin) { pwm = new PWM(pin); } /// <summary> /// Sends the given frequency to the piezo speaker for the parameter duration. /// </summary> /// <param name="duration">Duration of the output, in ms.</param> /// <param name="frequency">Frequency of the output in Hz.</param> public void FrequencyOut(int duration, int frequency) { if (timer != null) throw new Exception("The speaker is already in use."); // Start the PWM pin buzzing. The input in Hz is the number of times the signal // should oscillate per second. Given high and low values times should be equal, // divide the time in a second in half to account for off time, then divide the // remainder by the frequency to get the PWM duration value. Period = duration here. var period = (uint)(1000 / 2 / frequency); pwm.SetPulse(period, period); timer = new Timer(FrequencyOutTimerCallback, null, duration, 0); } /// <summary> /// Turns off the PWM pin used for the speaker and cleans up the timer. /// </summary> private void FrequencyOutTimerCallback(object state) { Debug.Print(DateTime.Now.ToString() + " tick."); pwm.SetDutyCycle(0); timer.Dispose(); timer = null; } } }
And to make it buzz at 3000 Hz for 1 second:
public static void Main() { PiezoSpeaker speaker = new PiezoSpeaker(Pins.GPIO_PIN_D5); Debug.Print(DateTime.Now.ToString() + " start."); speaker.FrequencyOut(1000, 3000); Thread.Sleep(10000); // Sleep for 10 seconds so the program doesn't exit while the speaker is in use. Debug.Print(DateTime.Now.ToString() + " done."); }
Sadly, I get no result from the speaker. The speaker I have was made for use with a Parallax basic stamp. I assumed I could wire it up to the Netduino the same way it's wired up for a basic board - I'm running the + terminal to pin 5 on the Netduino and the - terminal to ground. Can anyone spot an error in my code or wiring?