4.15 Example 13
Sound generation, sound library...
Audio signals are often used when it is necessary to call the user’s attention, confirm that some of the push buttons is pressed, warn that minimum or maximum values are reached etc. It can be just a ‘beep’ signal as well as longer or shorter melody. This example demonstrates sound generation using functions belonging to the
Sound library.
In adition to these functions, the
Button function belonging to the same library is used for testing push buttons.
/*Header******************************************************/
void Tone1() {
Sound_Play(659, 250); // Frequency = 659Hz, duration = 250ms
}
void Tone2() {
Sound_Play(698, 250); // Frequency = 698Hz, duration = 250ms
}
void Tone3() {
Sound_Play(784, 250); // Frequency = 784Hz, duration = 250ms
}
void Melody1() { // Make funny melody 1
Tone1(); Tone2(); Tone3(); Tone3();
Tone1(); Tone2(); Tone3(); Tone3();
Tone1(); Tone2(); Tone3();
Tone1(); Tone2(); Tone3(); Tone3();
Tone1(); Tone2(); Tone3();
Tone3(); Tone3(); Tone2(); Tone2(); Tone1();
}
void ToneA() { // Tone A
Sound_Play(880, 50);
}
void ToneC() { // Tone C
Sound_Play(1046, 50);
}
void ToneE() { // Tone E
Sound_Play(1318, 50);
}
void Melody2() { // Make funny melody 2
unsigned short i;
for (i = 9; i > 0; i--) {
ToneA(); ToneC(); ToneE();
}
}
void main() {
ANSEL = 0; // All I/O pins are digital
ANSELH = 0;
TRISB = 0xF0; // Pins RB7-RB4 are configured as inputs,
// RB3 is configured as an output
Sound_Init(&PORTB, 3);
Sound_Play(1000, 500);
while (1) {
if (Button(&PORTB,7,1,1)) // RB7 generates Tone1
Tone1();
while (PORTB & 0x80) ; // Wait for push button release
if (Button(&PORTB,6,1,1)) // RB6 generates Tone2
Tone2();
while (PORTB & 0x40) ; // Wait for push button release
if (Button(&PORTB,5,1,1)) // RB5 generates melody 2
Melody2();
while (PORTB & 0x20) ; // Wait for push button release
if (Button(&PORTB,4,1,1)) // RB4 generates melody 1
Melody1();
while (PORTB & 0x10) ; // Wait for push button release
}
}
In order to make this example work properly, it is necessary to tick off the following libraries in the
Library Manager prior to compiling: