LED是字符设备,可以根据字符设备驱动进行编写。字符设备驱动的编写首先是内核模块的框架,然后分析得到LED驱动需要实现的方法有打开设备,控制设备。
这就是编写LED驱动的分析流程。下面开始编写。
创建驱动文件led.c
1.首先编写内核模块
#include <linux/module.h>
#include <linux/init.h>
static int led_init()
{
return 0;
}
static void led_exit()
{
}
module_init(led_init);
module_exit(led_exit);
2.编写Makefile
obj -m := led.o
KDIR := /内核路径
all :
make -C $(KDIR) M=$(PWD) modules CROSS_COMPILE=arm-linux- ARCH=arm
3.驱动的初始化
#include <linux/module.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <linux/fs.h>
struct cdev cdev;//静态分配cdev
dev_t devno;
struct struct file_operations led_fops =
{
.open = led_open;
.unlocked_ioctl = led_ioctl;
}//file_operations 结构的定义
int led_open(struct inode *node, struct file *filp)
{
led_config = ioremap(LEDCON,4);
writel(0x11110000,led_config);
led_data = ioremap(LEDDAT,4);
return 0;
}
static int led_init()
{
cdev_init(&cdev,&led_fops);//初始化cdev
alloc_chrdev_region(&devno,0,1,myled);.//动态分配主设备号
cdev_add(&cdev,devno,1);//注册CDEV
return 0;
}
static void led_exit()
{
cdev_del(&cdev);//注销内核的cdev
unregiter_chrdev_region(devno,1);//注销设备号
}
module_init(led_init);
module_exit(led_exit);
4.实现控制命令
创建led.h文件
编写:
#defien MEM_MAGIC 'L'
#defien MEM_ON _IO(MEM_MAGIC,0)
#defien MEM_OFF _IO(MEM_MAGIC,1)
编写驱动文件
long led_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
switch (cmd)
{
case LED_ON:
writel(0x00,led_data);
return 0;
case LED_OFF:
writel(0xff,led_data);
return 0;
default:
return -EINVAL;
}
}