Piezo buzzers

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 generate the sound.

If we want to bypass the driver and use PWM directly to control the buzzer, we can do it like this:

private lateinit var buzzer: Pwm

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

val pioService = PeripheralManager.getInstance()
buzzer = pioService.openPwm(BoardDefaults.piezoPwm)
buzzer.setPwmDutyCycle(50.0)

[...]
}

override fun onDestroy() {
super.onDestroy()
buzzer.close()
[...]
}

The initialization is now done using PeripheralManager.openPwm() and the only configuration is to set the duty cycle. Note that the buzzer variable type is now Pwm instead of Speaker.

Then, we can set the frequency and enable it to play as well as set enabled to false in order to make it stop.

A PWM signal will stop completely when we disable it.

Regardless of the configuration of frequency and duty cycle, a PWM signal will stop completely when we disable it. We also need to enable it explicitly to make it send the pulse.

Note that we need to set the frequency before enabling the PWM pin; otherwise the operating system considers it as not properly initialized and throws an exception.

override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
val freqToPlay = frequencies.get(keyCode)
if (freqToPlay != null) {
buzzer.setPwmFrequencyHz(freqToPlay)
buzzer.setEnabled(true)
return true
}
else {
return false
}
}

override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
buzzer.setEnabled(false)
return true
}

With these simple modifications, we can now control the piezo buzzer using the concepts of PWM. Let's move onto the most interesting components that you can control with this protocol: servo motors.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.33.107