Today we will learn a new way to output through the Arduino pins using the tone() function.
We will also learn how to recieve input through an Arduino pin and to send debugging information back to a PC.
BONUS: If we do well we can combine both of these to make a musical instrument called a "Theramin".
tone(pinNumber, frequency)
Sets a pin to continuously turn on and off at a given number of times per second.
noTone(pinNumber)
Suspends any tone currently playing through a given pin.
Serial.begin(baudRate)
Opens a serial channel on the given baud rate (use 9600) which we can use to communicate with other devices like our PC through the USB connection.
Serial.println(message)
Sends a message over a previously opened serial channel. Use the Serial Monitor to recieve messages.
analogRead(analogPin)
Checks the given pin and returns a value for the current it is currently recieving 0-1023.
int speaker = 10; // Remember speaker is on pin 10
void setup() {
pinMode(speaker, OUTPUT); // Set speaker pin to output mode
}
void loop() {
tone(speaker, 440); // play a note of 440Hz over the speaker (A Note)
delay(200); // Wait 20% of a second
tone(speaker, 559); // play a note of 559Hz over the speaker (B Note)
delay(200); // Wait 20% of a second
}
int resistor = 9; // Remember resistor is on pin 9
void setup() {
Serial.begin(9600);
pinMode(resistor, INPUT); // Set speaker pin to INPUT mode
}
void loop() {
int value = analogRead(resistor);
Serial.println(value);
delay(200); // Wait 20% of a second
}
int resistor = 9; // Remember resistor is on pin 9
int speaker = 10; // Remember speaker is on pin 10
void setup() {
Serial.begin(9600);
pinMode(resistor, INPUT); // Set speaker pin to input mode
pinMode(speaker, OUTPUT); // Set speaker pin to output mode
}
void loop() {
int value = analogRead(resistor);
tone(speaker, value);
delay(200); // Wait 20% of a second
}
EASY
Write a program that will play a simple tune through the speaker, you will have to have a series of tone() and delay() commands.
Mary Had a Little Lamb is suggested, it's notes are:
E D C D E E E D D D E E E E D C D E E E D D E D C
The frequencies for the standard middle musical notes are:
C 262 D 294 E 330 F 349 G 392 A 440 B 494
LESS EASY
Adjust the theramin code from schematic 3 so that instead of playing the valuefrom the photoresistor directly, it plays the above musical notes.
This can be done by checking the range of values that the resistor gives andmaking a series of IF statements to make certain ranges play a note.
eg.
if (value < 20){
tone(speaker, 262);
} else if (value < 40){
tone(speaker, 294);
} else......