This lab is an introduction to generating simple tones on an Arduino. NOTE: This will work only for Arduino 0018 and beyond.
The Lab:
The Arduino Code:
void setup(){
//nothing to do here
}
void loop(){
// get a sensor reading;
int frequency = analogRead(A0);
tone(8, frequency,10);
}
The Result:
A more complex example:
For this sketch, we’ll play a simple melody. A melody consists of notes played in a sequence, and rests between the note. Each note and rest has its own particular duration. We’re going to play a seven note sequence, as follows (in C Major):
The Lab:
The lab is the same lab as the above. Only the code is changed.
The Code:
#include “pitches.h”
//notes in the melody:
int melody[] = {
NOTE_C4, NOTE_G3,NOTE_G3, NOTE_G3, NOTE_G3,0, NOTE_B3, NOTE_C4};
//note durations: 4=quarter note, 8=eight note, etc.:
int noteDurations[] = {
4, 8, 8, 4,4,4,4,4 };
void setup () {
//iterate over the notes of the melody;
for (int thisNote = 0; thisNote < 8; thisNote++) {
//to calculate the note duration, take one second
//divided by the note type.
//e.g. quarter note = 1000/4, eight note = 1000/8, etc.
int noteDuration = 1000/noteDurations[thisNote];
tone(8, melody[thisNote],noteDuration);
//pause for the note’s duration plus 30 ms:
delay(noteDuration +30);
}
}
void loop()
{
//no need to repeat the melody.
}
The Result:
A Musical Instrument:
The Lab:
[nggallery id=4]
The Code: I changed the code a little but because I didn’t have a third pressure resistor so I used a photo resistor. So, instead of a if statement, I used ‘if’ and ‘else’ statements.
#include “pitches.h”
const int threshold = 10; //minimum reading of the sensors that generates a note
const int speakerPin = 8; //pin number for the speaker
const int noteDuration = 20; //play note for 20 ms
//note to play, corresponding to the 3 sensors;
int notes[] = {
NOTE_A4, NOTE_B4,NOTE_C3 };
void setup() {
Serial.begin(9600);
}
void loop() {
for (int thisSensor = 0; thisSensor < 3; thisSensor++) {
//get a sensor reading:
int sensorReading = analogRead(thisSensor);
//if the sensor is pressed hard enough:
if( thisSensor < 2) {
if (sensorReading > threshold) {
//play the note corresponding to this sensor:
tone(speakerPin, notes[thisSensor], 20);
}
} else if(sensorReading < 800) {
tone(speakerPin, notes[thisSensor], 20);
}
}
}
The Result:



