Piezo buzzer
Let's make some noise. The buzzer also has its own driver. We can open it using theRainbowHat.openPiezo()
method and it returns an object of type Speaker
.
The Speaker
class has two methods: play
, which receives the frequency to play, and stop
, which -unsurprisingly- makes the speaker stop.
To follow up from the previous section, let's build a three-tone piano where the buttons A, B, and C will play the frequencies of 1,000 Hz, 3,000 Hz, and 5,000 Hz, respectively. The buzzer will start sounding when the button is pressed and stop when the button is released.
For this example, we'll use button drivers for simplicity. The initialization and cleanup for PianoActivity
looks like this:
class PianoActivity : Activity() {
private lateinit var buttonA: ButtonInputDriver
private lateinit var buttonB: ButtonInputDriver
private lateinit var buttonC: ButtonInputDriver
private lateinit var buzzer: Speaker
private val frequencies = hashMapOf(
KEYCODE_A to 1000.0,
KEYCODE_B to 3000.0,
KEYCODE_C...