基于ok6410:
led驱动程序:
vim led.c
#include<linux/kernel.h>
#include<linux/module.h>
#include<linux/init.h>
#include<linux/io.h>
#include<linux/fs.h>
#include<linux/cdev.h>
#include"led.h"
#include<mach/gpio-bank-k.h>
#define GPMCON 0x7f008820
#define GPMDAT 0x7f008824
unsigned int *led_config;
unsigned int *led_data;
struct cdev cdev;
dev_t devno;
long led_loctl(struct file *filp, unsigned int cmd, unsigned long arg) //实现对硬件的控制
{
switch(cmd)
{
case LED_ON:
writel(0x00,led_data);
return 0;
case LED_OFF:
writel(0xf,led_data);想寄存器写入数据,驱动专用函数
return 0;
default:
return -EINVAL;
}
}
int led_open(struct inode *node, struct file *filp) //open中实现硬件初始化
{
led_config = ioremap(GPMCON,4);
writel(0x1111,led_config);
led_data = ioremap(GPMDAT,4);//将寄存器映射为虚拟内存。
return 0;
}
const struct file_operations led_fops =
{
.open = led_open,
.unlocked_ioctl = led_loctl,
};
static int led_init() //模块入口函数
{
cdev_init(&cdev, &led_fops);
alloc_chrdev_region(&devno, 0, 1, "myled");
cdev_add(&cdev, devno, 1);
return 0;
}
static void led_exit() //模块注销
{
cdev_del(&cdev);
unregister_chrdev_region(devno, 1);
}
module_init(led_init);
module_exit(led_exit);
头文件的包含必要的命令:
vim led.h
#define LED_MAGIC ‘l‘ //定义幻数
#define LED_ON _IO(LED_MAGIC,0)
#define LED_OFF _IO(LED_MAGIC,1)
应用程序编写:
vim led_app.c
#include"led.h"
#include<stdio.h>
#include<sys/fcntl.h>
#include<sys/ioctl.h>
#include<sys/stat.h>
#include<sys/types.h>
int main(int argc,char *argv[])
{
int cmd;
int fd;
if(argc<2){
printf("please enter the second para!\n");
return 0;}
cmd = atoi(argv[1]);
fd = open("/dev/myled",O_RDWR);
if(cmd == 1)
ioctl(fd,LED_ON);//设备驱动程序中对设备的I/O通道进行管理的函数。
else
ioctl(fd,LED_OFF);
return 0;}
安装模块,安装设备文件,执行编译好的应用程序。