How to use a piezoelectric buzzer with ARM based Arduino compatibles

I recently had to integrate a basic passive piezoelectric buzzer into a project utilizing the Adafruit Bluefruit Feather nRF52, which is an Arduino IDE compatible development board that is based on the Nordic Semiconductor nRF52832 SoC containing an ARM Cortex-M4F processor. Upon googling how to use a piezo buzzer with Arduino all guides pointed towards using the build in tone() library which should do the trick. But there is only one problem, there is currently no native support for ARM based controllers due to some changes in timings that would need to be made from the AVR compatible version. The solution is simple, just use basic PWM to make the buzzer buzz. Here is a wiring diagram to get it working:

Just hookup the positive side of the buzzer to any PWM supported header and the negative to ground. In this case I have it connected to A4 which translates to digital output 28 according to this pinout:

Now that we have the wiring done, we need to write a program to address the buzzer. This requires the Arduino IDE of course along with the correct BSP installed (check Adafruit’s website for the BSP install info for this particular board). Now for the program itself.

This solution allows you to enter in the duration of the buzz into the Serial Monitor and the piezo buzzer will buzz for that allotment of time. It uses digitalWrite() to send an alternating HIGH and LOW signal to the buzzer with a 1000 microsecond delay between modulation. Changing the delay will alter the pitch of the buzz, with lower delays providing a more high pitched sound and higher delays providing a lower pitch. Feel free to change the delays to match your desired pitch. This quick and simple solution will pretty much work with all Arduino compatibles that support digitalWrite().