led_drv.c驱动文件:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <asm/io.h> //包含 iomap 和 iounmap 函数
#include <asm/uaccess.h> //包含 copy_from_user 函数
#include <linux/device.h> //包含 class 类相关的处理函数
#include <linux/fs.h> //包含 file_operations 结构体
#define DRIVER_NAME "led_drv"
#define DEVICE_NAME "led_dev"
int major;
static struct class *leddrv_class;
static struct class_device *leddrv_class_dev;
volatile unsigned long *gpfcon = NULL;
volatile unsigned long *gpfdat = NULL;
static int led_drv_open(struct inode *inode, struct file *file)
{
*gpfcon &= ~((0x3<<(4*2)) | (0x3<<(5*2)) | (0x3<<(6*2)));
*gpfcon |= ((0x1<<(4*2)) | (0x1<<(5*2)) | (0x1<<(6*2)));
return 0;
}
static ssize_t led_drv_write(struct file *file, const char __user *buf, size_t count, loff_t * ppos)
{
int val, ret;
ret = copy_from_user(&val, buf, count);
if(ret!=0)
{
printk("led_drv_write error 1 \n");
}
if (val == 1)
{
*gpfdat &= ~((1<<4) | (1<<5) | (1<<6)); //点灯
}
else
{
*gpfdat |= (1<<4) | (1<<5) | (1<<6); //灭灯
}
return 0;
}
static struct file_operations led_drv_fops = {
.owner = THIS_MODULE,
.open = led_drv_open,
.write = led_drv_write,
};
static int led_drv_init(void)
{
major = register_chrdev(0, DRIVER_NAME, &led_drv_fops);
leddrv_class = class_create(THIS_MODULE, DRIVER_NAME); //创建设备类
leddrv_class_dev = class_device_create(leddrv_class, NULL, MKDEV(major, 0), NULL, DEVICE_NAME); //在设备类下创建设备文件其实也就是设备节点,
//创建好的设备文件(设备节点)可以在中/dev
//下查看, 如果创建成功,则在/dev下应该有
//led_dev这个设备文件名,或者说是有
//led_dev这个设备节点
gpfcon = (volatile unsigned long *)ioremap(0x56000050, 16);
gpfdat = gpfcon + 1;
return 0;
}
static void led_drv_exit(void)
{
unregister_chrdev(major, DRIVER_NAME);
class_device_unregister(leddrv_class_dev);
class_destroy(leddrv_class);
iounmap(gpfcon);
}
module_init(led_drv_init);
module_exit(led_drv_exit);
MODULE_LICENSE("GPL");
Makefile文件:
obj-m += led_drv.o
KERN_DIR = /work/system/linux-2.6.22.6
all:
make -C $(KERN_DIR) M=`pwd` modules
clean:
rm -rf *.o *.ko *.order *.symvers *.mod.c
led_app文件:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc, char **argv)
{
int fd;
int val = 1;
fd = open("/dev/led_dev", O_RDWR);
if(fd<0)
{
printf("can not open \n");
}
if(argc != 2)
{
printf("%s <on|off> \n");
return 0;
}
if(strcmp(argv[1], "on") == 0)
{
val = 1;
}
else
{
val = 0;
}
write(fd, &val, 4);
return 0;
}
编译led_drv.c与led_app.c文件, 加载编译后的模块, 运行./led_app on 或 ./led_app off可以看到灯的亮灭。