User Tools

Site Tools


courses:jan27

Sound from an arduino

A simple way to create sound for a prototype is by connecting a speaker to the arduino and send frequencies to it by setting the pin high and low in quick succession.

A simple example:

int soundPin =  13;    // Piezo speaker connected to digital pin 13
 
// The setup() method runs once, when the sketch starts
void setup()   {                
  // initialize the digital pin as an output:
  pinMode(soundPin, OUTPUT);     
}
 
// the loop() method runs over and over again,
// as long as the Arduino has power
 
void loop()                     
{
  digitalWrite(soundPin, HIGH);   // set the pin HIGH
  delayMicroseconds(1136);                  // wait for a bit
  digitalWrite(soundPin, LOW);    // set the pin LOW
  delayMicroseconds(1136);                  // wait for a bit
}

Explore how you can program the tones to behave. What happens if you have the frequency slide over time? Can you make the arduino tweet like a bird? What kind of noises can you create? Laser? Explosion? Creaking? Croaking?

Tone library

If the goal is to play simple melodies, there is a library for the arduino that neatly packages the frequencies and commands to play actual tones.

A simplified version of the Tone library has been incorporated into the Arduino core since 0018. If you don't have it, it can be downloaded from here.

To install a library, create a directory called libraries (if you have none since before) within your sketchbook directory. Then unzip the library there. For example, to install the Tone library, its files should be in the /libraries/Tone sub-folder of your sketchbook folder.

Methods

- begin(pin) - prepares a pin for playing a tone.

- isPlaying() - returns true if tone is playing, false if not.

- play(frequency [, duration]) - play a tone. frequency is in Hertz, and the duration is in milliseconds. duration is optional. If duration is not given, tone will play continuously until stop() is called. play() is non-blocking. Once called, play() will return immediately. If duration is given, the tone will play for that amount of time, and then stop automatically.

- stop() - stop playing a tone.

A table of notes versus frequencies could be useful.

More details on the library here.

Quick example

Play a 440 Hz - musical note of 4th octave A - on pin 13:

#include <Tone.h>
 
Tone tone1;
 
void setup()
{
  tone1.begin(13);
  tone1.play(NOTE_A4);
}
 
void loop()
{
}

Play around with melodies, practice methods by putting phrases in methods called from the loop.

Done already?

Expand with sensors and build an instrument!

courses/jan27.txt · Last modified: 2011/01/27 00:23 by 130.239.149.90