Beep your PC speaker in linux

Nowaldays,Many PC(even all) come with an on board device called “PC speaker”, Its common use is to signal an error when BIOS POST(Power-On Self Test).

Sometimes, we are working under a Linux console and want to be noticed when something interesting happen, beep can help.

To make PC speaker beep,we have too method,both using the ioctl function

1. Use the KDMKTONE ioctl command

ioctl(fd, KDMKTONE, arg)

arg is an int value, the upper 16 bits give the duration in millisecond(some article says that it’s in clock tick, but that’s not ture now). The lower 16 bits of arg specify the period in clock cycles(that is 1193180/frequency).fd is the file descriptor of a console device opened with write permission.The call returns immediately

For example, to beep at frequency 440HZ for 5 seconds, we can do like this:

int ms = 5000;
int freq = 440;
ioctl(fd, KDMKTONE, (ms<<16 | 1193180/freq));

2. Use KIOCSOUND ioctl command

ioctl(fd, KIOCSOUND, arg)

The lower 16 bits of arg spec ify the period in clock cycles (that is, arg = 1193180/frequency). arg = 0 turns sound off.In either case, the call returns immediately. fd is the file descriptor of a console device opened with write permission.

For example, to beep at frequency 440HZ for 5 seconds, we can do like this:

int ms = 5000;
int freq = 440;
/* start beep */
ioctl(fd, KIOCSOUND, 1193180/freq);
/* sleep for the duration time  */
usleep(ms * 1000);
/* stop beep */
ioctl(fd, KIOCSOUND, 0);

Notice: In order to use the above two ioctl command, you must include linux/kd.h first.

#include 
#include 

There are already two tools available in linux,both with source code. So you can peek the source and learn the usage:
The one is beep,the other is kdmktone

This entry was posted in Programming and tagged . Bookmark the permalink.

One Response to Beep your PC speaker in linux

  1. aj says:

    I installed pcspkr module and your ‘beep’ program. Now my pc is beeping.
    However, If I try printf(“07″) or char str = {7,0}; printf(str). or even ‘echo ^G’ in the console, my pc does not beep. Then I started looking at beep.c
    it opens device /dev/console and ioctl(fd, KIOCSOUND, clock/freq).
    so I tried that code in my ARM board where I recently wrote a PWM beep driver. It does not invoke this function.
    static int Buzzer_event(struct input_dev *input,
    unsigned int type, unsigned int code, int value)

Leave a Reply

Your email address will not be published.


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>