Output: Piezo Speakers
3 min readSep 29, 2021
Description
For the potentiometer:
- I connected a red power wire to 5V on the arduino, and 1B on the breadboard.
- I connected the potentiometer’s red wire to 1C.
- I connected a blue wire to A0 on the arduino, and 1G on the breadboard.
- I connected a 220 ohm-resistor to 1I and to the power rail (on the negative side)
- I connected the potentiometer’s black wire to the power rail (on the negative side) near the resistor.
- I connected the potentiometer’s yellow wire to A1 on the arduino.
For the piezo speaker:
- I connected a red power wire to 8 on the arduino, and 11G on the breadboard.
- I connected the red wire of the piezo speaker to 11H.
- I connected a black wire to GND on the right side of the arduino, and 8F on the breadboard.
- I connected a 10K ohm-resistor to 8G and 8I.
- I connected the black wire of the piezo speaker to 8J.
I changed the melody (the original one provided for the lab) so that when you turn the potentiometer knob up, it changes the melody to start at a higher pitch, and when you turn the potentiometer knob down, it changes the melody to start at a lower pitch. It also is coded such that once the potentiometer moves, the melody starts over (so it doesn’t have to go through the whole melody before updating to the new pitch). I did this by including the potVal inside of the for loop before it iterates through the melody.
Code
#include "pitches.h"// notes in the melody:
int melody[] = {NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {4, 8, 8, 4, 4, 4, 4, 4
};void setup() {
}void loop() {// iterate over the notes of the melody:for (int thisNote = 0; thisNote < 8; thisNote++) {int potVal = analogRead(A1);
// to calculate the note duration, take one second divided by the note type.//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.int noteDuration = 1000 / noteDurations[thisNote];tone(8, melody[thisNote] + potVal, noteDuration);// to distinguish the notes, set a minimum time between them.// the note's duration + 30% seems to work well:int pauseBetweenNotes = noteDuration * 1.30;delay(pauseBetweenNotes);// stop the tone playing:noTone(8);}
}
Components Used
- Arduino
- Breadboard
- Potentiometer
- 1 long red wire for power (for potentiometer)
- 1 220 ohm-resistor (two red and one brown stripe, for potentiometer)
- 1 long black wire for ground (for potentiometer)
- 1 short blue wire (tells the output what to be from potentiometer)
- Piezo speaker
- 1 short red wire (for connecting piezo speaker)
- 1 short black wire for ground (for piezo speaker)
- 1 10K ohm-resistor (one gold, orange, black, and brown stripe, for piezo speaker)