Arduino Code Example - playing sounds
Example 1: just playing sounds
The following program is an example that will play notes out of the characters received over the serial port. To try it out, upload this file to Arduino, hook up a piezo or a speaked to digital pin 8 and send characters to play each note.
/* Play notes over serial
* ----------------------
*
* note - half period (uS)
* -----------------------
* c - 1,911
* d - 1,703
* e - 1,517
* f - 1,432
* g - 1,276
* a - 1,136
* b - 1,012
* C - 956
*/
int val = 0; // to check if there is data available from the serial port
int val2 = 0; // stores the data that came from the port
int piezoPin = 8; // pin number where to hook the speaker
int pulso = 0; // value of half pulse
void setup() {
Serial.begin(9600);
pinMode(piezoPin, OUTPUT);
}
void loop() {
val = Serial.available();
if (val > 0) {
val2 = Serial.read();
if (val2 == 'c') {
pulso = 1911;
}
if (val2 == 'd') {
pulso = 1703;
}
if (val2 == 'e') {
pulso = 1517;
}
if (val2 == 'f') {
pulso = 1432;
}
if (val2 == 'g') {
pulso = 1276;
}
if (val2 == 'a') {
pulso = 1136;
}
if (val2 == 'b') {
pulso = 1012;
}
if (val2 == 'C') {
pulso = 956;
}
}
digitalWrite(piezoPin, HIGH);
delayMicroseconds(pulso);
digitalWrite(piezoPin, LOW);
delayMicroseconds(pulso);
}
Example 2: upgrading to notes
Notes have duration in time, this program will play a tone for some time, and then go silent, instead of keeping it sounding forever, as the previous program does.
/* Play notes over serial v0002
* ----------------------------
*
* note - half period (uS)
* -----------------------
* c - 1,911
* d - 1,703
* e - 1,517
* f - 1,432
* g - 1,276
* a - 1,136
* b - 1,012
* C - 956
*
* We create a function that will take care of
* playing a tone for a while and go silent
* afterwards
*/
int val = 0; // to check if there is data available from the serial port
int val2 = 0; // stores the data that came from the port
int piezoPin = 8; // pin number where to hook the speaker
void playNote(int note) {
for( int a=0; a <= 50; a++) {
digitalWrite(piezoPin, HIGH);
delayMicroseconds(note);
digitalWrite(piezoPin, LOW);
delayMicroseconds(note);
}
}
void setup() {
Serial.begin(9600);
pinMode(piezoPin, OUTPUT);
}
void loop() {
val = Serial.available();
if (val > 0) {
val2 = Serial.read();
if (val2 == 'c') {
playNote(1911);
}
if (val2 == 'd') {
playNote(1703);
}
if (val2 == 'e') {
playNote(1517);
}
if (val2 == 'f') {
playNote(1432);
}
if (val2 == 'g') {
playNote(1276);
}
if (val2 == 'a') {
playNote(1136);
}
if (val2 == 'b') {
playNote(1012);
}
if (val2 == 'C') {
playNote(956);
}
}
}