In this project, we will create a simple tone generator that emits a tone in the audible range between 20Hz and 20KHz.
Connect a Buzzer Brick to Port 2C, and a Rotary Switch Brick to Port 2A and 4A.
Run the following code in the Web IDE:
var buzzer = new Buzzer(PORT_2C);
var rsw = new RotarySwitch(PORT_2A, PORT_4A);
var playing = false;
var freq = 4000; // Starting frequency
while(true) {
// This lets the target frequency be adjusted in increments of 100
var newFreq = freq + (rsw.getDelta() * 100);
// This limits the target frequency to between 20Hz and 20,000Hz
newFreq = Math.max(20, Math.min(newFreq, 20000));
// If there are any changes, print out the new parameters to console so that we can see what's going on
var clicked = rsw.clicked();
if (newFreq != freq || clicked) {
if (clicked) playing = !playing;
freq = newFreq;
print('Frequency = ' + freq + 'Hz' + (playing ? ' (playing)' : ' (not playing)'));
}
// Start playing a tone in the target frequency, or stop the playing
if (playing) buzzer.playTone(freq); else buzzer.stop();
}
When you click on the button, the buzzer will start playing a tone in 4KHz. Turning the knob will adjust the frequency up or down. Clicking the button again will stop the tone.