Using a buzzer

A simple piezo buzzer can be used to make beeps and even play simple tunes.

Parts

  • Piezo buzzer

  • 2 jumper wires

Wire the circuit

The buzzer requires only a simple circuit. One lead of the buzzer is longer than the other. The longer lead is the positive connector. Using a wire, connect this to a GPIO port. Then connect the other lead to ground.

Create the Xojo app

You'll use the open-source Xojo GPIO library to control the buzzer. For advanced control of the buzzer, you can use the GPIO.SoftToneCreate and SoftToneWrite methods.

Alarm

This code sends a simple ON/OFF signal to the buzzer to make it act like an alarm:

GPIO.SetupGPIO

Const kBuzzerPin = 5
GPIO.PinMode(kBuzzerPin, GPIO.OUTPUT)

For i As Integer = 1 To 10
  GPIO.DigitalWrite(kBuzzerPin, GPIO.LOW)
  App.DoEvents(100)
  GPIO.DigitalWrite(kBuzzerPin, GPIO.HIGH)
  App.DoEvents(100)
Next

GPIO.Cleanup

Tones

This code uses the SoftToneCreate and SoftToneWrite methods to play a simple Super Mario Brothers tune:

Const kBuzzerPin = 5

' Simple Super Mario Brothers theme
Var scales() As Integer = Array(659, 659, 0, 659, 0, 523, 659, 0, _
  784, 0, 0, 0, 392, 0, 0, 0, 523, 0, 0, 392, 0, 0, 330)

GPIO.SetupGPIO
If GPIO.SoftToneCreate(kBuzzerPin) = 0 Then
  For i As Integer = 0 To scales.LastRowIndex
    GPIO.SoftToneWrite(kBuzzerPin, scales(i))
    App.DoEvents(200)
  Next
End If

GPIO.PinMode(kBuzzerPin, GPIO.INPUT)