home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / c / other / utility / beep.c next >
Encoding:
C/C++ Source or Header  |  1988-10-27  |  2.2 KB  |  86 lines

  1. /* BEEP.C illustrates timing and port input and output functions
  2.  * including:
  3.  *      inp             outp            clock
  4.  * Also keyword:
  5.  *      enum
  6.  *
  7.  * In addition to the delay use shown here, clock can be used as a
  8.  * timer as shown in SIEVE.C.
  9.  */
  10.  
  11. #include <time.h>
  12. #include <conio.h>
  13.  
  14. void beep( unsigned duration, unsigned frequency );
  15. void delay( clock_t wait );
  16.  
  17.  
  18. enum notes
  19. {   /* Enumeration of notes and frequencies     */
  20.     C0 = 262, D0 = 296, E0 = 330, F0 = 349, G0 = 392, A0 = 440, B0 = 494,
  21.     C1 = 523, D1 = 587, E1 = 659, F1 = 698, G1 = 784, A1 = 880, B1 = 988,
  22.     EIGHTH = 125, QUARTER = 250, HALF = 500, WHOLE = 1000, END = 0
  23. } song[] =
  24. {   /* Array initialized to notes of song       */
  25.     C1, HALF, G0, HALF, A0, HALF, E0, HALF, F0, HALF, E0, QUARTER,
  26.     D0, QUARTER, C0, WHOLE, END
  27. };
  28.  
  29. int main ()
  30. {
  31.     int note = 0;
  32.  
  33.     while( song[note] )
  34.         beep( song[note++], song[note++] );
  35. }
  36.  
  37. /* beep - sounds the speaker for a time specified in microseconds by
  38.  * duration at a pitch specified in hertz by frequency.
  39.  */
  40. void beep( unsigned duration, unsigned frequency )
  41. {
  42.     int control;
  43.  
  44.     /* If frequency is 0, beep doesn't try to make a sound. It
  45.      * just sleeps for the duration.
  46.      */
  47.     if (frequency)
  48.     {
  49.         /* 75 is the shortest reliable duration of a sound. */
  50.         if( duration < 75 )
  51.             duration = 75;
  52.  
  53.         /* Prepare timer by sending 10111100 to port 43. */
  54.         outp( 0x43, 0xb6 );
  55.  
  56.         /* Divide input frequency by timer ticks per second and
  57.          * write (byte by byte) to timer.
  58.          */
  59.         frequency = (unsigned)(1193180L / frequency);
  60.         outp( 0x42, (char)frequency );
  61.         outp( 0x42, (char)(frequency >> 8) );
  62.  
  63.         /* Save speaker control byte. */
  64.         control = inp( 0x61 );
  65.  
  66.         /* Turn on the speaker (with bits 0 and 1). */
  67.         outp( 0x61, control | 0x3 );
  68.     }
  69.  
  70.     delay( (clock_t)duration );
  71.  
  72.     /* Turn speaker back on if necessary. */
  73.     if( frequency )
  74.         outp( 0x61, control );
  75. }
  76.  
  77. /* delay - Pauses for a specified number of microseconds. */
  78. void delay( clock_t wait )
  79. {
  80.     clock_t goal;
  81.  
  82.     goal = wait + clock();
  83.     while( goal > clock() )
  84.         ;
  85. }
  86.