字符设备驱动---点亮led---基于jz2440开发板

First_drv.c内容如下:

#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 <asm/io.h>
#include <asm/arch/regs-gpio.h>
#include <asm/hardware.h>

static struct class *firstdrv_class;
static struct class_device *firstdrv_class_devs;

volatile unsigned long *GPFCON = NULL;
volatile unsigned long *GPFDAT = NULL;

static int first_drv_open(struct inode *inode, struct file *file)
{
//printk("first_drv_open\n");
/*配置引脚GPF 4 5 6为输出*/
*GPFCON &= ~((3<< (4*2)) |(3<< (5*2)) |(3<< (6*2)));
*GPFCON |= ((1<< (4*2)) |(1<< (5*2)) |(1<< (6*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");
/*用户空间和内核空间之间的数据传递cope_to_user*/
copy_from_user(&val, buf, count);
if(val == 1)
{
                  //点灯

                *GPFDAT &= ~((1<<5) |(1<<6)|(1<<4));

      }
else
{
//灭灯
*GPFDAT |= ((1<<5) |(1<<6)|(1<<4));
}
return 0;
}
/* 这个结构是字符设备驱动程序的核心
 * 当应用程序操作设备文件时所调用的open、read、write等函数,
 * 最终会调用这个结构中指定的对应函数
 */
static struct file_operations first_drv_fops = {
    .owner  =   THIS_MODULE,    /* 这是一个宏,推向编译模块时自动创建的__this_module变量 */
    .open   =   first_drv_open,       
.write =    first_drv_write,   
};

 int major;
 /*
 * 执行insmod命令时就会调用这个函数 
 */
int first_drv_init(void)
{
major = register_chrdev(0,"first_drv",&first_drv_fops);  //注册,告诉内核
firstdrv_class = class_create(THIS_MODULE, "firstdrv");   //创建一个类

//if (IS_ERR(firstdrv_class))
//return PTR_ERR(firstdrv_class);
firstdrv_class_devs = class_device_create(firstdrv_class, NULL, MKDEV(major, 0), NULL, "xyz"); /* /dev/xyz */  
//在类下面创建一个设备

// if (unlikely(IS_ERR(firstdrv_class_devs)))
// return PTR_ERR(firstdrv_class_devs);
GPFCON = (volatile unsigned long *)ioremap(0x56000050,16);
GPFDAT = GPFCON+1;
return 0;
}
 /*
 * 执行rmmod命令时就会调用这个函数 
 */
static void first_drv_exit(void)
{
unregister_chrdev(major,"first_drv");  //卸载驱动
class_device_unregister(firstdrv_class_devs);
class_destroy(firstdrv_class);
iounmap(GPFCON);
}
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("cannt 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驱动文件编译的时候要制定头文件的目录,韦东山视频里在makefile中指定了编译好的内核目录。

猜你喜欢

转载自blog.csdn.net/stormjason/article/details/79943367