Skip to content

Instantly share code, notes, and snippets.

@zed
Last active November 5, 2016 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zed/9af4ebc7136348721677a35d7fd8cc84 to your computer and use it in GitHub Desktop.
Save zed/9af4ebc7136348721677a35d7fd8cc84 to your computer and use it in GitHub Desktop.
Beep PC Speaker using Linux evdev API.
#!/usr/bin/env python
"""Beep PC Speaker using Linux evdev API.
To make /dev/input/by-path/platform-pcspkr-event-spkr device available, run:
root# modprobe pcspkr
"""
import ctypes
import math
import os
import time
EV_SND = 0x12 # linux/input-event-codes.h
SND_TONE = 0x2 # ditto
time_t = suseconds_t = ctypes.c_long
class Timeval(ctypes.Structure):
_fields_ = [('tv_sec', time_t), # seconds
('tv_usec', suseconds_t)] # microseconds
class InputEvent(ctypes.Structure):
_fields_ = [('time', Timeval),
('type', ctypes.c_uint16),
('code', ctypes.c_uint16),
('value', ctypes.c_int32)]
frequency = 440 # Hz, A440 in ISO 16
device = "/dev/input/by-path/platform-pcspkr-event-spkr"
pcspkr_fd = os.open(device, os.O_WRONLY) # root! + modprobe pcspkr
fsec, sec = math.modf(time.time()) # current time
ev = InputEvent(time=Timeval(tv_sec=int(sec), tv_usec=int(fsec * 1000000)),
type=EV_SND,
code=SND_TONE,
value=frequency)
os.write(pcspkr_fd, ev) # start beep
try:
time.sleep(0.2) # 200 milliseconds
finally:
ev.value = 0 # stop
os.write(pcspkr_fd, ev)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment