Similar to what we did for GPIO, let's remove the Rainbow HAT driver from our dependencies and include only the drivers we require. For this first example, we just need to add the driver for the piezo buzzer, which is called driver-pwmspeaker:
dependencies {
[...]
implementation 'com.google.android.things.contrib:driver-pwmspeaker:+'
}
And then, we simply need to instantiate a Speaker object attached to the correct PWM pin:
class PianoActivity : Activity() {
[...]
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
buzzer = Speaker(BoardDefaults.piezoPwm)
[...]
}
[...]
}
If we dig into the source code of the driver, we can see that it sets the duty cycle to 50% and then modifies the frequency when we invoke play. The buzzer uses the frequency from the PWM signal to vibrate and...