Timer_A: Sound Generation

Another application of PWM is producing sound with the buzzer peripheral on the BoosterPack. Sound waves can be modelled as sinusoidal oscillations. If you look at a sine wave, it has positive values for one half of a cycle and negative values for the other half. One can draw a parallel with the nature of sinusoids to the previous example of dimming an LED to 50% brightness: the LED is on for one half of a cycle and off for the other half.

Knowing that sound waves are oscillations, we can apply PWM to generates sounds of varying pitches. The pitch of a sound is determined by its frequency, as can be seen with musical notes. Every musical note has its own pitch, and every pitch has its own frequency. A convenient reference for which notes match with which frequencies can be found here:

https://homes.luddy.indiana.edu/donbyrd/Teach/MusicalPitchesTable.htm

Let’s take A4 for example. A4 has a frequency of 440 Hz. Thus, the period (T) of a wave that produces the A4 sound is 1/440 ≈ 2,272 μs. From here, we can apply the seconds-to-load-cycles formula to get the length of the period in load cycles. Suppose our system clock (f) is 3 MHz. Then, for load cycles N and prescaler P, N * P = T * f = 2,272 μs * 3 MHz = 6,816 cycles. In this case, choosing a prescaler of 1 would suffice, thus bringing our load value to N = 6,816. Going back to the parallel we drew between sound generation and dimming an LED to 50%, we can conclude that the appropriate duty cycle for sound generation would be 50%. So to conclude, in order to produce a tone of A4 using the buzzer, given a system clock of 3 MHz and a prescaler of 1, we would have to configure a PWM with a period of 6,816 cycles, with the output being high for 6,816/ 2 = 3,408 cycles and low for the other 3,408 cycles.