Arduino Note Generator

This project is a continuation of the Arduino Tone Generator but rather than create a continuous tone, this code chooses specific notes to play.

These are the key Arduino tutorials for the main concepts used in this project:

If you are new to Arduino, see the Getting Started pages.

Parts list

  • Arduino Uno
  • 8 ohm speaker or old headphone speaker
  • 1x 220 resistor
  • 1x 10k potentiometer
  • Breadboard and jumper wires

The Circuit

ArduinoToneGenerator_bb

This is the same circuit as the Arduino Tone Generator.

The Code

Once again the basic idea for the code is as follows:

  1. Read the value from the potentiometer, which will be between 0 (for 0V) up to 1023 (for the full 5V).
  2. Translate this into a pitch to output to the tone() generator – this time it chooses from a specific set of notes.
  3. Instruct the tone() generator to play the tone at that pitch.

Again, if the potentiometer reads 0, then I treat that as an instruction to turn the tone generator off completely.

This uses the map() function again, but this time it maps the sensor value read onto a number (an index) into a list of notes.  The list of notes is defined at the start using the pitch values from the toneMelody tutorial.

Another programming trick allows us to get the size of the list, so we don’t have to tell the code how many notes we’ve put in.  If the number of notes is less than the full 1024 range of the potentiometer, then there will be several readings that match to each note.  If the number of notes is greater, then some will be skipped as the potentiometer is turned.

As previously stated, the tone() function generates a square wave at a certain frequency, which when fed through a speaker generates a simple tone at that frequency.  “Concert A” or A4 is 440Hz and the other notes go up and down from there.  You can see the full set of frequencies for the standard western set of notes by googling “music note frequencies” but there is a pretty good chart here.  The notes used in this example come from the “pitches.h” file in the Arduino example sketch ToneMelody (you can find it in the Arduino environment here File->Examples->02.Digital->toneMelody).

This uses the full range from the toneMelody tutorial – B0 to D#8.

Find it on GitHub here.

Closing Thoughts

From these basic principles it is possible to create a simple keyboard to play some notes.  That will be my next project.

Kevin

Leave a comment