C编程控制PC蜂鸣器方法2
在《C编程控制PC蜂鸣器》一文中,我们了解并使用了通过IO端口控制的方式操作硬件,而有些时候这对于一些朋友来说太模糊了,很容易让人迷糊,这次采用最基本的write系统调用来写入input_event数据实现相同功能。 这里涉及到的input_event可参考《C编程实现键盘LED闪烁方法2》一文,还有接下来要先加载pcspkr驱动,这个问题可查阅《Shell命令控制蜂鸣器发声》一文了解。 首先,执行sudo modprobe pcspkr命令加载驱动,然后查看/proc/bus/input/devices文件,我这边会有如下内容: I: Bus=0010 Vendor=001f Product=0001 Version=0100 N: Name=”PC Speaker” P: Phys=isa0061/input0 S: Sysfs=/devices/platform/pcspkr/input/input17 U: Uniq= H: Handlers=kbd event15 B: PROP=0 B: EV=40001 B: SND=6 这就是加载Linux内核drivers/input/misc/pcspkr.c文件对应的pcspkr驱动后所生成的。 而我们对应的input_event设置中,其type设置为EV_SND,而code可设置为SND_TONE和SND_BELL,其中前者只接受value为20至32767之间的值,其他值均为无声,后者接受0时无声,其他值时均会转为1000。 接下来上代码吧,你可以从代码中看到我们的处理: #include <stdio.h> #include <linux/input.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #define PCSPKR_EVENT_PATH "/dev/input/event15" int main(int argc,char * argv[]) { unsigned int val; int fd = 0; struct input_event ev; e...