Overview
With Arduino, we can generate sounds in several frequencies using a simple buzzer or speaker.
Arduino's API comes with specific functions for this given task: tone() and noTone() [1].
In this project, we'll use a bunch of pushbuttons in order to create a musical keyboard!
The goal is to produce distinct tones for each of the 6 available pushbuttons.
These six tones should correspond to these musical notes: C5, D5, E5, F5, G5, and A5.
Yeah, B5 is missing due to lack of space in my small 400-contacts breadboard.
Note frequencies were retrieved from Physics of Music Notes (MTU Physics) [2].
Components
- 1 buzzer (or speaker)
- 6 pushbuttons
- 6 current resistors
- Jumper wires
- Breadboard
- Arduino Uno compatible
Schematics
[https://github.com/hjort/arduino-toys/blob/master/buzzer/MusicalKeyboard.fz]
Source Code
#define BUTTON1_PIN 3 #define BUTTON2_PIN 4 #define BUTTON3_PIN 5 #define BUTTON4_PIN 6 #define BUTTON5_PIN 7 #define BUTTON6_PIN 8 #define BUZZER_PIN 9 #define FIRST_BUTTON BUTTON1_PIN #define LAST_BUTTON BUTTON6_PIN #define FREQ_C5 523.25 #define FREQ_D5 587.33 #define FREQ_E5 659.25 #define FREQ_F5 698.46 #define FREQ_G5 783.99 #define FREQ_A5 880.00 const float freqs[] = {FREQ_C5, FREQ_D5, FREQ_E5, FREQ_F5, FREQ_G5, FREQ_A5}; void setup() { for (int pin = FIRST_BUTTON; pin <= LAST_BUTTON; pin++) pinMode(pin, INPUT); } void loop() { int button = 0, freq = 0; for (int pin = FIRST_BUTTON; pin <= LAST_BUTTON; pin++) { if (digitalRead(pin) == HIGH) { button = pin - FIRST_BUTTON; freq = int(freqs[button]); tone(BUZZER_PIN, freq, 100); } } delay(100); }
[https://github.com/hjort/arduino-toys/blob/master/buzzer/MusicalKeyboard.ino]
Project in Action
References
- Arduino Language Reference Guide - Tone: https://www.arduino.cc/en/Reference/Tone
- Frequencies of Musical Notes: http://www.phy.mtu.edu/~suits/notefreqs.html