字符设备驱动程序之LED驱动程序__韦老师linux视频源码

虚拟机ubuntu 11.04

linux-2.6.32.2

mini2440 


题外话:我是个初学者,一直想学linux编程, 但是平时工作的平台是单片机,没有使用上,但是自己心真的不甘,希望能够征服它。平台是大四时候购买的mini2440,4年了,现在把它拿出来学习。再不学习就老了。废话不说了。直接上源代码。

first_drv.c

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/device.h>

#include <mach/irqs.h>
#include <mach/regs-gpio.h>
#include <mach/hardware.h>
#include <asm/uaccess.h>
#include <asm/io.h>


static struct class *firstdrv_class;
static struct class_device	*firstdrv_class_dev;

volatile unsigned long *gpbcon = NULL;
volatile unsigned long *gpbdat = NULL;


static int first_drv_open(struct inode *inode, struct file *file)
{
	printk("first_drv_open\n");
	// gpb5,6,7,8 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)) ); 
	
	return 0;
}

static ssize_t first_drv_write(struct file *file, const char __user *buf, size_t count, loff_t * ppos)
{
	int val;

	printk("first_drv_write\n");
	copy_from_user(&val, buf, count); //	copy_to_user();
	
		if (val == 1)
		{ 
		    //led on
			*gpbdat &= ~((1<<5) | (1<<6) | (1<<7) | (1<<8));
		}
		else
		{
	        //led off
			*gpbdat |= (1<<5) | (1<<6) | (1<<7) | (1<<8);
		}
		

	return 0;
}

static struct file_operations first_drv_fops = {
    .owner  =   THIS_MODULE,    
    .open   =   first_drv_open,     
	.write	=	first_drv_write,	   
};


int major;
static int first_drv_init(void)
{
	major = register_chrdev(0, "first_drv", &first_drv_fops);

	firstdrv_class = class_create(THIS_MODULE, "firstdrv");

	firstdrv_class_dev = device_create(firstdrv_class, NULL, MKDEV(major, 0), NULL, "xyz"); /* /dev/xyz */

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


	return 0;
}

static void first_drv_exit(void)
{
	unregister_chrdev(major, "first_drv"); 
	device_destroy(firstdrv_class,firstdrv_class_dev);

}

module_init(first_drv_init);
module_exit(first_drv_exit);


MODULE_LICENSE("GPL");


firstdrvtest.c

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

/* firstdrvtest on
  * firstdrvtest off
  */
int main(int argc, char **argv)
{
	int fd;
	int val = 1;
	fd = open("/dev/xyz", O_RDWR);
	if (fd < 0)
	{
		printf("can't open!\n");
	}
	
	if (argc != 2)
		{
			printf("Usage :\n");
			printf("%s <on|off>\n", argv[0]);
			return 0;
		}
	
		if (strcmp(argv[1], "on") == 0)
		{
			val  = 1;
		}
		else
		{
			val = 0;
		}
		
		write(fd, &val, 4);
		return 0;
	}


注意红色部分区别


你可能感兴趣的:(字符设备驱动程序之LED驱动程序__韦老师linux视频源码)