嵌入式ARM驱动蜂鸣器

//包含了模块的一些初始:化函数/宏
#include  
#include
#include   //file operation
#include   //device_create
#include  //copy_from_usr
#include  
#include 
#include   //struct cdev
#include     
#include  //ioremap
#include "led.h"


struct class *p_class;
struct device *p_device;
struct cdev  *p_cdev;
int chr_major;
static volatile unsigned int *p_gpd0con;
static volatile unsigned int *p_gpd0dat;



int drv_open(struct inode * p_indo, struct file * p_file)
{	
	*p_gpd0con = 0x1;

	return 0;
}

//write(fd, &val, sizeof(val));

ssize_t drv_write(struct file *p_file, const char __user *buf, size_t size, loff_t *offset)
{
	int val;
	int ret;
	
	//将数据从用户空间拷贝到内核空间
	ret = copy_from_user(&val,buf,size);
	if (ret)
		return -EFAULT;
	if(val !=0 )
	{
		//点灯
		*p_gpd0dat = val;
	}
	else
	{	//灭灯
		*p_gpd0dat = 0x0;
	}
	
	return size;
}

struct file_operations f_ops = {
	.owner = THIS_MODULE,
	.open  = drv_open,
	.write = drv_write,
};


static int __init drv_init(void)
{
	int ret;	//注册操作方法,申请主设备号	
	chr_major = register_chrdev(0, "drv_module_beep", &f_ops);
	if (chr_major < 1) {		
		printk(KERN_ERR "register_chrdev err\n");		
		return -EINVAL;	
		}	
	//自动创建设备文件	
	//创建一个设备类	
	p_class = class_create(THIS_MODULE, "dev_class_beep");	
	if (IS_ERR(p_class)) {		
		printk(KERN_ERR "failed to create class\n");	
		ret = PTR_ERR(p_class);		
		goto err0;	
	}	
	//在该设备类中,创建一个设备文件	
	p_device = device_create(p_class, NULL, MKDEV(chr_major, 0),NULL, "spv210_beep");	
	if (IS_ERR(p_device)) {		
		printk(KERN_ERR "failed to create device\n");		
		ret = PTR_ERR(p_device);		
		goto err1;
		}	
	//将物理地址映射为虚拟地址	
	/*
	p_gpj2con = ioremap(GPJ2CON,4);	
	p_gpj2dat = ioremap(GPJ2CON,4);*/
	p_gpd0con = ioremap(GPD0CON,8);	
	if (!p_gpd0con) {		
		ret = -ENOMEM;		
		goto err2;	
	}	
	p_gpd0dat = p_gpd0con + 1;
	return 0;
err2:
	device_destroy(p_class, MKDEV(chr_major,0));	
err1:	
	class_destroy(p_class);
	
err0:	
	unregister_chrdev(chr_major, "drv_module_beep");	
	return ret;
		
}


static void __exit drv_exit(void)
{
	//注销操作方法
	unregister_chrdev_region(chr_major,1);
	device_destroy(p_class, MKDEV(chr_major,0));
	class_destroy(p_class);
	iounmap(p_gpd0con);
}


/*声明加载函数和卸载函数*/
module_init(drv_init);
module_exit(drv_exit);
MODULE_LICENSE("GPL");//表示有发布软件的自由

你可能感兴趣的:(嵌入式arm)