PWM overview

PWM is an output digital signal that is commonly used to apply a proportional control signal to an external device using a single digital output pin.

PWM is a square wave (no intermediate values, only 0 and 1) that oscillates according to a given frequency and duty cycle. It encodes the information in the length of the pulse, hence its name. A Pulse Width Modulation signal has two components:

  • Frequency (expressed in Hz), which describes how often the output pulse repeats
  • Duty cycle (expressed as a percentage), which describes the amount of time the pulse is on

For example, a PWM signal set to 50% duty is active for half of each cycle:

You can adjust the duty cycle to increase or decrease the amount of time the signal is on, which is reflected in the average value of it (the analog equivalent). The following diagram shows how the signal looks like with 0%, 25%, and 100% duty:

There are a few ways in which components read this information. We will be looking at them separately.

When we use the Rainbow HAT driver, the buzzer is connected to the second PWM pin, while the first one is designed to be used as a connection for a servo. Keep in mind that the naming of the pins depends on the developer kit: Raspberry Pi has them as PWM1 and PWM2, while iMX7D has them labeled PWM0 and PWM1Both are configured on BoardDefaults of the driver, which we will be using in this chapter:

object BoardDefaults {
private const val DEVICE_RPI3 = "rpi3"
private const val DEVICE_IMX7D_PICO = "imx7d_pico"
[...]
val piezoPwm: String
get() = when (Build.DEVICE) {
DEVICE_RPI3 -> "PWM1"
DEVICE_IMX7D_PICO -> "PWM2"
else -> throw IllegalStateException("Unknown Build.DEVICE ${Build.DEVICE}")
}
val servoPwm: String
get() = when (Build.DEVICE) {
DEVICE_RPI3 -> "PWM0"
DEVICE_IMX7D_PICO -> "PWM1"
else -> throw IllegalStateException("Unknown Build.DEVICE ${Build.DEVICE}")
}
[...]
}

Let's start by accessing the piezo buzzer directly.

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

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