led点灯驱动

内核版本:linux-2.6.32.2

开发板:mini2440


参考韦东山的视频,编写代码,对于其源码稍有改动,以适合linux-2.6.32.2版本。代码如下:

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <mach/io.h>
#include <asm/io.h>

#include <mach/regs-gpio.h>
#include <mach/hardware.h>
#include <linux/device.h>


#define DEVICE_NAME "led_2"

static struct class *leds_class;
//static struct device *leds_class_devs;

volatile unsigned long *gpbcon;
volatile unsigned long *gpbdat;

 

static int mini2440_leds_open(struct inode *inode, struct file *file)
{
	/* mini2440 board the leds
	   GPB5~8,set these ports output 
    */
    *gpbcon &= ~((0x03<<(5*2))|(0x03<<(6*2))|(0x03<<(7*2))|(0x03<<(8*2)));
    *gpbcon |=  ((0x01<<(5*2))|(0x01<<(6*2))|(0x01<<(7*2))|(0x01<<(8*2)));        
	//printk("mini2440_leds_open\n");
    return 0;
}


static ssize_t mini2440_leds_write(struct file *file, const char __user *buf, size_t count, loff_t * ppos)
{
    int ret;
	copy_from_user(&ret,buf,count);
	printk("ret=%d\n",ret);
	if ( ret == 1 ) /*when the light is on set ports 0*/
	{
		*gpbdat &= ~((1<<5)|(1<<6)|(1<<7)|(1<<8)); 
		printk("the light is on\n");
	}
	else
	{
		*gpbdat |=  ((1<<5)|(1<<6)|(1<<7)|(1<<8)); 
		printk("the light is off\n");
	}

    return 0;
}

static struct file_operations mini2440_leds_fops = {
    .owner  =   THIS_MODULE,    /* 这是一个宏,推向编译模块时自动创建的__this_module变量 */
    .open   =   mini2440_leds_open,     	   
	.write	=	mini2440_leds_write,	   
};

/*
 * 执行insmod命令时就会调用这个函数 
 */

int ret;
static int mini2440_leds_init(void)
{

    ret = register_chrdev(0, DEVICE_NAME, &mini2440_leds_fops);
	 
	leds_class = class_create(THIS_MODULE,"leds");


	device_create(leds_class, NULL, MKDEV(ret, 0), NULL, "led2"); /* /dev/led1 */
	

     gpbcon =(volatile unsigned long *)ioremap(0x56000010,16);
	 gpbdat = gpbcon + 1;
     return 0;
}

/*
 * 执行rmmod命令时就会调用这个函数 
 */
static void mini2440_leds_exit(void)
{
	
    /* 卸载驱动程序 */
    unregister_chrdev(ret, DEVICE_NAME);
	
    device_destroy(leds_class,MKDEV(ret, 0));

    class_destroy(leds_class);

    iounmap(gpbcon);
    }
/* 这两行指定驱动程序的初始化函数和卸载函数 */
module_init(mini2440_leds_init);
module_exit(mini2440_leds_exit);
/* 描述驱动程序的一些信息,不是必须的 */MODULE_LICENSE("GPL");
<pre name="code" class="cpp"><pre name="code" class="cpp">

 
 

 注意 
 

	leds_class = class_create(THIS_MODULE,"leds");


	device_create(leds_class, NULL, MKDEV(ret, 0), NULL, "led2"); /* /dev/led1 */

	device_destroy(leds_class,MKDEV(ret, 0));

	class_destroy(leds_class);
这4个函数,之前因为对这个不是很了解,在insmod和rmmod时一直出现错误,有不能卸载的错误出现。




   


你可能感兴趣的:(linux)