Linux下简易蜂鸣器驱动代码及测试实例
驱动代码:
#include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/err.h> #include <linux/miscdevice.h> #include <mach/gpio.h> #include <mach/regs-gpio.h> #include <plat/gpio-cfg.h> #define DEVICE_NAME "beep3" #define BEEP_MAGIC 'k' #define BEEP_START_CMD _IO (BEEP_MAGIC, 1) #define BEEP_STOP_CMD _IO (BEEP_MAGIC, 2) static void beep3_stop(void) { printk("in the beep3_stop!!\n"); s3c_gpio_cfgpin(S5PV210_GPD0(0), S3C_GPIO_OUTPUT); gpio_set_value(S5PV210_GPD0(0), 0); } static void beep3_start(void) { printk("in the beep3_start!!\n"); s3c_gpio_cfgpin(S5PV210_GPD0(0), S3C_GPIO_OUTPUT); gpio_set_value(S5PV210_GPD0(0), 1); } static long beep3_ioctl(struct file *filep, unsigned int cmd, unsigned long arg) { printk("in the beep3_ioctl!!\n"); switch ( cmd ) { case BEEP_START_CMD: { printk("in the start_cmd!!\n"); beep3_start(); break; } case BEEP_STOP_CMD: { printk("in the stop_cmd!!\n"); beep3_stop(); break; } default: { break; } } return 0; } static struct file_operations beep3_fops = { .owner = THIS_MODULE, .unlocked_ioctl = beep3_ioctl, }; static struct miscdevice beep3_misc_dev = { .minor = MISC_DYNAMIC_MINOR, .name = DEVICE_NAME, .fops = &beep3_fops, }; static int __init beep3_dev_init(void) { int ret; ret = gpio_request(S5PV210_GPD0(0), DEVICE_NAME); if (ret) { printk("request GPIO %d failed\n",S5PV210_GPD0(0)); return ret; } s3c_gpio_cfgpin(S5PV210_GPD0(0), S3C_GPIO_OUTPUT); gpio_set_value(S5PV210_GPD0(0), 0); ret = misc_register(&beep3_misc_dev); printk(DEVICE_NAME "\tinitialized\n"); return ret; } static void __exit beep3_dev_exit(void) { beep3_stop(); misc_deregister(&beep3_misc_dev); } module_init(beep3_dev_init); module_exit(beep3_dev_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("mhb@SEU"); MODULE_DESCRIPTION("S5PV210 beep Driver");
测试实例:
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <fcntl.h> #define BEEP_MAGIC 'k' #define BEEP_START_CMD _IO (BEEP_MAGIC, 1) #define BEEP_STOP_CMD _IO (BEEP_MAGIC, 2) int main(int argc ,char* argv[]) { int m_fd=0;// m_fd = open("/dev/beep3", O_RDONLY); ioctl(m_fd, BEEP_STOP_CMD); while(1) { printf("enter any key to start !!\n"); getchar(); ioctl(m_fd, BEEP_START_CMD); printf("start success!!\n"); printf("enter any key to stop !!\n"); getchar(); ioctl(m_fd, BEEP_STOP_CMD); } close(m_fd); return 0; }