Simple Speaker Setup
Introduction
Speakers can be used for many things, for example playing tunes, communicate to a user of a product or even give a warning that something is wrong.
In this guide, you will learn how to connect a speaker to your microcontroller and make it play a noise using a speaker or active buzzer.
Before continuing this guide it is recommended that you have read- or have basic knowledge about .
Supplies
- board
- Wires
- 100 Ohm
- Piezo (any speaker or buzzer will do)
Circuit
Code
// How to connect a (Piezo) speaker
// This code will make your speaker make a pitched sound.
// a pin for the speaker is initialized
const int PiezoPin = 2;
void setup() {
// no setup is required for this tutorial :)
}
void loop() {
/* For this tutorial the tone() function is used:
* tone() require 2 inputs with an optional third input
* 1) pin number
* 2) frequency - hertz (cycles per second) which determines
* the pitch of the noise made
* 3) duration (optional) - duration of tone in milliseconds before the
* code skips to the next line. If no duration is used the tone will
* play continuously.
*/
// make a pitch sound at 2000-, 3000- and 4000 hertz for half a second each
tone(PiezoPin, 2000, 500);
delay(500);
tone(PiezoPin, 3000, 500);
delay(500);
tone(PiezoPin, 4000, 500);
delay(500);
}
import gpiozero as g
import time
# How to connect a (Piezo) speaker
# This code will make your speaker make a pitched sound.
# Define Buzzer on pin 11 (#17)
buzzer = g.Buzzer(17)
# Initialize loop
while True:
# Buzzer makes noise every second
buzzer.on()
time.sleep(1)
buzzer.off()
time.sleep(10)
Further Work
Now that you have completed this tutorial on how to connect a speaker, try creating your own tune.